File:  [LON-CAPA] / loncom / lonnet / perl / lonnet.pm
Revision 1.1522: download - view: text, annotated - select for diffs
Thu Dec 28 18:14:09 2023 UTC (6 months, 2 weeks ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Internal name for conditional portfolio sharing for specific IP addresses
  ranges when set by a user is now userip, to distinguish from those set
  for externalresponse (inrenal name: ip).
- Portfolio shareability setting in domain defaults (by affiliation), with
  possible override for an individual user will apply to portfolio file
  requests to a LON-CAPA node running 2.11, when the file owner's homeserver
  is 2.12 (or later).

    1: # The LearningOnline Network
    2: # TCP networking package
    3: #
    4: # $Id: lonnet.pm,v 1.1522 2023/12/28 18:14:09 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','authordefaults',
 2757:                                   'selfenrollment','coursecategories',
 2758:                                   'ssl','autoenroll','trust',
 2759:                                   'helpsettings','wafproxy',
 2760:                                   'ltisec','toolsec','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','portaccess');
 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{'authordefaults'}) eq 'HASH') {
 2805:         foreach my $item ('nocodemirror','copyright','sourceavail','domcoordacc','editors') {
 2806:             if ($item eq 'editors') {
 2807:                 if (ref($domconfig{'authordefaults'}{'editors'}) eq 'ARRAY') {
 2808:                     $domdefaults{$item} = join(',',@{$domconfig{'authordefaults'}{'editors'}});
 2809:                 }
 2810:             } else {
 2811:                 $domdefaults{$item} = $domconfig{'authordefaults'}{$item};
 2812:             }
 2813:         }
 2814:     }
 2815:     if (ref($domconfig{'inststatus'}) eq 'HASH') {
 2816:         foreach my $item ('inststatustypes','inststatusorder','inststatusguest') {
 2817:             $domdefaults{$item} = $domconfig{'inststatus'}{$item};
 2818:         }
 2819:     }
 2820:     if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
 2821:         $domdefaults{'canuse_pdfforms'} = $domconfig{'coursedefaults'}{'canuse_pdfforms'};
 2822:         $domdefaults{'usejsme'} = $domconfig{'coursedefaults'}{'usejsme'};
 2823:         $domdefaults{'inline_chem'} = $domconfig{'coursedefaults'}{'inline_chem'};
 2824:         $domdefaults{'uselcmath'} = $domconfig{'coursedefaults'}{'uselcmath'};
 2825:         if (ref($domconfig{'coursedefaults'}{'postsubmit'}) eq 'HASH') {
 2826:             $domdefaults{'postsubmit'} = $domconfig{'coursedefaults'}{'postsubmit'}{'client'};
 2827:         }
 2828:         foreach my $type (@coursetypes) {
 2829:             if (ref($domconfig{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
 2830:                 unless ($type eq 'community') {
 2831:                     $domdefaults{$type.'credits'} = $domconfig{'coursedefaults'}{'coursecredits'}{$type};
 2832:                 }
 2833:             }
 2834:             if (ref($domconfig{'coursedefaults'}{'uploadquota'}) eq 'HASH') {
 2835:                 $domdefaults{$type.'quota'} = $domconfig{'coursedefaults'}{'uploadquota'}{$type};
 2836:             }
 2837:             if (ref($domconfig{'coursedefaults'}{'coursequota'}) eq 'HASH') {
 2838:                 $domdefaults{$type.'coursequota'} = $domconfig{'coursedefaults'}{'coursequota'}{$type};
 2839:             }
 2840:             if ($domdefaults{'postsubmit'} eq 'on') {
 2841:                 if (ref($domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}) eq 'HASH') {
 2842:                     $domdefaults{$type.'postsubtimeout'} = 
 2843:                         $domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}{$type}; 
 2844:                 }
 2845:             }
 2846:             if (ref($domconfig{'coursedefaults'}{'domexttool'}) eq 'HASH') {
 2847:                 $domdefaults{$type.'domexttool'} = $domconfig{'coursedefaults'}{'domexttool'}{$type};
 2848:             } else {
 2849:                 $domdefaults{$type.'domexttool'} = 1;
 2850:             }
 2851:             if (ref($domconfig{'coursedefaults'}{'exttool'}) eq 'HASH') {
 2852:                 $domdefaults{$type.'exttool'} = $domconfig{'coursedefaults'}{'exttool'}{$type};
 2853:             } else {
 2854:                 $domdefaults{$type.'exttool'} = 0;
 2855:             }
 2856:             if (ref($domconfig{'coursedefaults'}{'crsauthor'}) eq 'HASH') {
 2857:                 $domdefaults{$type.'crsauthor'} = $domconfig{'coursedefaults'}{'crsauthor'}{$type};
 2858:             } else {
 2859:                 $domdefaults{$type.'crsauthor'} = 1;
 2860:             }
 2861:         }
 2862:         if (ref($domconfig{'coursedefaults'}{'canclone'}) eq 'HASH') {
 2863:             if (ref($domconfig{'coursedefaults'}{'canclone'}{'instcode'}) eq 'ARRAY') {
 2864:                 my @clonecodes = @{$domconfig{'coursedefaults'}{'canclone'}{'instcode'}};
 2865:                 if (@clonecodes) {
 2866:                     $domdefaults{'canclone'} = join('+',@clonecodes);
 2867:                 }
 2868:             }
 2869:         } elsif ($domconfig{'coursedefaults'}{'canclone'}) {
 2870:             $domdefaults{'canclone'}=$domconfig{'coursedefaults'}{'canclone'};
 2871:         }
 2872:         if ($domconfig{'coursedefaults'}{'texengine'}) {
 2873:             $domdefaults{'texengine'} = $domconfig{'coursedefaults'}{'texengine'};
 2874:         }
 2875:         if (exists($domconfig{'coursedefaults'}{'ltiauth'})) {
 2876:             $domdefaults{'crsltiauth'} = $domconfig{'coursedefaults'}{'ltiauth'};
 2877:         }
 2878:     }
 2879:     if (ref($domconfig{'usersessions'}) eq 'HASH') {
 2880:         if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
 2881:             $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
 2882:         }
 2883:         if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
 2884:             $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
 2885:         }
 2886:         if (ref($domconfig{'usersessions'}{'offloadnow'}) eq 'HASH') {
 2887:             $domdefaults{'offloadnow'} = $domconfig{'usersessions'}{'offloadnow'};
 2888:         }
 2889:         if (ref($domconfig{'usersessions'}{'offloadoth'}) eq 'HASH') {
 2890:             $domdefaults{'offloadoth'} = $domconfig{'usersessions'}{'offloadoth'};
 2891:         }
 2892:     }
 2893:     if (ref($domconfig{'selfenrollment'}) eq 'HASH') {
 2894:         if (ref($domconfig{'selfenrollment'}{'admin'}) eq 'HASH') {
 2895:             my @settings = ('types','registered','enroll_dates','access_dates','section',
 2896:                             'approval','limit');
 2897:             foreach my $type (@coursetypes) {
 2898:                 if (ref($domconfig{'selfenrollment'}{'admin'}{$type}) eq 'HASH') {
 2899:                     my @mgrdc = ();
 2900:                     foreach my $item (@settings) {
 2901:                         if ($domconfig{'selfenrollment'}{'admin'}{$type}{$item} eq '0') {
 2902:                             push(@mgrdc,$item);
 2903:                         }
 2904:                     }
 2905:                     if (@mgrdc) {
 2906:                         $domdefaults{$type.'selfenrolladmdc'} = join(',',@mgrdc);
 2907:                     }
 2908:                 }
 2909:             }
 2910:         }
 2911:         if (ref($domconfig{'selfenrollment'}{'default'}) eq 'HASH') {
 2912:             foreach my $type (@coursetypes) {
 2913:                 if (ref($domconfig{'selfenrollment'}{'default'}{$type}) eq 'HASH') {
 2914:                     foreach my $item (keys(%{$domconfig{'selfenrollment'}{'default'}{$type}})) {
 2915:                         $domdefaults{$type.'selfenroll'.$item} = $domconfig{'selfenrollment'}{'default'}{$type}{$item};
 2916:                     }
 2917:                 }
 2918:             }
 2919:         }
 2920:     }
 2921:     if (ref($domconfig{'coursecategories'}) eq 'HASH') {
 2922:         $domdefaults{'catauth'} = 'std';
 2923:         $domdefaults{'catunauth'} = 'std';
 2924:         if ($domconfig{'coursecategories'}{'auth'}) {
 2925:             $domdefaults{'catauth'} = $domconfig{'coursecategories'}{'auth'};
 2926:         }
 2927:         if ($domconfig{'coursecategories'}{'unauth'}) {
 2928:             $domdefaults{'catunauth'} = $domconfig{'coursecategories'}{'unauth'};
 2929:         }
 2930:     }
 2931:     if (ref($domconfig{'ssl'}) eq 'HASH') {
 2932:         if (ref($domconfig{'ssl'}{'replication'}) eq 'HASH') {
 2933:             $domdefaults{'replication'} = $domconfig{'ssl'}{'replication'};
 2934:         }
 2935:         if (ref($domconfig{'ssl'}{'connto'}) eq 'HASH') {
 2936:             $domdefaults{'connect'} = $domconfig{'ssl'}{'connto'};
 2937:         }
 2938:         if (ref($domconfig{'ssl'}{'connfrom'}) eq 'HASH') {
 2939:             $domdefaults{'connect'} = $domconfig{'ssl'}{'connfrom'};
 2940:         }
 2941:     }
 2942:     if (ref($domconfig{'trust'}) eq 'HASH') {
 2943:         my @prefixes = qw(content shared enroll othcoau coaurem domroles catalog reqcrs msg);
 2944:         foreach my $prefix (@prefixes) {
 2945:             if (ref($domconfig{'trust'}{$prefix}) eq 'HASH') {
 2946:                 $domdefaults{'trust'.$prefix} = $domconfig{'trust'}{$prefix};
 2947:             }
 2948:         }
 2949:     }
 2950:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
 2951:         $domdefaults{'autofailsafe'} = $domconfig{'autoenroll'}{'autofailsafe'};
 2952:         $domdefaults{'failsafe'} = $domconfig{'autoenroll'}{'failsafe'};
 2953:     }
 2954:     if (ref($domconfig{'helpsettings'}) eq 'HASH') {
 2955:         $domdefaults{'submitbugs'} = $domconfig{'helpsettings'}{'submitbugs'};
 2956:         if (ref($domconfig{'helpsettings'}{'adhoc'}) eq 'HASH') {
 2957:             $domdefaults{'adhocroles'} = $domconfig{'helpsettings'}{'adhoc'};
 2958:         }
 2959:     }
 2960:     if (ref($domconfig{'wafproxy'}) eq 'HASH') {
 2961:         foreach my $item ('ipheader','trusted','vpnint','vpnext','sslopt') {
 2962:             if ($domconfig{'wafproxy'}{$item}) {
 2963:                 $domdefaults{'waf_'.$item} = $domconfig{'wafproxy'}{$item};
 2964:             }
 2965:         }
 2966:     }
 2967:     if (ref($domconfig{'ltisec'}) eq 'HASH') {
 2968:         if (ref($domconfig{'ltisec'}{'encrypt'}) eq 'HASH') {
 2969:             $domdefaults{'linkprotenc_crs'} = $domconfig{'ltisec'}{'encrypt'}{'crs'};
 2970:             $domdefaults{'linkprotenc_dom'} = $domconfig{'ltisec'}{'encrypt'}{'dom'};
 2971:             $domdefaults{'ltienc_consumers'} = $domconfig{'ltisec'}{'encrypt'}{'consumers'};
 2972:         }
 2973:         if (ref($domconfig{'ltisec'}{'private'}) eq 'HASH') {
 2974:             if (ref($domconfig{'ltisec'}{'private'}{'keys'}) eq 'ARRAY') {
 2975:                 $domdefaults{'ltiprivhosts'} = $domconfig{'ltisec'}{'private'}{'keys'};
 2976:             }
 2977:         }
 2978:     }
 2979:     if (ref($domconfig{'toolsec'}) eq 'HASH') {
 2980:         if (ref($domconfig{'toolsec'}{'encrypt'}) eq 'HASH') {
 2981:             $domdefaults{'toolenc_crs'} = $domconfig{'toolsec'}{'encrypt'}{'crs'};
 2982:             $domdefaults{'toolenc_dom'} = $domconfig{'toolsec'}{'encrypt'}{'dom'};
 2983:         }
 2984:         if (ref($domconfig{'toolsec'}{'private'}) eq 'HASH') {
 2985:             if (ref($domconfig{'toolsec'}{'private'}{'keys'}) eq 'ARRAY') {
 2986:                 $domdefaults{'toolprivhosts'} = $domconfig{'toolsec'}{'private'}{'keys'};
 2987:             }
 2988:         }
 2989:     }
 2990:     if (ref($domconfig{'privacy'}) eq 'HASH') {
 2991:         if (ref($domconfig{'privacy'}{'approval'}) eq 'HASH') {
 2992:             foreach my $domtype ('instdom','extdom') {
 2993:                 if (ref($domconfig{'privacy'}{'approval'}{$domtype}) eq 'HASH') {
 2994:                     foreach my $roletype ('domain','author','course','community') {
 2995:                         if ($domconfig{'privacy'}{'approval'}{$domtype}{$roletype} eq 'user') {
 2996:                             $domdefaults{'userapprovals'} = 1;
 2997:                             last;
 2998:                         }
 2999:                     }
 3000:                 }
 3001:                 last if ($domdefaults{'userapprovals'});
 3002:             }
 3003:         }
 3004:     }
 3005:     &do_cache_new('domdefaults',$domain,\%domdefaults,$cachetime);
 3006:     return %domdefaults;
 3007: }
 3008: 
 3009: sub get_dom_cats {
 3010:     my ($dom) = @_;
 3011:     return unless (&domain($dom));
 3012:     my ($cats,$cached)=&is_cached_new('cats',$dom);
 3013:     unless (defined($cached)) {
 3014:         my %domconfig = &get_dom('configuration',['coursecategories'],$dom);
 3015:         if (ref($domconfig{'coursecategories'}) eq 'HASH') {
 3016:             if (ref($domconfig{'coursecategories'}{'cats'}) eq 'HASH') {
 3017:                 %{$cats} = %{$domconfig{'coursecategories'}{'cats'}};
 3018:             } else {
 3019:                 $cats = {};
 3020:             }
 3021:         } else {
 3022:             $cats = {};
 3023:         }
 3024:         &do_cache_new('cats',$dom,$cats,3600);
 3025:     }
 3026:     return $cats;
 3027: }
 3028: 
 3029: sub get_dom_instcats {
 3030:     my ($dom) = @_;
 3031:     return unless (&domain($dom));
 3032:     my ($instcats,$cached)=&is_cached_new('instcats',$dom);
 3033:     unless (defined($cached)) {
 3034:         my (%coursecodes,%codes,@codetitles,%cat_titles,%cat_order);
 3035:         my $totcodes = &retrieve_instcodes(\%coursecodes,$dom);
 3036:         if ($totcodes > 0) {
 3037:             my $caller = 'global';
 3038:             if (&auto_instcode_format($caller,$dom,\%coursecodes,\%codes,
 3039:                                       \@codetitles,\%cat_titles,\%cat_order) eq 'ok') {
 3040:                 $instcats = {
 3041:                                 totcodes => $totcodes,
 3042:                                 codes => \%codes,
 3043:                                 codetitles => \@codetitles,
 3044:                                 cat_titles => \%cat_titles,
 3045:                                 cat_order => \%cat_order,
 3046:                             };
 3047:                 &do_cache_new('instcats',$dom,$instcats,3600);
 3048:             }
 3049:         }
 3050:     }
 3051:     return $instcats;
 3052: }
 3053: 
 3054: sub retrieve_instcodes {
 3055:     my ($coursecodes,$dom) = @_;
 3056:     my $totcodes;
 3057:     my %courses = &courseiddump($dom,'.',1,'.','.','.',undef,undef,'Course');
 3058:     foreach my $course (keys(%courses)) {
 3059:         if (ref($courses{$course}) eq 'HASH') {
 3060:             if ($courses{$course}{'inst_code'} ne '') {
 3061:                 $$coursecodes{$course} = $courses{$course}{'inst_code'};
 3062:                 $totcodes ++;
 3063:             }
 3064:         }
 3065:     }
 3066:     return $totcodes;
 3067: }
 3068: 
 3069: sub course_portal_url {
 3070:     my ($cnum,$cdom,$r) = @_;
 3071:     my $chome = &homeserver($cnum,$cdom);
 3072:     my $hostname = &hostname($chome);
 3073:     my $protocol = $protocol{$chome};
 3074:     $protocol = 'http' if ($protocol ne 'https');
 3075:     my %domdefaults = &get_domain_defaults($cdom);
 3076:     my $firsturl;
 3077:     if ($domdefaults{'portal_def'}) {
 3078:         $firsturl = $domdefaults{'portal_def'};
 3079:     } else {
 3080:         my $alias = &use_proxy_alias($r,$chome);
 3081:         $hostname = $alias if ($alias ne '');
 3082:         $firsturl = $protocol.'://'.$hostname;
 3083:     }
 3084:     return $firsturl;
 3085: }
 3086: 
 3087: sub url_prefix {
 3088:     my ($r,$dom,$home,$context) = @_;
 3089:     my $prefix;
 3090:     my %domdefs = &get_domain_defaults($dom);
 3091:     if ($domdefs{'portal_def'} && $domdefs{'portal_def_'.$context}) {
 3092:         if ($domdefs{'portal_def'} =~ m{^(https?://[^/]+)}) {
 3093:             $prefix = $1;
 3094:         }
 3095:     }
 3096:     if ($prefix eq '') {
 3097:         my $hostname = &hostname($home);
 3098:         my $protocol = $protocol{$home};
 3099:         $protocol = 'http' if ($protocol{$home} ne 'https');
 3100:         my $alias = &use_proxy_alias($r,$home);
 3101:         $hostname = $alias if ($alias ne '');
 3102:         $prefix = $protocol.'://'.$hostname;
 3103:     }
 3104:     return $prefix;
 3105: }
 3106: 
 3107: # --------------------------------------------- Get domain config for passwords
 3108: 
 3109: sub get_passwdconf {
 3110:     my ($dom) = @_;
 3111:     my (%passwdconf,$gotconf,$lookup);
 3112:     my ($result,$cached)=&is_cached_new('passwdconf',$dom);
 3113:     if (defined($cached)) {
 3114:         if (ref($result) eq 'HASH') {
 3115:             %passwdconf = %{$result};
 3116:             $gotconf = 1;
 3117:         }
 3118:     }
 3119:     unless ($gotconf) {
 3120:         my %domconfig = &get_dom('configuration',['passwords'],$dom);
 3121:         if (ref($domconfig{'passwords'}) eq 'HASH') {
 3122:             %passwdconf = %{$domconfig{'passwords'}};
 3123:         }
 3124:         my $cachetime = 24*60*60;
 3125:         &do_cache_new('passwdconf',$dom,\%passwdconf,$cachetime);
 3126:     }
 3127:     return %passwdconf;
 3128: }
 3129: 
 3130: # --------------------------------------------------- Assign a key to a student
 3131: 
 3132: sub assign_access_key {
 3133: #
 3134: # a valid key looks like uname:udom#comments
 3135: # comments are being appended
 3136: #
 3137:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
 3138:     $kdom=
 3139:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
 3140:     $knum=
 3141:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
 3142:     $cdom=
 3143:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 3144:     $cnum=
 3145:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 3146:     $udom=$env{'user.name'} unless (defined($udom));
 3147:     $uname=$env{'user.domain'} unless (defined($uname));
 3148:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
 3149:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
 3150:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
 3151:                                                   # assigned to this person
 3152:                                                   # - this should not happen,
 3153:                                                   # unless something went wrong
 3154:                                                   # the first time around
 3155: # ready to assign
 3156:         $logentry=$1.'; '.$logentry;
 3157:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
 3158:                                                  $kdom,$knum) eq 'ok') {
 3159: # key now belongs to user
 3160: 	    my $envkey='key.'.$cdom.'_'.$cnum;
 3161:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
 3162:                 &appenv({'environment.'.$envkey => $ckey});
 3163:                 return 'ok';
 3164:             } else {
 3165:                 return 
 3166:   'error: Count not permanently assign key, will need to be re-entered later.';
 3167: 	    }
 3168:         } else {
 3169:             return 'error: Could not assign key, try again later.';
 3170:         }
 3171:     } elsif (!$existing{$ckey}) {
 3172: # the key does not exist
 3173: 	return 'error: The key does not exist';
 3174:     } else {
 3175: # the key is somebody else's
 3176: 	return 'error: The key is already in use';
 3177:     }
 3178: }
 3179: 
 3180: # ------------------------------------------ put an additional comment on a key
 3181: 
 3182: sub comment_access_key {
 3183: #
 3184: # a valid key looks like uname:udom#comments
 3185: # comments are being appended
 3186: #
 3187:     my ($ckey,$cdom,$cnum,$logentry)=@_;
 3188:     $cdom=
 3189:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 3190:     $cnum=
 3191:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 3192:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
 3193:     if ($existing{$ckey}) {
 3194:         $existing{$ckey}.='; '.$logentry;
 3195: # ready to assign
 3196:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
 3197:                                                  $cdom,$cnum) eq 'ok') {
 3198: 	    return 'ok';
 3199:         } else {
 3200: 	    return 'error: Count not store comment.';
 3201:         }
 3202:     } else {
 3203: # the key does not exist
 3204: 	return 'error: The key does not exist';
 3205:     }
 3206: }
 3207: 
 3208: # ------------------------------------------------------ Generate a set of keys
 3209: 
 3210: sub generate_access_keys {
 3211:     my ($number,$cdom,$cnum,$logentry)=@_;
 3212:     $cdom=
 3213:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 3214:     $cnum=
 3215:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 3216:     unless (&allowed('mky',$cdom)) { return 0; }
 3217:     unless (($cdom) && ($cnum)) { return 0; }
 3218:     if ($number>10000) { return 0; }
 3219:     sleep(2); # make sure don't get same seed twice
 3220:     srand(time()^($$+($$<<15))); # from "Programming Perl"
 3221:     my $total=0;
 3222:     for (my $i=1;$i<=$number;$i++) {
 3223:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
 3224:                   sprintf("%lx",int(100000*rand)).'-'.
 3225:                   sprintf("%lx",int(100000*rand));
 3226:        $newkey=~s/1/g/g; # folks mix up 1 and l
 3227:        $newkey=~s/0/h/g; # and also 0 and O
 3228:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
 3229:        if ($existing{$newkey}) {
 3230:            $i--;
 3231:        } else {
 3232: 	  if (&put('accesskeys',
 3233:               { $newkey => '# generated '.localtime().
 3234:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
 3235:                            '; '.$logentry },
 3236: 		   $cdom,$cnum) eq 'ok') {
 3237:               $total++;
 3238: 	  }
 3239:        }
 3240:     }
 3241:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
 3242:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
 3243:     return $total;
 3244: }
 3245: 
 3246: # ------------------------------------------------------- Validate an accesskey
 3247: 
 3248: sub validate_access_key {
 3249:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
 3250:     $cdom=
 3251:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 3252:     $cnum=
 3253:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 3254:     $udom=$env{'user.domain'} unless (defined($udom));
 3255:     $uname=$env{'user.name'} unless (defined($uname));
 3256:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
 3257:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
 3258: }
 3259: 
 3260: # ------------------------------------- Find the section of student in a course
 3261: sub devalidate_getsection_cache {
 3262:     my ($udom,$unam,$courseid)=@_;
 3263:     my $hashid="$udom:$unam:$courseid";
 3264:     &devalidate_cache_new('getsection',$hashid);
 3265: }
 3266: 
 3267: sub courseid_to_courseurl {
 3268:     my ($courseid) = @_;
 3269:     #already url style courseid
 3270:     return $courseid if ($courseid =~ m{^/});
 3271: 
 3272:     if (exists($env{'course.'.$courseid.'.num'})) {
 3273: 	my $cnum = $env{'course.'.$courseid.'.num'};
 3274: 	my $cdom = $env{'course.'.$courseid.'.domain'};
 3275: 	return "/$cdom/$cnum";
 3276:     }
 3277: 
 3278:     my %courseinfo=&coursedescription($courseid);
 3279:     if (exists($courseinfo{'num'})) {
 3280: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
 3281:     }
 3282: 
 3283:     return undef;
 3284: }
 3285: 
 3286: sub getsection {
 3287:     my ($udom,$unam,$courseid)=@_;
 3288:     my $cachetime=1800;
 3289: 
 3290:     my $hashid="$udom:$unam:$courseid";
 3291:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
 3292:     if (defined($cached)) { return $result; }
 3293: 
 3294:     my %Pending; 
 3295:     my %Expired;
 3296:     #
 3297:     # Each role can either have not started yet (pending), be active, 
 3298:     #    or have expired.
 3299:     #
 3300:     # If there is an active role, we are done.
 3301:     #
 3302:     # If there is more than one role which has not started yet, 
 3303:     #     choose the one which will start sooner
 3304:     # If there is one role which has not started yet, return it.
 3305:     #
 3306:     # If there is more than one expired role, choose the one which ended last.
 3307:     # If there is a role which has expired, return it.
 3308:     #
 3309:     $courseid = &courseid_to_courseurl($courseid);
 3310:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
 3311:     foreach my $key (keys(%roleshash)) {
 3312:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
 3313:         my $section=$1;
 3314:         if ($key eq $courseid.'_st') { $section=''; }
 3315:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
 3316:         my $now=time;
 3317:         if (defined($end) && $end && ($now > $end)) {
 3318:             $Expired{$end}=$section;
 3319:             next;
 3320:         }
 3321:         if (defined($start) && $start && ($now < $start)) {
 3322:             $Pending{$start}=$section;
 3323:             next;
 3324:         }
 3325:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
 3326:     }
 3327:     #
 3328:     # Presumedly there will be few matching roles from the above
 3329:     # loop and the sorting time will be negligible.
 3330:     if (scalar(keys(%Pending))) {
 3331:         my ($time) = sort {$a <=> $b} keys(%Pending);
 3332:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
 3333:     } 
 3334:     if (scalar(keys(%Expired))) {
 3335:         my @sorted = sort {$a <=> $b} keys(%Expired);
 3336:         my $time = pop(@sorted);
 3337:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
 3338:     }
 3339:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
 3340: }
 3341: 
 3342: sub save_cache {
 3343:     &purge_remembered();
 3344:     #&Apache::loncommon::validate_page();
 3345:     undef(%env);
 3346:     undef($env_loaded);
 3347: }
 3348: 
 3349: my $to_remember=-1;
 3350: my %remembered;
 3351: my %accessed;
 3352: my $kicks=0;
 3353: my $hits=0;
 3354: sub make_key {
 3355:     my ($name,$id) = @_;
 3356:     if (length($id) > 65 
 3357: 	&& length(&escape($id)) > 200) {
 3358: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
 3359:     }
 3360:     return &escape($name.':'.$id);
 3361: }
 3362: 
 3363: sub devalidate_cache_new {
 3364:     my ($name,$id,$debug) = @_;
 3365:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
 3366:     my $remembered_id=$name.':'.$id;
 3367:     $id=&make_key($name,$id);
 3368:     $memcache->delete($id);
 3369:     delete($remembered{$remembered_id});
 3370:     delete($accessed{$remembered_id});
 3371: }
 3372: 
 3373: sub is_cached_new {
 3374:     my ($name,$id,$debug) = @_;
 3375:     my $remembered_id=$name.':'.$id; # this is to avoid make_key (which is slow) whenever possible
 3376:     if (exists($remembered{$remembered_id})) {
 3377: 	if ($debug) { &Apache::lonnet::logthis("Early return $remembered_id of $remembered{$remembered_id} "); }
 3378: 	$accessed{$remembered_id}=[&gettimeofday()];
 3379: 	$hits++;
 3380: 	return ($remembered{$remembered_id},1);
 3381:     }
 3382:     $id=&make_key($name,$id);
 3383:     my $value = $memcache->get($id);
 3384:     if (!(defined($value))) {
 3385: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
 3386: 	return (undef,undef);
 3387:     }
 3388:     if ($value eq '__undef__') {
 3389: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
 3390: 	$value=undef;
 3391:     }
 3392:     &make_room($remembered_id,$value,$debug);
 3393:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
 3394:     return ($value,1);
 3395: }
 3396: 
 3397: sub do_cache_new {
 3398:     my ($name,$id,$value,$time,$debug) = @_;
 3399:     my $remembered_id=$name.':'.$id;
 3400:     $id=&make_key($name,$id);
 3401:     my $setvalue=$value;
 3402:     if (!defined($setvalue)) {
 3403: 	$setvalue='__undef__';
 3404:     }
 3405:     if (!defined($time) ) {
 3406: 	$time=600;
 3407:     }
 3408:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
 3409:     my $result = $memcache->set($id,$setvalue,$time);
 3410:     if (! $result) {
 3411: 	&logthis("caching of id -> $id  failed");
 3412: 	$memcache->disconnect_all();
 3413:     }
 3414:     # need to make a copy of $value
 3415:     &make_room($remembered_id,$value,$debug);
 3416:     return $value;
 3417: }
 3418: 
 3419: sub make_room {
 3420:     my ($remembered_id,$value,$debug)=@_;
 3421: 
 3422:     $remembered{$remembered_id}= (ref($value)) ? &Storable::dclone($value)
 3423:                                     : $value;
 3424:     if ($to_remember<0) { return; }
 3425:     $accessed{$remembered_id}=[&gettimeofday()];
 3426:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
 3427:     my $to_kick;
 3428:     my $max_time=0;
 3429:     foreach my $other (keys(%accessed)) {
 3430: 	if (&tv_interval($accessed{$other}) > $max_time) {
 3431: 	    $to_kick=$other;
 3432: 	    $max_time=&tv_interval($accessed{$other});
 3433: 	}
 3434:     }
 3435:     delete($remembered{$to_kick});
 3436:     delete($accessed{$to_kick});
 3437:     $kicks++;
 3438:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
 3439:     return;
 3440: }
 3441: 
 3442: sub purge_remembered {
 3443:     #&logthis("Tossing ".scalar(keys(%remembered)));
 3444:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
 3445:     undef(%remembered);
 3446:     undef(%accessed);
 3447: }
 3448: # ------------------------------------- Read an entry from a user's environment
 3449: 
 3450: sub userenvironment {
 3451:     my ($udom,$unam,@what)=@_;
 3452:     my $items;
 3453:     foreach my $item (@what) {
 3454:         $items.=&escape($item).'&';
 3455:     }
 3456:     $items=~s/\&$//;
 3457:     my %returnhash=();
 3458:     my $uhome = &homeserver($unam,$udom);
 3459:     unless ($uhome eq 'no_host') {
 3460:         my @answer=split(/\&/, 
 3461:             &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
 3462:         if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
 3463:             return %returnhash;
 3464:         }
 3465:         my $i;
 3466:         for ($i=0;$i<=$#what;$i++) {
 3467: 	    $returnhash{$what[$i]}=&unescape($answer[$i]);
 3468:         }
 3469:     }
 3470:     return %returnhash;
 3471: }
 3472: 
 3473: # ---------------------------------------------------------- Get a studentphoto
 3474: sub studentphoto {
 3475:     my ($udom,$unam,$ext) = @_;
 3476:     my $home=&homeserver($unam,$udom);
 3477:     if (defined($env{'request.course.id'})) {
 3478:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
 3479:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
 3480:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
 3481:             } else {
 3482:                 my ($result,$perm_reqd)=
 3483: 		    &auto_photo_permission($unam,$udom);
 3484:                 if ($result eq 'ok') {
 3485:                     if (!($perm_reqd eq 'yes')) {
 3486:                         return(&retrievestudentphoto($udom,$unam,$ext));
 3487:                     }
 3488:                 }
 3489:             }
 3490:         }
 3491:     } else {
 3492:         my ($result,$perm_reqd) = 
 3493: 	    &auto_photo_permission($unam,$udom);
 3494:         if ($result eq 'ok') {
 3495:             if (!($perm_reqd eq 'yes')) {
 3496:                 return(&retrievestudentphoto($udom,$unam,$ext));
 3497:             }
 3498:         }
 3499:     }
 3500:     return '/adm/lonKaputt/lonlogo_broken.gif';
 3501: }
 3502: 
 3503: sub retrievestudentphoto {
 3504:     my ($udom,$unam,$ext,$type) = @_;
 3505:     my $home=&homeserver($unam,$udom);
 3506:     my $ret=&reply("studentphoto:$udom:$unam:$ext:$type",$home);
 3507:     if ($ret eq 'ok') {
 3508:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
 3509:         if ($type eq 'thumbnail') {
 3510:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
 3511:         }
 3512:         my $tokenurl=&tokenwrapper($url);
 3513:         return $tokenurl;
 3514:     } else {
 3515:         if ($type eq 'thumbnail') {
 3516:             return '/adm/lonKaputt/genericstudent_tn.gif';
 3517:         } else { 
 3518:             return '/adm/lonKaputt/lonlogo_broken.gif';
 3519:         }
 3520:     }
 3521: }
 3522: 
 3523: # -------------------------------------------------------------------- New chat
 3524: 
 3525: sub chatsend {
 3526:     my ($newentry,$anon,$group)=@_;
 3527:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
 3528:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 3529:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
 3530:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
 3531: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
 3532: 		   &escape($newentry)).':'.$group,$chome);
 3533: }
 3534: 
 3535: # ------------------------------------------ Find current version of a resource
 3536: 
 3537: sub getversion {
 3538:     my $fname=&clutter(shift);
 3539:     unless ($fname=~m{^(/adm/wrapper|)/res/}) { return -1; }
 3540:     return &currentversion(&filelocation('',$fname));
 3541: }
 3542: 
 3543: sub currentversion {
 3544:     my $fname=shift;
 3545:     my $author=$fname;
 3546:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 3547:     my ($udom,$uname)=split(/\//,$author);
 3548:     my $home=&homeserver($uname,$udom);
 3549:     if ($home eq 'no_host') { 
 3550:         return -1; 
 3551:     }
 3552:     my $answer=&reply("currentversion:$fname",$home);
 3553:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
 3554: 	return -1;
 3555:     }
 3556:     return $answer;
 3557: }
 3558: 
 3559: #
 3560: # Return special version number of resource if set by override, empty otherwise
 3561: #
 3562: sub usedversion {
 3563:     my $fname=shift;
 3564:     unless ($fname) { $fname=$env{'request.uri'}; }
 3565:     my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
 3566:     if ($urlversion) { return $urlversion; }
 3567:     return '';
 3568: }
 3569: 
 3570: # ----------------------------- Subscribe to a resource, return URL if possible
 3571: 
 3572: sub subscribe {
 3573:     my $fname=shift;
 3574:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
 3575:     $fname=~s/[\n\r]//g;
 3576:     my $author=$fname;
 3577:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 3578:     my ($udom,$uname)=split(/\//,$author);
 3579:     my $home=homeserver($uname,$udom);
 3580:     if ($home eq 'no_host') {
 3581:         return 'not_found';
 3582:     }
 3583:     my $answer=reply("sub:$fname",$home);
 3584:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
 3585: 	$answer.=' by '.$home;
 3586:     }
 3587:     return $answer;
 3588: }
 3589:     
 3590: # -------------------------------------------------------------- Replicate file
 3591: 
 3592: sub repcopy {
 3593:     my $filename=shift;
 3594:     $filename=~s/\/+/\//g;
 3595:     my $londocroot = $perlvar{'lonDocRoot'};
 3596:     if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
 3597:     if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
 3598:     if ($filename=~m{^\Q$londocroot/userfiles/\E} or
 3599: 	$filename=~m{^/*(uploaded|editupload)/}) {
 3600: 	return &repcopy_userfile($filename);
 3601:     }
 3602:     $filename=~s/[\n\r]//g;
 3603:     my $transname="$filename.in.transfer";
 3604: # FIXME: this should flock
 3605:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
 3606:     my $remoteurl=subscribe($filename);
 3607:     if ($remoteurl =~ /^con_lost by/) {
 3608: 	   &logthis("Subscribe returned $remoteurl: $filename");
 3609:            return 'unavailable';
 3610:     } elsif ($remoteurl eq 'not_found') {
 3611: 	   #&logthis("Subscribe returned not_found: $filename");
 3612: 	   return 'not_found';
 3613:     } elsif ($remoteurl =~ /^rejected by/) {
 3614: 	   &logthis("Subscribe returned $remoteurl: $filename");
 3615:            return 'forbidden';
 3616:     } elsif ($remoteurl eq 'directory') {
 3617:            return 'ok';
 3618:     } else {
 3619:         my $author=$filename;
 3620:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 3621:         my ($udom,$uname)=split(/\//,$author);
 3622:         my $home=homeserver($uname,$udom);
 3623:         unless ($home eq $perlvar{'lonHostID'}) {
 3624:            my @parts=split(/\//,$filename);
 3625:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
 3626:            if ($path ne "$londocroot/res") {
 3627:                &logthis("Malconfiguration for replication: $filename");
 3628: 	       return 'bad_request';
 3629:            }
 3630:            my $count;
 3631:            for ($count=5;$count<$#parts;$count++) {
 3632:                $path.="/$parts[$count]";
 3633:                if ((-e $path)!=1) {
 3634: 		   mkdir($path,0777);
 3635:                }
 3636:            }
 3637:            my $request=new HTTP::Request('GET',"$remoteurl");
 3638:            my $response;
 3639:            if ($remoteurl =~ m{/raw/}) {
 3640:                $response=&LONCAPA::LWPReq::makerequest($home,$request,$transname,\%perlvar,'',0,1);
 3641:            } else {
 3642:                $response=&LONCAPA::LWPReq::makerequest($home,$request,$transname,\%perlvar,'',1);
 3643:            }
 3644:            if ($response->is_error()) {
 3645: 	       unlink($transname);
 3646:                my $message=$response->status_line;
 3647:                &logthis("<font color=\"blue\">WARNING:"
 3648:                        ." LWP get: $message: $filename</font>");
 3649:                return 'unavailable';
 3650:            } else {
 3651: 	       if ($remoteurl!~/\.meta$/) {
 3652:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
 3653:                   my $mresponse;
 3654:                   if ($remoteurl =~ m{/raw/}) {
 3655:                       $mresponse = &LONCAPA::LWPReq::makerequest($home,$mrequest,$filename.'.meta',\%perlvar,'',0,1);
 3656:                   } else {
 3657:                       $mresponse = &LONCAPA::LWPReq::makerequest($home,$mrequest,$filename.'.meta',\%perlvar,'',1);
 3658:                   }
 3659:                   if ($mresponse->is_error()) {
 3660: 		      unlink($filename.'.meta');
 3661:                       &logthis(
 3662:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
 3663:                   }
 3664: 	       }
 3665:                rename($transname,$filename);
 3666:                return 'ok';
 3667:            }
 3668:        }
 3669:     }
 3670: }
 3671: 
 3672: # ------------------------------------------------- Unsubscribe from a resource
 3673: 
 3674: sub unsubscribe {
 3675:     my ($fname) = @_;
 3676:     my $answer;
 3677:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return $answer; }
 3678:     $fname=~s/[\n\r]//g;
 3679:     my $author=$fname;
 3680:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 3681:     my ($udom,$uname)=split(/\//,$author);
 3682:     my $home=homeserver($uname,$udom);
 3683:     if ($home eq 'no_host') {
 3684:         $answer = 'no_host';
 3685:     } elsif (grep { $_ eq $home } &current_machine_ids()) {
 3686:         $answer = 'home';
 3687:     } else {
 3688:         my $defdom = $perlvar{'lonDefDomain'};
 3689:         if (&will_trust('content',$defdom,$udom)) {
 3690:             $answer = reply("unsub:$fname",$home);
 3691:         } else {
 3692:             $answer = 'untrusted';
 3693:         }
 3694:     }
 3695:     return $answer;
 3696: }
 3697: 
 3698: # ------------------------------------------------ Get server side include body
 3699: sub ssi_body {
 3700:     my ($filelink,%form)=@_;
 3701:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
 3702:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
 3703:     }
 3704:     my $output='';
 3705:     my $response;
 3706:     if ($filelink=~/^https?\:/) {
 3707:        ($output,$response)=&externalssi($filelink);
 3708:     } else {
 3709:        $filelink .= $filelink=~/\?/ ? '&' : '?';
 3710:        $filelink .= 'inhibitmenu=yes';
 3711:        ($output,$response)=&ssi($filelink,%form);
 3712:     }
 3713:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
 3714:     $output=~s/^.*?\<body[^\>]*\>//si;
 3715:     $output=~s/\<\/body\s*\>.*?$//si;
 3716:     if (wantarray) {
 3717:         return ($output, $response);
 3718:     } else {
 3719:         return $output;
 3720:     }
 3721: }
 3722: 
 3723: # --------------------------------------------------------- Server Side Include
 3724: 
 3725: sub absolute_url {
 3726:     my ($host_name,$unalias,$keep_proto) = @_;
 3727:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
 3728:     if ($host_name eq '') {
 3729: 	$host_name = $ENV{'SERVER_NAME'};
 3730:     }
 3731:     if ($unalias) {
 3732:         my $alias = &get_proxy_alias();
 3733:         if ($alias eq $host_name) {
 3734:             my $lonhost = $perlvar{'lonHostID'};
 3735:             my $hostname = &hostname($lonhost);
 3736:             my $lcproto; 
 3737:             if (($keep_proto) || ($hostname eq '')) {
 3738:                 $lcproto = $protocol;
 3739:             } else {
 3740:                 $lcproto = $protocol{$lonhost};
 3741:                 $lcproto = 'http' if ($lcproto ne 'https');
 3742:                 $lcproto .= '://';
 3743:             }
 3744:             unless ($hostname eq '') {
 3745:                 return $lcproto.$hostname;
 3746:             }
 3747:         }
 3748:     }
 3749:     return $protocol.$host_name;
 3750: }
 3751: 
 3752: #
 3753: #   Server side include.
 3754: # Parameters:
 3755: #  fn     Possibly encrypted resource name/id.
 3756: #  form   Hash that describes how the rendering should be done
 3757: #         and other things.
 3758: # Returns:
 3759: #   Scalar context: The content of the response.
 3760: #   Array context:  2 element list of the content and the full response object.
 3761: #     
 3762: sub ssi {
 3763: 
 3764:     my ($fn,%form)=@_;
 3765:     my ($host,$request,$response);
 3766:     $host = &absolute_url('',1);
 3767: 
 3768:     $form{'no_update_last_known'}=1;
 3769:     &Apache::lonenc::check_encrypt(\$fn);
 3770:     if (%form) {
 3771:       $request=new HTTP::Request('POST',$host.$fn);
 3772:       $request->content(join('&',map { 
 3773:             my $name = escape($_);
 3774:             "$name=" . ( ref($form{$_}) eq 'ARRAY' 
 3775:             ? join("&$name=", map {escape($_) } @{$form{$_}}) 
 3776:             : &escape($form{$_}) );    
 3777:         } keys(%form)));
 3778:     } else {
 3779:       $request=new HTTP::Request('GET',$host.$fn);
 3780:     }
 3781: 
 3782:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
 3783:     my $lonhost = $perlvar{'lonHostID'};
 3784:     my $islocal;
 3785:     if (($env{'request.course.id'}) &&
 3786:         ($form{'grade_courseid'} eq $env{'request.course.id'}) &&
 3787:         ($form{'grade_username'} ne '') && ($form{'grade_domain'} ne '') &&
 3788:         ($form{'grade_symb'} ne '') &&
 3789:         (&allowed('mgr',$env{'request.course.id'}.
 3790:                         ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:'')))) {
 3791:         $islocal = 1;
 3792:     }
 3793:     $response= &LONCAPA::LWPReq::makerequest($lonhost,$request,'',\%perlvar,
 3794:                                              '','','',$islocal);
 3795: 
 3796:     if (wantarray) {
 3797: 	return ($response->content, $response);
 3798:     } else {
 3799: 	return $response->content;
 3800:     }
 3801: }
 3802: 
 3803: sub externalssi {
 3804:     my ($url)=@_;
 3805:     my $request=new HTTP::Request('GET',$url);
 3806:     my $response = &LONCAPA::LWPReq::makerequest('',$request,'',\%perlvar);
 3807:     if (wantarray) {
 3808:         return ($response->content, $response);
 3809:     } else {
 3810:         return $response->content;
 3811:     }
 3812: }
 3813: 
 3814: 
 3815: # If the local copy of a replicated resource is outdated, trigger a  
 3816: # connection from the homeserver to flush the delayed queue. If no update 
 3817: # happens, remove local copies of outdated resource (and corresponding
 3818: # metadata file).
 3819: 
 3820: sub remove_stale_resfile {
 3821:     my ($url) = @_;
 3822:     my $removed;
 3823:     if ($url=~m{^/res/($match_domain)/($match_username)/}) {
 3824:         my $audom = $1;
 3825:         my $auname = $2;
 3826:         unless (($url =~ /\.\d+\.\w+$/) || ($url =~ m{^/res/lib/templates/})) {
 3827:             my $homeserver = &homeserver($auname,$audom);
 3828:             unless (($homeserver eq 'no_host') ||
 3829:                     (grep { $_ eq $homeserver } &current_machine_ids())) {
 3830:                 my $fname = &filelocation('',$url);
 3831:                 if (-e $fname) {
 3832:                     my $hostname = &hostname($homeserver);
 3833:                     if ($hostname) {
 3834:                         my $protocol = $protocol{$homeserver};
 3835:                         $protocol = 'http' if ($protocol ne 'https');
 3836:                         my $uri = &declutter($url);
 3837:                         my $request=new HTTP::Request('HEAD',$protocol.'://'.$hostname.'/raw/'.$uri);
 3838:                         my $response = &LONCAPA::LWPReq::makerequest($homeserver,$request,'',\%perlvar,5,0,1);
 3839:                         if ($response->is_success()) {
 3840:                             my $remmodtime = &HTTP::Date::str2time( $response->header('Last-modified') );
 3841:                             my $locmodtime = (stat($fname))[9];
 3842:                             if ($locmodtime < $remmodtime) {
 3843:                                 my $stale;
 3844:                                 my $answer = &reply('pong',$homeserver);
 3845:                                 if ($answer eq $homeserver.':'.$perlvar{'lonHostID'}) {
 3846:                                     sleep(0.2);
 3847:                                     $locmodtime = (stat($fname))[9];
 3848:                                     if ($locmodtime < $remmodtime) {
 3849:                                         my $posstransfer = $fname.'.in.transfer';
 3850:                                         if ((-e $posstransfer) && ($remmodtime < (stat($posstransfer))[9])) {
 3851:                                             $removed = 1;
 3852:                                         } else {
 3853:                                             $stale = 1;
 3854:                                         }
 3855:                                     } else {
 3856:                                         $removed = 1;
 3857:                                     }
 3858:                                 } else {
 3859:                                     $stale = 1;
 3860:                                 }
 3861:                                 if ($stale) {
 3862:                                     if (unlink($fname)) {
 3863:                                         if ($uri!~/\.meta$/) {
 3864:                                             if (-e $fname.'.meta') {
 3865:                                                 unlink($fname.'.meta');
 3866:                                             }
 3867:                                         }
 3868:                                         my $unsubresult = &unsubscribe($fname);
 3869:                                         unless ($unsubresult eq 'ok') {
 3870:                                             &logthis("no unsub of $fname from $homeserver, reason: $unsubresult");
 3871:                                         }
 3872:                                         $removed = 1;
 3873:                                     }
 3874:                                 }
 3875:                             }
 3876:                         }
 3877:                     }
 3878:                 }
 3879:             }
 3880:         }
 3881:     }
 3882:     return $removed;
 3883: }
 3884: 
 3885: # -------------------------------- Allow a /uploaded/ URI to be vouched for
 3886: 
 3887: sub allowuploaded {
 3888:     my ($srcurl,$url)=@_;
 3889:     $url=&clutter(&declutter($url));
 3890:     my $dir=$url;
 3891:     $dir=~s/\/[^\/]+$//;
 3892:     my %httpref=();
 3893:     my $httpurl=&hreflocation('',$url);
 3894:     $httpref{'httpref.'.$httpurl}=$srcurl;
 3895:     &Apache::lonnet::appenv(\%httpref);
 3896: }
 3897: 
 3898: #
 3899: # Determine if the current user should be able to edit a particular resource,
 3900: # when viewing in course context.
 3901: # (a) When viewing resource used to determine if "Edit" item is included in 
 3902: #     Functions.
 3903: # (b) When displaying folder contents in course editor, used to determine if
 3904: #     "Edit" link will be displayed alongside resource.
 3905: #
 3906: #  input: six args -- filename (decluttered), course number, course domain,
 3907: #                   url, symb (if registered) and group (if this is a group
 3908: #                   item -- e.g., bulletin board, group page etc.).
 3909: #  output: array of five scalars -- 
 3910: #          $cfile -- url for file editing if editable on current server
 3911: #          $home -- homeserver of resource (i.e., for author if published,
 3912: #                                           or course if uploaded.).
 3913: #          $switchserver --  1 if server switch will be needed.
 3914: #          $forceedit -- 1 if icon/link should be to go to edit mode 
 3915: #          $forceview -- 1 if icon/link should be to go to view mode
 3916: #
 3917: 
 3918: sub can_edit_resource {
 3919:     my ($file,$cnum,$cdom,$resurl,$symb,$group) = @_;
 3920:     my ($cfile,$home,$switchserver,$forceedit,$forceview,$uploaded,$incourse);
 3921: #
 3922: # For aboutme pages user can only edit his/her own.
 3923: #
 3924:     if ($resurl =~ m{^/?adm/($match_domain)/($match_username)/aboutme$}) {
 3925:         my ($sdom,$sname) = ($1,$2);
 3926:         if (($sdom eq $env{'user.domain'}) && ($sname eq $env{'user.name'})) {
 3927:             $home = $env{'user.home'};
 3928:             $cfile = $resurl;
 3929:             if ($env{'form.forceedit'}) {
 3930:                 $forceview = 1;
 3931:             } else {
 3932:                 $forceedit = 1;
 3933:             }
 3934:             return ($cfile,$home,$switchserver,$forceedit,$forceview);
 3935:         } else {
 3936:             return;
 3937:         }
 3938:     }
 3939: 
 3940: #
 3941: # For /adm/viewcoauthors can only edit if author or co-author who is manager.
 3942: #
 3943: 
 3944:     if (($resurl eq '/adm/viewcoauthors') && ($cnum ne '') && ($cdom ne '')) {
 3945:         if (((&allowed('cca',"$cdom/$cnum")) ||
 3946:              (&allowed('caa',"$cdom/$cnum"))) ||
 3947:              ((&allowed('vca',"$cdom/$cnum") ||
 3948:                &allowed('vaa',"$cdom/$cnum")) &&
 3949:               ($env{"environment.internal.manager./$cdom/$cnum"}))) {
 3950:             $home = $env{'user.home'};
 3951:             $cfile = $resurl;
 3952:             if ($env{'form.forceedit'}) {
 3953:                 $forceview = 1;
 3954:             } else {
 3955:                 $forceedit = 1;
 3956:             }
 3957:             return ($cfile,$home,$switchserver,$forceedit,$forceview);
 3958:         } else {
 3959:             return;
 3960:         }
 3961:     }
 3962: 
 3963:     if ($env{'request.course.id'}) {
 3964:         my $crsedit = &allowed('mdc',$env{'request.course.id'});
 3965:         if ($group ne '') {
 3966: # if this is a group homepage or group bulletin board, check group privs
 3967:             my $allowed = 0;
 3968:             if ($resurl =~ m{^/?adm/$cdom/$cnum/$group/smppg$}) {
 3969:                 if ((&allowed('mdg',$env{'request.course.id'}.
 3970:                               ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
 3971:                         (&allowed('mgh',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
 3972:                     $allowed = 1;
 3973:                 }
 3974:             } elsif ($resurl =~ m{^/?adm/$cdom/$cnum/\d+/bulletinboard$}) {
 3975:                 if ((&allowed('mdg',$env{'request.course.id'}.($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
 3976:                         (&allowed('cgb',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
 3977:                     $allowed = 1;
 3978:                 }
 3979:             }
 3980:             if ($allowed) {
 3981:                 $home=&homeserver($cnum,$cdom);
 3982:                 if ($env{'form.forceedit'}) {
 3983:                     $forceview = 1;
 3984:                 } else {
 3985:                     $forceedit = 1;
 3986:                 }
 3987:                 $cfile = $resurl;
 3988:             } else {
 3989:                 return;
 3990:             }
 3991:         } else {
 3992:             if ($resurl =~ m{^/?adm/viewclasslist$}) {
 3993:                 unless (&allowed('opa',$env{'request.course.id'})) {
 3994:                     return;
 3995:                 }
 3996:             } elsif (!$crsedit) {
 3997:                 if ($env{'request.role'} =~ m{^st\./$cdom/$cnum}) {
 3998: #
 3999: # No edit allowed where CC has switched to student role.
 4000: #
 4001:                     return;
 4002:                 } elsif (($resurl !~ m{^/res/$match_domain/$match_username/}) ||
 4003:                          ($resurl =~ m{^/res/lib/templates/})) {
 4004:                     return;
 4005:                 }
 4006:             }
 4007:         }
 4008:     }
 4009: 
 4010:     if ($file ne '') {
 4011:         if (($cnum =~ /$match_courseid/) && ($cdom =~ /$match_domain/)) {
 4012:             if (&is_course_upload($file,$cnum,$cdom)) {
 4013:                 $uploaded = 1;
 4014:                 $incourse = 1;
 4015:                 if ($file =~/\.(htm|html|css|js|txt)$/) {
 4016:                     $cfile = &hreflocation('',$file);
 4017:                     if ($env{'form.forceedit'}) {
 4018:                         $forceview = 1;
 4019:                     } else {
 4020:                         $forceedit = 1;
 4021:                     }
 4022:                 }
 4023:             } elsif ($resurl =~ m{^/public/$cdom/$cnum/syllabus}) {
 4024:                 $incourse = 1;
 4025:                 if ($env{'form.forceedit'}) {
 4026:                     $forceview = 1;
 4027:                 } else {
 4028:                     $forceedit = 1;
 4029:                 }
 4030:                 $cfile = $resurl;
 4031:             } elsif (($resurl ne '') && (&is_on_map($resurl))) {
 4032:                 if ($resurl =~ m{^/adm/$match_domain/$match_username/\d+/smppg|bulletinboard$}) {
 4033:                     $incourse = 1;
 4034:                     if ($env{'form.forceedit'}) {
 4035:                         $forceview = 1;
 4036:                     } else {
 4037:                         $forceedit = 1;
 4038:                     }
 4039:                     $cfile = $resurl;
 4040:                 } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem') {
 4041:                     $incourse = 1;
 4042:                     $cfile = $resurl.'/smpedit';
 4043:                 } elsif ($resurl =~ m{^/adm/wrapper/ext/}) {
 4044:                     $incourse = 1;
 4045:                     if ($env{'form.forceedit'}) {
 4046:                         $forceview = 1;
 4047:                     } else {
 4048:                         $forceedit = 1;
 4049:                     }
 4050:                     $cfile = $resurl;
 4051:                 } elsif (($resurl =~ m{^/ext/}) && ($symb ne '')) {
 4052:                     my ($map,$id,$res) = &decode_symb($symb);
 4053:                     if ($map =~ /\.page$/) {
 4054:                         $incourse = 1;
 4055:                         if ($env{'form.forceedit'}) {
 4056:                             $forceview = 1;
 4057:                             $cfile = $map;
 4058:                         } else {
 4059:                             $forceedit = 1;
 4060:                             $cfile =  '/adm/wrapper'.$resurl;
 4061:                         }
 4062:                     }
 4063:                 } elsif ($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/ext\.tool$}) {
 4064:                     $incourse = 1;
 4065:                     if ($env{'form.forceedit'}) {
 4066:                         $forceview = 1;
 4067:                     } else {
 4068:                         $forceedit = 1;
 4069:                     }
 4070:                     $cfile = $resurl;
 4071:                 } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
 4072:                     $incourse = 1;
 4073:                     if ($env{'form.forceedit'}) {
 4074:                         $forceview = 1;
 4075:                     } else {
 4076:                         $forceedit = 1;
 4077:                     }
 4078:                     $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
 4079:                 }
 4080:             } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem/smpedit') {
 4081:                 my $template = '/res/lib/templates/simpleproblem.problem';
 4082:                 if (&is_on_map($template)) { 
 4083:                     $incourse = 1;
 4084:                     $forceview = 1;
 4085:                     $cfile = $template;
 4086:                 }
 4087:             } elsif (($resurl =~ m{^/adm/wrapper/ext/}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
 4088:                 $incourse = 1;
 4089:                 if ($env{'form.forceedit'}) {
 4090:                     $forceview = 1;
 4091:                 } else {
 4092:                     $forceedit = 1;
 4093:                 }
 4094:                 $cfile = $resurl;
 4095:             } elsif (($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/ext\.tool$}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
 4096:                 $incourse = 1;
 4097:                 if ($env{'form.forceedit'}) {
 4098:                     $forceview = 1;
 4099:                 } else {
 4100:                     $forceedit = 1;
 4101:                 }
 4102:                 $cfile = $resurl;
 4103:             } elsif (($resurl eq '/adm/extresedit') && ($symb || $env{'form.folderpath'})) {
 4104:                 $incourse = 1;
 4105:                 $forceview = 1;
 4106:                 if ($symb) {
 4107:                     my ($map,$id,$res)=&decode_symb($symb);
 4108:                     $env{'request.symb'} = $symb;
 4109:                     $cfile = &clutter($res);
 4110:                 } else {
 4111:                     $cfile = $env{'form.suppurl'};
 4112:                     my $escfile = &unescape($cfile);
 4113:                     if ($escfile =~ m{^/adm/$cdom/$cnum/\d+/ext\.tool$}) {
 4114:                         $cfile = '/adm/wrapper'.$escfile;
 4115:                     } else {
 4116:                         $escfile =~ s{^http://}{};
 4117:                         $cfile = &escape("/adm/wrapper/ext/$escfile");
 4118:                     }
 4119:                 }
 4120:             } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
 4121:                 if ($env{'form.forceedit'}) {
 4122:                     $forceview = 1;
 4123:                 } else {
 4124:                     $forceedit = 1;
 4125:                 }
 4126:                 $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
 4127:             }
 4128:         }
 4129:         if ($uploaded || $incourse) {
 4130:             $home=&homeserver($cnum,$cdom);
 4131:         } elsif ($file !~ m{/$}) {
 4132:             $file=~s{^(priv/$match_domain/$match_username)}{/$1};
 4133:             $file=~s{^($match_domain/$match_username)}{/priv/$1};
 4134:             # Check that the user has permission to edit this resource
 4135:             my $setpriv = 1;
 4136:             my ($cfuname,$cfudom)=&constructaccess($file,$setpriv);
 4137:             if (defined($cfudom)) {
 4138:                 $home=&homeserver($cfuname,$cfudom);
 4139:                 $cfile=$file;
 4140:             }
 4141:         }
 4142:         if (($cfile ne '') && (!$incourse || $uploaded) && 
 4143:             (($home ne '') && ($home ne 'no_host'))) {
 4144:             my @ids=&current_machine_ids();
 4145:             unless (grep(/^\Q$home\E$/,@ids)) {
 4146:                 $switchserver=1;
 4147:             }
 4148:         }
 4149:     }
 4150:     return ($cfile,$home,$switchserver,$forceedit,$forceview);
 4151: }
 4152: 
 4153: sub is_course_upload {
 4154:     my ($file,$cnum,$cdom) = @_;
 4155:     my $uploadpath = &LONCAPA::propath($cdom,$cnum);
 4156:     $uploadpath =~ s{^\/}{};
 4157:     if (($file =~ m{^\Q$uploadpath\E/userfiles/(docs|supplemental)/}) ||
 4158:         ($file =~ m{^userfiles/\Q$cdom\E/\Q$cnum\E/(docs|supplemental)/})) {
 4159:         return 1;
 4160:     }
 4161:     return;
 4162: }
 4163: 
 4164: sub in_course {
 4165:     my ($udom,$uname,$cdom,$cnum,$type,$hideprivileged) = @_;
 4166:     if ($hideprivileged) {
 4167:         my $skipuser;
 4168:         my %coursehash = &coursedescription($cdom.'_'.$cnum);
 4169:         my @possdoms = ($cdom);  
 4170:         if ($coursehash{'checkforpriv'}) { 
 4171:             push(@possdoms,split(/,/,$coursehash{'checkforpriv'})); 
 4172:         }
 4173:         if (&privileged($uname,$udom,\@possdoms)) {
 4174:             $skipuser = 1;
 4175:             if ($coursehash{'nothideprivileged'}) {
 4176:                 foreach my $item (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 4177:                     my $user;
 4178:                     if ($item =~ /:/) {
 4179:                         $user = $item;
 4180:                     } else {
 4181:                         $user = join(':',split(/[\@]/,$item));
 4182:                     }
 4183:                     if ($user eq $uname.':'.$udom) {
 4184:                         undef($skipuser);
 4185:                         last;
 4186:                     }
 4187:                 }
 4188:             }
 4189:             if ($skipuser) {
 4190:                 return 0;
 4191:             }
 4192:         }
 4193:     }
 4194:     $type ||= 'any';
 4195:     if (!defined($cdom) || !defined($cnum)) {
 4196:         my $cid  = $env{'request.course.id'};
 4197:         $cdom = $env{'course.'.$cid.'.domain'};
 4198:         $cnum = $env{'course.'.$cid.'.num'};
 4199:     }
 4200:     my $typesref;
 4201:     if (($type eq 'any') || ($type eq 'all')) {
 4202:         $typesref = ['active','previous','future'];
 4203:     } elsif ($type eq 'previous' || $type eq 'future') {
 4204:         $typesref = [$type];
 4205:     }
 4206:     my %roles = &get_my_roles($uname,$udom,'userroles',
 4207:                               $typesref,undef,[$cdom]);
 4208:     my ($tmp) = keys(%roles);
 4209:     return 0 if ($tmp =~ /^(con_lost|error|no_such_host)/i);
 4210:     my @course_roles = grep(/^\Q$cnum\E:\Q$cdom\E:/, keys(%roles));
 4211:     if (@course_roles > 0) {
 4212:         return 1;
 4213:     }
 4214:     return 0;
 4215: }
 4216: 
 4217: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
 4218: # input: action, courseID, current domain, intended
 4219: #        path to file, source of file, instruction to parse file for objects,
 4220: #        ref to hash for embedded objects,
 4221: #        ref to hash for codebase of java objects.
 4222: #        reference to scalar to accommodate mime type determined
 4223: #          from File::MMagic if $parser = parse.
 4224: #
 4225: # output: url to file (if action was uploaddoc), 
 4226: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
 4227: #
 4228: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
 4229: # course.
 4230: #
 4231: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 4232: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
 4233: #          course's home server.
 4234: #
 4235: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
 4236: #          be copied from $source (current location) to 
 4237: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 4238: #         and will then be copied to
 4239: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
 4240: #         course's home server.
 4241: #
 4242: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 4243: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
 4244: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 4245: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
 4246: #         in course's home server.
 4247: #
 4248: 
 4249: sub process_coursefile {
 4250:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
 4251:         $mimetype)=@_;
 4252:     my $fetchresult;
 4253:     my $home=&homeserver($docuname,$docudom);
 4254:     if ($action eq 'propagate') {
 4255:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 4256: 			     $home);
 4257:     } else {
 4258:         my $fpath = '';
 4259:         my $fname = $file;
 4260:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 4261:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 4262:         my $filepath = &build_filepath($fpath);
 4263:         if ($action eq 'copy') {
 4264:             if ($source eq '') {
 4265:                 $fetchresult = 'no source file';
 4266:                 return $fetchresult;
 4267:             } else {
 4268:                 my $destination = $filepath.'/'.$fname;
 4269:                 rename($source,$destination);
 4270:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 4271:                                  $home);
 4272:             }
 4273:         } elsif ($action eq 'uploaddoc') {
 4274:             open(my $fh,'>',$filepath.'/'.$fname);
 4275:             print $fh $env{'form.'.$source};
 4276:             close($fh);
 4277:             if ($parser eq 'parse') {
 4278:                 my $mm = new File::MMagic;
 4279:                 my $type = $mm->checktype_filename($filepath.'/'.$fname);
 4280:                 if ($type eq 'text/html') {
 4281:                     my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
 4282:                     unless ($parse_result eq 'ok') {
 4283:                         &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
 4284:                     }
 4285:                 }
 4286:                 if (ref($mimetype)) {
 4287:                     $$mimetype = $type;
 4288:                 } 
 4289:             }
 4290:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 4291:                                  $home);
 4292:             if ($fetchresult eq 'ok') {
 4293:                 return '/uploaded/'.$fpath.'/'.$fname;
 4294:             } else {
 4295:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 4296:                         ' to host '.$home.': '.$fetchresult);
 4297:                 return '/adm/notfound.html';
 4298:             }
 4299:         }
 4300:     }
 4301:     unless ( $fetchresult eq 'ok') {
 4302:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 4303:              ' to host '.$home.': '.$fetchresult);
 4304:     }
 4305:     return $fetchresult;
 4306: }
 4307: 
 4308: sub build_filepath {
 4309:     my ($fpath) = @_;
 4310:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
 4311:     unless ($fpath eq '') {
 4312:         my @parts=split('/',$fpath);
 4313:         foreach my $part (@parts) {
 4314:             $filepath.= '/'.$part;
 4315:             if ((-e $filepath)!=1) {
 4316:                 mkdir($filepath,0777);
 4317:             }
 4318:         }
 4319:     }
 4320:     return $filepath;
 4321: }
 4322: 
 4323: sub store_edited_file {
 4324:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
 4325:     my $file = $primary_url;
 4326:     $file =~ s#^/uploaded/$docudom/$docuname/##;
 4327:     my $fpath = '';
 4328:     my $fname = $file;
 4329:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 4330:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 4331:     my $filepath = &build_filepath($fpath);
 4332:     open(my $fh,'>',$filepath.'/'.$fname);
 4333:     print $fh $content;
 4334:     close($fh);
 4335:     my $home=&homeserver($docuname,$docudom);
 4336:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 4337: 			  $home);
 4338:     if ($$fetchresult eq 'ok') {
 4339:         return '/uploaded/'.$fpath.'/'.$fname;
 4340:     } else {
 4341:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 4342: 		 ' to host '.$home.': '.$$fetchresult);
 4343:         return '/adm/notfound.html';
 4344:     }
 4345: }
 4346: 
 4347: sub clean_filename {
 4348:     my ($fname,$args)=@_;
 4349: # Replace Windows backslashes by forward slashes
 4350:     $fname=~s/\\/\//g;
 4351:     if (!$args->{'keep_path'}) {
 4352:         # Get rid of everything but the actual filename
 4353: 	$fname=~s/^.*\/([^\/]+)$/$1/;
 4354:     }
 4355: # Replace spaces by underscores
 4356:     $fname=~s/\s+/\_/g;
 4357: # Transliterate non-ascii text to ascii
 4358:     my $lang = &Apache::lonlocal::current_language();
 4359:     $fname = &LONCAPA::transliterate::fname_to_ascii($fname,$lang);
 4360: # Replace all other weird characters by nothing
 4361:     $fname=~s{[^/\w\.\-]}{}g;
 4362: # Replace all .\d. sequences with _\d. so they no longer look like version
 4363: # numbers
 4364:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
 4365: # Replace three or more adjacent underscores with one for consistency 
 4366: # with loncfile::filename_check() so complete url can be extracted by
 4367: # lonnet::decode_symb()
 4368:     $fname=~s/_{3,}/_/g;
 4369:     return $fname;
 4370: }
 4371: 
 4372: # This Function checks if an Image's dimensions exceed either $resizewidth (width) 
 4373: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an 
 4374: # image with the same aspect ratio as the original, but with dimensions which do 
 4375: # not exceed $resizewidth and $resizeheight.
 4376:  
 4377: sub resizeImage {
 4378:     my ($img_path,$resizewidth,$resizeheight) = @_;
 4379:     my $ima = Image::Magick->new;
 4380:     my $resized;
 4381:     if (-e $img_path) {
 4382:         $ima->Read($img_path);
 4383:         if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
 4384:             my $width = $ima->Get('width');
 4385:             my $height = $ima->Get('height');
 4386:             if ($width > $resizewidth) {
 4387: 	        my $factor = $width/$resizewidth;
 4388:                 my $newheight = $height/$factor;
 4389:                 $ima->Scale(width=>$resizewidth,height=>$newheight);
 4390:                 $resized = 1;
 4391:             }
 4392:         }
 4393:         if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
 4394:             my $width = $ima->Get('width');
 4395:             my $height = $ima->Get('height');
 4396:             if ($height > $resizeheight) {
 4397:                 my $factor = $height/$resizeheight;
 4398:                 my $newwidth = $width/$factor;
 4399:                 $ima->Scale(width=>$newwidth,height=>$resizeheight);
 4400:                 $resized = 1;
 4401:             }
 4402:         }
 4403:         if ($resized) {
 4404:             $ima->Write($img_path);
 4405:         }
 4406:     }
 4407:     return;
 4408: }
 4409: 
 4410: # --------------- Take an uploaded file and put it into the userfiles directory
 4411: # input: $formname - the contents of the file are in $env{"form.$formname"}
 4412: #                    the desired filename is in $env{"form.$formname.filename"}
 4413: #        $context - possible values: coursedoc, existingfile, overwrite, 
 4414: #                                    canceloverwrite, scantron, toollogo  or ''.
 4415: #                   if 'coursedoc': upload to the current course
 4416: #                   if 'existingfile': write file to tmp/overwrites directory 
 4417: #                   if 'canceloverwrite': delete file written to tmp/overwrites directory
 4418: #                   $context is passed as argument to &finishuserfileupload
 4419: #        $subdir - directory in userfile to store the file into
 4420: #        $parser - instruction to parse file for objects ($parser = parse) or
 4421: #                  if context is 'scantron', $parser is hashref of csv column mapping
 4422: #                  (e.g.,{ PaperID => 0, LastName => 1, FirstName => 2, ID => 3, 
 4423: #                          Section => 4, CODE => 5, FirstQuestion => 9 }).
 4424: #        $allfiles - reference to hash for embedded objects
 4425: #        $codebase - reference to hash for codebase of java objects
 4426: #        $destuname - username for permanent storage of uploaded file
 4427: #        $destudom - domain for permanaent storage of uploaded file
 4428: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
 4429: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
 4430: #        $resizewidth - width (pixels) to which to resize uploaded image
 4431: #        $resizeheight - height (pixels) to which to resize uploaded image
 4432: #        $mimetype - reference to scalar to accommodate mime type determined
 4433: #                    from File::MMagic.
 4434: # 
 4435: # output: url of file in userspace, or error: <message> 
 4436: #             or /adm/notfound.html if failure to upload occurse
 4437: 
 4438: sub userfileupload {
 4439:     my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
 4440:         $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
 4441:     if (!defined($subdir)) { $subdir='unknown'; }
 4442:     my $fname=$env{'form.'.$formname.'.filename'};
 4443:     $fname=&clean_filename($fname);
 4444:     # See if there is anything left
 4445:     unless ($fname) { return 'error: no uploaded file'; }
 4446:     # If filename now begins with a . prepend unix timestamp _ milliseconds
 4447:     if ($fname =~ /^\./) {
 4448:         my ($s,$usec) = &gettimeofday();
 4449:         while (length($usec) < 6) {
 4450:             $usec = '0'.$usec;
 4451:         }
 4452:         $fname = $s.'_'.substr($usec,0,3).$fname;
 4453:     }
 4454:     # Files uploaded to help request form, or uploaded to "create course" page are handled differently
 4455:     if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
 4456:         (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
 4457:          ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
 4458:         my $now = time;
 4459:         my $filepath;
 4460:         if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
 4461:              $filepath = 'tmp/helprequests/'.$now;
 4462:         } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
 4463:              $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
 4464:                          '_'.$env{'user.domain'}.'/pending';
 4465:         } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
 4466:             my ($docuname,$docudom);
 4467:             if ($destudom =~ /^$match_domain$/) {
 4468:                 $docudom = $destudom;
 4469:             } else {
 4470:                 $docudom = $env{'user.domain'};
 4471:             }
 4472:             if ($destuname =~ /^$match_username$/) {
 4473:                 $docuname = $destuname;
 4474:             } else {
 4475:                 $docuname = $env{'user.name'};
 4476:             }
 4477:             if (exists($env{'form.group'})) {
 4478:                 $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 4479:                 $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 4480:             }
 4481:             $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
 4482:             if ($context eq 'canceloverwrite') {
 4483:                 my $tempfile =  $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
 4484:                 if (-e  $tempfile) {
 4485:                     my @info = stat($tempfile);
 4486:                     if ($info[9] eq $env{'form.timestamp'}) {
 4487:                         unlink($tempfile);
 4488:                     }
 4489:                 }
 4490:                 return;
 4491:             }
 4492:         }
 4493:         # Create the directory if not present
 4494:         my @parts=split(/\//,$filepath);
 4495:         my $fullpath = $perlvar{'lonDaemons'};
 4496:         for (my $i=0;$i<@parts;$i++) {
 4497:             $fullpath .= '/'.$parts[$i];
 4498:             if ((-e $fullpath)!=1) {
 4499:                 mkdir($fullpath,0777);
 4500:             }
 4501:         }
 4502:         open(my $fh,'>',$fullpath.'/'.$fname);
 4503:         print $fh $env{'form.'.$formname};
 4504:         close($fh);
 4505:         if ($context eq 'existingfile') {
 4506:             my @info = stat($fullpath.'/'.$fname);
 4507:             return ($fullpath.'/'.$fname,$info[9]);
 4508:         } else {
 4509:             return $fullpath.'/'.$fname;
 4510:         }
 4511:     }
 4512:     if ($subdir eq 'scantron') {
 4513:         $fname = 'scantron_orig_'.$fname;
 4514:     } else {
 4515:         $fname="$subdir/$fname";
 4516:     }
 4517:     if ($context eq 'coursedoc') {
 4518: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 4519: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 4520:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
 4521:             return &finishuserfileupload($docuname,$docudom,
 4522: 					 $formname,$fname,$parser,$allfiles,
 4523: 					 $codebase,$thumbwidth,$thumbheight,
 4524:                                          $resizewidth,$resizeheight,$context,$mimetype);
 4525:         } else {
 4526:             if ($env{'form.folder'}) {
 4527:                 $fname=$env{'form.folder'}.'/'.$fname;
 4528:             }
 4529:             return &process_coursefile('uploaddoc',$docuname,$docudom,
 4530: 				       $fname,$formname,$parser,
 4531: 				       $allfiles,$codebase,$mimetype);
 4532:         }
 4533:     } elsif (defined($destuname)) {
 4534:         my $docuname=$destuname;
 4535:         my $docudom=$destudom;
 4536: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
 4537: 				     $parser,$allfiles,$codebase,
 4538:                                      $thumbwidth,$thumbheight,
 4539:                                      $resizewidth,$resizeheight,$context,$mimetype);
 4540:     } else {
 4541:         my $docuname=$env{'user.name'};
 4542:         my $docudom=$env{'user.domain'};
 4543:         if ((exists($env{'form.group'})) || ($context eq 'syllabus')) {
 4544:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 4545:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 4546:         }
 4547: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
 4548: 				     $parser,$allfiles,$codebase,
 4549:                                      $thumbwidth,$thumbheight,
 4550:                                      $resizewidth,$resizeheight,$context,$mimetype);
 4551:     }
 4552: }
 4553: 
 4554: sub finishuserfileupload {
 4555:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
 4556:         $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
 4557:     my $path=$docudom.'/'.$docuname.'/';
 4558:     my $filepath=$perlvar{'lonDocRoot'};
 4559:   
 4560:     my ($fnamepath,$file,$fetchthumb);
 4561:     $file=$fname;
 4562:     if ($fname=~m|/|) {
 4563:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
 4564: 	$path.=$fnamepath.'/';
 4565:     }
 4566:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
 4567:     my $count;
 4568:     for ($count=4;$count<=$#parts;$count++) {
 4569:         $filepath.="/$parts[$count]";
 4570:         if ((-e $filepath)!=1) {
 4571: 	    mkdir($filepath,0777);
 4572:         }
 4573:     }
 4574: 
 4575: # Save the file
 4576:     {
 4577: 	if (!open(FH,'>',$filepath.'/'.$file)) {
 4578: 	    &logthis('Failed to create '.$filepath.'/'.$file);
 4579: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
 4580: 	    return '/adm/notfound.html';
 4581: 	}
 4582:         if ($context eq 'overwrite') {
 4583:             my $source =  LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
 4584:             my $target = $filepath.'/'.$file;
 4585:             if (-e $source) {
 4586:                 my @info = stat($source);
 4587:                 if ($info[9] eq $env{'form.timestamp'}) {   
 4588:                     unless (&File::Copy::move($source,$target)) {
 4589:                         &logthis('Failed to overwrite '.$filepath.'/'.$file);
 4590:                         return "Moving from $source failed";
 4591:                     }
 4592:                 } else {
 4593:                     return "Temporary file: $source had unexpected date/time for last modification";
 4594:                 }
 4595:             } else {
 4596:                 return "Temporary file: $source missing";
 4597:             }
 4598:         } elsif (!print FH ($env{'form.'.$formname})) {
 4599: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
 4600: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
 4601: 	    return '/adm/notfound.html';
 4602: 	}
 4603: 	close(FH);
 4604:         if ($resizewidth && $resizeheight) {
 4605:             my $mm = new File::MMagic;
 4606:             my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
 4607:             if ($mime_type =~ m{^image/}) {
 4608: 	        &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
 4609:             }  
 4610: 	}
 4611:     }
 4612:     if (($context eq 'coursedoc') || ($parser eq 'parse')) {
 4613:         if (ref($mimetype)) {
 4614:             if ($$mimetype eq '') {
 4615:                 my $mm = new File::MMagic;
 4616:                 my $type = $mm->checktype_filename($filepath.'/'.$file);
 4617:                 $$mimetype = $type;
 4618:             }
 4619:         }
 4620:     }
 4621:     if (($context ne 'scantron') && ($parser eq 'parse')) {
 4622:         if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
 4623:             my $parse_result = &extract_embedded_items($filepath.'/'.$file,
 4624:                                                        $allfiles,$codebase);
 4625:             unless ($parse_result eq 'ok') {
 4626:                 &logthis('Failed to parse '.$filepath.$file.
 4627: 	   	         ' for embedded media: '.$parse_result); 
 4628:             }
 4629:         }
 4630:     } elsif (($context eq 'scantron') && (ref($parser) eq 'HASH')) {
 4631:         my $format = $env{'form.scantron_format'};
 4632:         &bubblesheet_converter($docudom,$filepath.'/'.$file,$parser,$format);
 4633:     }
 4634:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
 4635:         my $input = $filepath.'/'.$file;
 4636:         my $output = $filepath.'/'.'tn-'.$file;
 4637:         my $makethumb; 
 4638:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
 4639:         if ($context eq 'toollogo') {
 4640:             my ($fullwidth,$fullheight) = &check_dimensions($input);
 4641:             if ($fullwidth ne '' && $fullheight ne '') {
 4642:                 if ($fullwidth > $thumbwidth && $fullheight > $thumbheight) {
 4643:                     $makethumb = 1;
 4644:                 }
 4645:             }
 4646:         } else {
 4647:             $makethumb = 1;
 4648:         }
 4649:         if ($makethumb) {
 4650:             my @args = ('convert','-sample',$thumbsize,$input,$output);
 4651:             system({$args[0]} @args);
 4652:             if (-e $filepath.'/'.'tn-'.$file) {
 4653:                 $fetchthumb  = 1; 
 4654:             }
 4655:         }
 4656:     }
 4657:  
 4658: # Notify homeserver to grep it
 4659: #
 4660:     my $docuhome=&homeserver($docuname,$docudom);	
 4661:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
 4662:     if ($fetchresult eq 'ok') {
 4663:         if ($fetchthumb) {
 4664:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
 4665:             if ($thumbresult ne 'ok') {
 4666:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
 4667:                          $docuhome.': '.$thumbresult);
 4668:             }
 4669:         }
 4670: #
 4671: # Return the URL to it
 4672:         return '/uploaded/'.$path.$file;
 4673:     } else {
 4674:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
 4675: 		 ': '.$fetchresult);
 4676:         return '/adm/notfound.html';
 4677:     }
 4678: }
 4679: 
 4680: sub extract_embedded_items {
 4681:     my ($fullpath,$allfiles,$codebase,$content) = @_;
 4682:     my @state = ();
 4683:     my (%lastids,%related,%shockwave,%flashvars);
 4684:     my %javafiles = (
 4685:                       codebase => '',
 4686:                       code => '',
 4687:                       archive => ''
 4688:                     );
 4689:     my %mediafiles = (
 4690:                       src => '',
 4691:                       movie => '',
 4692:                      );
 4693:     my $p;
 4694:     if ($content) {
 4695:         $p = HTML::LCParser->new($content);
 4696:     } else {
 4697:         $p = HTML::LCParser->new($fullpath);
 4698:     }
 4699:     while (my $t=$p->get_token()) {
 4700: 	if ($t->[0] eq 'S') {
 4701: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
 4702: 	    push(@state, $tagname);
 4703:             if (lc($tagname) eq 'allow') {
 4704:                 &add_filetype($allfiles,$attr->{'src'},'src');
 4705:             }
 4706: 	    if (lc($tagname) eq 'img') {
 4707: 		&add_filetype($allfiles,$attr->{'src'},'src');
 4708: 	    }
 4709: 	    if (lc($tagname) eq 'a') {
 4710:                 unless (($attr->{'href'} =~ /^#/) || ($attr->{'href'} eq '')) {
 4711:                     &add_filetype($allfiles,$attr->{'href'},'href');
 4712:                 }
 4713: 	    }
 4714:             if (lc($tagname) eq 'script') {
 4715:                 my $src;
 4716:                 if ($attr->{'archive'} =~ /\.jar$/i) {
 4717:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
 4718:                 } else {
 4719:                     if ($attr->{'src'} ne '') {
 4720:                         $src = $attr->{'src'};
 4721:                         &add_filetype($allfiles,$src,'src');
 4722:                     }
 4723:                 }
 4724:                 my $text = $p->get_trimmed_text();
 4725:                 if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
 4726:                     my @swfargs = split(/,/,$1);
 4727:                     foreach my $item (@swfargs) {
 4728:                         $item =~ s/["']//g;
 4729:                         $item =~ s/^\s+//;
 4730:                         $item =~ s/\s+$//;
 4731:                     }
 4732:                     if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
 4733:                         if (ref($related{$swfargs[0]}) eq 'ARRAY') {
 4734:                             push(@{$related{$swfargs[0]}},$swfargs[2]);
 4735:                         } else {
 4736:                             $related{$swfargs[0]} = [$swfargs[2]];
 4737:                         }
 4738:                     }
 4739:                 }
 4740:             }
 4741:             if (lc($tagname) eq 'link') {
 4742:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
 4743:                     &add_filetype($allfiles,$attr->{'href'},'href');
 4744:                 }
 4745:             }
 4746: 	    if (lc($tagname) eq 'object' ||
 4747: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
 4748: 		foreach my $item (keys(%javafiles)) {
 4749: 		    $javafiles{$item} = '';
 4750: 		}
 4751:                 if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
 4752:                     $lastids{lc($tagname)} = $attr->{'id'};
 4753:                 }
 4754: 	    }
 4755: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
 4756: 		my $name = lc($attr->{'name'});
 4757: 		foreach my $item (keys(%javafiles)) {
 4758: 		    if ($name eq $item) {
 4759: 			$javafiles{$item} = $attr->{'value'};
 4760: 			last;
 4761: 		    }
 4762: 		}
 4763:                 my $pathfrom;
 4764: 		foreach my $item (keys(%mediafiles)) {
 4765: 		    if ($name eq $item) {
 4766:                         $pathfrom = $attr->{'value'};
 4767:                         $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
 4768: 			&add_filetype($allfiles,$pathfrom,$name);
 4769: 			last;
 4770: 		    }
 4771: 		}
 4772:                 if ($name eq 'flashvars') {
 4773:                     $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
 4774:                 }
 4775:                 if ($pathfrom ne '') {
 4776:                     &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
 4777:                                          $pathfrom);
 4778:                 }
 4779: 	    }
 4780: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
 4781: 		foreach my $item (keys(%javafiles)) {
 4782: 		    if ($attr->{$item}) {
 4783: 			$javafiles{$item} = $attr->{$item};
 4784: 			last;
 4785: 		    }
 4786: 		}
 4787: 		foreach my $item (keys(%mediafiles)) {
 4788: 		    if ($attr->{$item}) {
 4789: 			&add_filetype($allfiles,$attr->{$item},$item);
 4790: 			last;
 4791: 		    }
 4792: 		}
 4793:                 if (lc($tagname) eq 'embed') {
 4794:                     if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
 4795:                         &embedded_dependency($allfiles,\%related,$attr->{'name'},
 4796:                                              $attr->{'src'});
 4797:                     }
 4798:                 }
 4799: 	    }
 4800:             if (lc($tagname) eq 'iframe') {
 4801:                 my $src = $attr->{'src'} ;
 4802:                 if (($src ne '') && ($src !~ m{^(/|https?://)})) {
 4803:                     &add_filetype($allfiles,$src,'src');
 4804:                 } elsif ($src =~ m{^/}) {
 4805:                     if ($env{'request.course.id'}) {
 4806:                         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 4807:                         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 4808:                         my $url = &hreflocation('',$fullpath);
 4809:                         if ($url =~ m{^/uploaded/$cdom/$cnum/docs/(\w+/\d+)/}) {
 4810:                             my $relpath = $1;
 4811:                             if ($src =~ m{^/uploaded/$cdom/$cnum/docs/\Q$relpath\E/(.+)$}) {
 4812:                                 &add_filetype($allfiles,$1,'src');
 4813:                             }
 4814:                         }
 4815:                     }
 4816:                 }
 4817:             }
 4818:             if ($t->[4] =~ m{/>$}) {
 4819:                 pop(@state);
 4820:             }
 4821: 	} elsif ($t->[0] eq 'E') {
 4822: 	    my ($tagname) = ($t->[1]);
 4823: 	    if ($javafiles{'codebase'} ne '') {
 4824: 		$javafiles{'codebase'} .= '/';
 4825: 	    }  
 4826: 	    if (lc($tagname) eq 'applet' ||
 4827: 		lc($tagname) eq 'object' ||
 4828: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
 4829: 		) {
 4830: 		foreach my $item (keys(%javafiles)) {
 4831: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
 4832: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
 4833: 			&add_filetype($allfiles,$file,$item);
 4834: 		    }
 4835: 		}
 4836: 	    } 
 4837: 	    pop @state;
 4838: 	}
 4839:     }
 4840:     foreach my $id (sort(keys(%flashvars))) {
 4841:         if ($shockwave{$id} ne '') {
 4842:             my @pairs = split(/\&/,$flashvars{$id});
 4843:             foreach my $pair (@pairs) {
 4844:                 my ($key,$value) = split(/\=/,$pair);
 4845:                 if ($key eq 'thumb') {
 4846:                     &add_filetype($allfiles,$value,$key);
 4847:                 } elsif ($key eq 'content') {
 4848:                     my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
 4849:                     my ($ext) = ($value =~ /\.([^.]+)$/);
 4850:                     if ($ext ne '') {
 4851:                         &add_filetype($allfiles,$path.$value,$ext);
 4852:                     }
 4853:                 }
 4854:             }
 4855:         }
 4856:     }
 4857:     return 'ok';
 4858: }
 4859: 
 4860: sub add_filetype {
 4861:     my ($allfiles,$file,$type)=@_;
 4862:     if (exists($allfiles->{$file})) {
 4863: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
 4864: 	    push(@{$allfiles->{$file}}, &escape($type));
 4865: 	}
 4866:     } else {
 4867: 	@{$allfiles->{$file}} = (&escape($type));
 4868:     }
 4869: }
 4870: 
 4871: sub embedded_dependency {
 4872:     my ($allfiles,$related,$identifier,$pathfrom) = @_;
 4873:     if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
 4874:         if (($identifier ne '') &&
 4875:             (ref($related->{$identifier}) eq 'ARRAY') &&
 4876:             ($pathfrom ne '')) {
 4877:             my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
 4878:             foreach my $dep (@{$related->{$identifier}}) {
 4879:                 &add_filetype($allfiles,$path.$dep,'object');
 4880:             }
 4881:         }
 4882:     }
 4883:     return;
 4884: }
 4885: 
 4886: sub check_dimensions {
 4887:     my ($inputfile) = @_;
 4888:     my ($fullwidth,$fullheight);
 4889:     if (($inputfile =~ m|^[/\w.\-]+$|) && (-e $inputfile)) {
 4890:         my $mm = new File::MMagic;
 4891:         my $mime_type = $mm->checktype_filename($inputfile);
 4892:         if ($mime_type =~ m{^image/}) {
 4893:             if (open(PIPE,"identify $inputfile 2>&1 |")) {
 4894:                 my $imageinfo = <PIPE>;
 4895:                 if (!close(PIPE)) {
 4896:                     &Apache::lonnet::logthis("Failed to close PIPE opened to retrieve image information for $inputfile");
 4897:                 }
 4898:                 chomp($imageinfo);
 4899:                 my ($fullsize) =
 4900:                     ($imageinfo =~ /^\Q$inputfile\E\s+\w+\s+(\d+x\d+)/);
 4901:                 if ($fullsize) {
 4902:                     ($fullwidth,$fullheight) = split(/x/,$fullsize);
 4903:                 }
 4904:             }
 4905:         }
 4906:     }
 4907:     return ($fullwidth,$fullheight);
 4908: }
 4909: 
 4910: sub bubblesheet_converter {
 4911:     my ($cdom,$fullpath,$config,$format) = @_;
 4912:     if ((&domain($cdom) ne '') &&
 4913:         ($fullpath =~ m{^\Q$perlvar{'lonDocRoot'}/userfiles/$cdom/\E$match_courseid/scantron_orig}) &&
 4914:         (-e $fullpath) && (ref($config) eq 'HASH') && ($format ne '')) {
 4915:         my (%csvcols,%csvoptions);
 4916:         if (ref($config->{'fields'}) eq 'HASH') {  
 4917:             %csvcols = %{$config->{'fields'}};
 4918:         }
 4919:         if (ref($config->{'options'}) eq 'HASH') {
 4920:             %csvoptions = %{$config->{'options'}};
 4921:         }
 4922:         my %csvbynum = reverse(%csvcols);
 4923:         my %scantronconf = &get_scantron_config($format,$cdom);
 4924:         if (keys(%scantronconf)) {
 4925:             my %bynum = (
 4926:                           $scantronconf{CODEstart} => 'CODEstart',
 4927:                           $scantronconf{IDstart}   => 'IDstart',
 4928:                           $scantronconf{PaperID}   => 'PaperID',
 4929:                           $scantronconf{FirstName} => 'FirstName',
 4930:                           $scantronconf{LastName}  => 'LastName',
 4931:                           $scantronconf{Qstart}    => 'Qstart',
 4932:                         );
 4933:             my @ordered;
 4934:             foreach my $item (sort { $a <=> $b } keys(%bynum)) {
 4935:                 push(@ordered,$bynum{$item});
 4936:             }
 4937:             my %mapstart = (
 4938:                               CODEstart => 'CODE',
 4939:                               IDstart   => 'ID',
 4940:                               PaperID   => 'PaperID',
 4941:                               FirstName => 'FirstName',
 4942:                               LastName  => 'LastName',
 4943:                               Qstart    => 'FirstQuestion',
 4944:                            );
 4945:             my %maplength = (
 4946:                               CODEstart => 'CODElength',
 4947:                               IDstart   => 'IDlength',
 4948:                               PaperID   => 'PaperIDlength',
 4949:                               FirstName => 'FirstNamelength',
 4950:                               LastName  => 'LastNamelength',
 4951:             );
 4952:             if (open(my $fh,'<',$fullpath)) {
 4953:                 my $output;
 4954:                 my %lettdig = &letter_to_digits();
 4955:                 my %diglett = reverse(%lettdig);
 4956:                 my $numletts = scalar(keys(%lettdig));
 4957:                 my $num = 0;
 4958:                 while (my $line=<$fh>) {
 4959:                     $num ++;
 4960:                     next if (($num == 1) && ($csvoptions{'hdr'} == 1));
 4961:                     $line =~ s{[\r\n]+$}{};
 4962:                     my %found;
 4963:                     my @values = split(/,/,$line,-1);
 4964:                     my ($qstart,$record);
 4965:                     for (my $i=0; $i<@values; $i++) {
 4966:                         if ((($qstart ne '') && ($i > $qstart)) ||
 4967:                             ($csvbynum{$i} eq 'FirstQuestion')) {
 4968:                             if ($values[$i] eq '') {
 4969:                                 $values[$i] = $scantronconf{'Qoff'};
 4970:                             } elsif ($scantronconf{'Qon'} eq 'number') {
 4971:                                 if ($values[$i] =~ /^[A-Ja-j]$/) {
 4972:                                     $values[$i] = $lettdig{uc($values[$i])};
 4973:                                 }
 4974:                             } elsif ($scantronconf{'Qon'} eq 'letter') {
 4975:                                 if ($values[$i] =~ /^[0-9]$/) {
 4976:                                     $values[$i] = $diglett{$values[$i]};
 4977:                                 }
 4978:                             } else {
 4979:                                 if ($values[$i] =~ /^[0-9A-Ja-j]$/) {
 4980:                                     my $digit;
 4981:                                     if ($values[$i] =~ /^[A-Ja-j]$/) {
 4982:                                         $digit = $lettdig{uc($values[$i])}-1;
 4983:                                         if ($values[$i] eq 'J') {
 4984:                                             $digit += $numletts;
 4985:                                         }
 4986:                                     } elsif ($values[$i] =~ /^[0-9]$/) {
 4987:                                         $digit = $values[$i]-1;
 4988:                                         if ($values[$i] eq '0') {
 4989:                                             $digit += $numletts;
 4990:                                         }
 4991:                                     }
 4992:                                     my $qval='';
 4993:                                     for (my $j=0; $j<$scantronconf{'Qlength'}; $j++) {
 4994:                                         if ($j == $digit) {
 4995:                                             $qval .= $scantronconf{'Qon'};
 4996:                                         } else {
 4997:                                             $qval .= $scantronconf{'Qoff'};
 4998:                                         }
 4999:                                     }
 5000:                                     $values[$i] = $qval;
 5001:                                 }
 5002:                             }
 5003:                             if (length($values[$i]) > $scantronconf{'Qlength'}) {
 5004:                                 $values[$i] = substr($values[$i],0,$scantronconf{'Qlength'});
 5005:                             }
 5006:                             my $numblank = $scantronconf{'Qlength'} - length($values[$i]);
 5007:                             if ($numblank > 0) {
 5008:                                  $values[$i] .= ($scantronconf{'Qoff'} x $numblank);
 5009:                             }
 5010:                             if ($csvbynum{$i} eq 'FirstQuestion') {
 5011:                                 $qstart = $i;
 5012:                                 $found{$csvbynum{$i}} = $values[$i];
 5013:                             } else {
 5014:                                 $found{'FirstQuestion'} .= $values[$i];
 5015:                             }
 5016:                         } elsif (exists($csvbynum{$i})) {
 5017:                             if ($csvoptions{'rem'}) {
 5018:                                 $values[$i] =~ s/^\s+//;
 5019:                             }
 5020:                             if (($csvbynum{$i} eq 'PaperID') && ($csvoptions{'pad'})) {
 5021:                                 while (length($values[$i]) < $scantronconf{$maplength{$csvbynum{$i}}}) {
 5022:                                     $values[$i] = '0'.$values[$i];
 5023:                                 }
 5024:                             }
 5025:                             $found{$csvbynum{$i}} = $values[$i];
 5026:                         }
 5027:                     }
 5028:                     foreach my $item (@ordered) {
 5029:                         my $currlength = 1+length($record);
 5030:                         my $numspaces = $scantronconf{$item} - $currlength;
 5031:                         if ($numspaces > 0) {
 5032:                             $record .= (' ' x $numspaces);
 5033:                         }
 5034:                         if (($mapstart{$item} ne '') && (exists($found{$mapstart{$item}}))) {
 5035:                             unless ($item eq 'Qstart') {
 5036:                                 if (length($found{$mapstart{$item}}) > $scantronconf{$maplength{$item}}) {
 5037:                                     $found{$mapstart{$item}} = substr($found{$mapstart{$item}},0,$scantronconf{$maplength{$item}});
 5038:                                 }
 5039:                             }
 5040:                             $record .= $found{$mapstart{$item}};
 5041:                         }
 5042:                     }
 5043:                     $output .= "$record\n";
 5044:                 }
 5045:                 close($fh);
 5046:                 if ($output) {
 5047:                     if (open(my $fh,'>',$fullpath)) {
 5048:                         print $fh $output;
 5049:                         close($fh);
 5050:                     }
 5051:                 }
 5052:             }
 5053:         }
 5054:         return;
 5055:     }
 5056: }
 5057: 
 5058: sub letter_to_digits {
 5059:     my %lettdig = (
 5060:                     A => 1,
 5061:                     B => 2,
 5062:                     C => 3,
 5063:                     D => 4,
 5064:                     E => 5,
 5065:                     F => 6,
 5066:                     G => 7,
 5067:                     H => 8,
 5068:                     I => 9,
 5069:                     J => 0,
 5070:                   );
 5071:     return %lettdig;
 5072: }
 5073: 
 5074: sub get_scantron_config {
 5075:     my ($which,$cdom) = @_;
 5076:     my @lines = &get_scantronformat_file($cdom);
 5077:     my %config;
 5078:     #FIXME probably should move to XML it has already gotten a bit much now
 5079:     foreach my $line (@lines) {
 5080:         my ($name,$descrip)=split(/:/,$line);
 5081:         if ($name ne $which ) { next; }
 5082:         chomp($line);
 5083:         my @config=split(/:/,$line);
 5084:         $config{'name'}=$config[0];
 5085:         $config{'description'}=$config[1];
 5086:         $config{'CODElocation'}=$config[2];
 5087:         $config{'CODEstart'}=$config[3];
 5088:         $config{'CODElength'}=$config[4];
 5089:         $config{'IDstart'}=$config[5];
 5090:         $config{'IDlength'}=$config[6];
 5091:         $config{'Qstart'}=$config[7];
 5092:         $config{'Qlength'}=$config[8];
 5093:         $config{'Qoff'}=$config[9];
 5094:         $config{'Qon'}=$config[10];
 5095:         $config{'PaperID'}=$config[11];
 5096:         $config{'PaperIDlength'}=$config[12];
 5097:         $config{'FirstName'}=$config[13];
 5098:         $config{'FirstNamelength'}=$config[14];
 5099:         $config{'LastName'}=$config[15];
 5100:         $config{'LastNamelength'}=$config[16];
 5101:         $config{'BubblesPerRow'}=$config[17];
 5102:         last;
 5103:     }
 5104:     return %config;
 5105: }
 5106: 
 5107: sub get_scantronformat_file {
 5108:     my ($cdom) = @_;
 5109:     if ($cdom eq '') {
 5110:         $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
 5111:     }
 5112:     my %domconfig = &get_dom('configuration',['scantron'],$cdom);
 5113:     my $gottab = 0;
 5114:     my @lines;
 5115:     if (ref($domconfig{'scantron'}) eq 'HASH') {
 5116:         if ($domconfig{'scantron'}{'scantronformat'} ne '') {
 5117:             my $formatfile = &getfile($perlvar{'lonDocRoot'}.$domconfig{'scantron'}{'scantronformat'});
 5118:             if ($formatfile ne '-1') {
 5119:                 @lines = split("\n",$formatfile,-1);
 5120:                 $gottab = 1;
 5121:             }
 5122:         }
 5123:     }
 5124:     if (!$gottab) {
 5125:         my $confname = $cdom.'-domainconfig';
 5126:         my $default = $perlvar{'lonDocRoot'}.'/res/'.$cdom.'/'.$confname.'/default.tab';
 5127:         my $formatfile = &getfile($default);
 5128:         if ($formatfile ne '-1') {
 5129:             @lines = split("\n",$formatfile,-1);
 5130:             $gottab = 1;
 5131:         }
 5132:     }
 5133:     if (!$gottab) {
 5134:         my @domains = &current_machine_domains();
 5135:         if (grep(/^\Q$cdom\E$/,@domains)) {
 5136:             if (open(my $fh,'<',$perlvar{'lonTabDir'}.'/scantronformat.tab')) {
 5137:                 @lines = <$fh>;
 5138:                 close($fh);
 5139:             }
 5140:         } else {
 5141:             if (open(my $fh,'<',$perlvar{'lonTabDir'}.'/default_scantronformat.tab')) {
 5142:                 @lines = <$fh>;
 5143:                 close($fh);
 5144:             }
 5145:         }
 5146:         chomp(@lines);
 5147:     }
 5148:     return @lines;
 5149: }
 5150: 
 5151: sub removeuploadedurl {
 5152:     my ($url)=@_;	
 5153:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);    
 5154:     return &removeuserfile($uname,$udom,$fname);
 5155: }
 5156: 
 5157: sub removeuserfile {
 5158:     my ($docuname,$docudom,$fname)=@_;
 5159:     my $home=&homeserver($docuname,$docudom);    
 5160:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
 5161:     if ($result eq 'ok') {	
 5162:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
 5163:             my $metafile = $fname.'.meta';
 5164:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
 5165: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
 5166:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];	   
 5167:             my $sqlresult = 
 5168:                 &update_portfolio_table($docuname,$docudom,$file,
 5169:                                         'portfolio_metadata',$group,
 5170:                                         'delete');
 5171:         }
 5172:     }
 5173:     return $result;
 5174: }
 5175: 
 5176: sub mkdiruserfile {
 5177:     my ($docuname,$docudom,$dir)=@_;
 5178:     my $home=&homeserver($docuname,$docudom);
 5179:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
 5180: }
 5181: 
 5182: sub renameuserfile {
 5183:     my ($docuname,$docudom,$old,$new)=@_;
 5184:     my $home=&homeserver($docuname,$docudom);
 5185:     my $result = &reply("renameuserfile:$docudom:$docuname:".
 5186:                         &escape("$old").':'.&escape("$new"),$home);
 5187:     if ($result eq 'ok') {
 5188:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
 5189:             my $oldmeta = $old.'.meta';
 5190:             my $newmeta = $new.'.meta';
 5191:             my $metaresult = 
 5192:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
 5193: 	    my $url = "/uploaded/$docudom/$docuname/$old";
 5194:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
 5195:             my $sqlresult = 
 5196:                 &update_portfolio_table($docuname,$docudom,$file,
 5197:                                         'portfolio_metadata',$group,
 5198:                                         'delete');
 5199:         }
 5200:     }
 5201:     return $result;
 5202: }
 5203: 
 5204: # ------------------------------------------------------------------------- Log
 5205: 
 5206: sub log {
 5207:     my ($dom,$nam,$hom,$what)=@_;
 5208:     return critical("log:$dom:$nam:$what",$hom);
 5209: }
 5210: 
 5211: # ------------------------------------------------------------------ Course Log
 5212: #
 5213: # This routine flushes several buffers of non-mission-critical nature
 5214: #
 5215: 
 5216: sub flushcourselogs {
 5217:     &logthis('Flushing log buffers');
 5218: #
 5219: # course logs
 5220: # This is a log of all transactions in a course, which can be used
 5221: # for data mining purposes
 5222: #
 5223: # It also collects the courseid database, which lists last transaction
 5224: # times and course titles for all courseids
 5225: #
 5226:     my %courseidbuffer=();
 5227:     foreach my $crsid (keys(%courselogs)) {
 5228:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
 5229: 		          &escape($courselogs{$crsid}),
 5230: 		          $coursehombuf{$crsid}) eq 'ok') {
 5231: 	    delete $courselogs{$crsid};
 5232:         } else {
 5233:             &logthis('Failed to flush log buffer for '.$crsid);
 5234:             if (length($courselogs{$crsid})>40000) {
 5235:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
 5236:                         " exceeded maximum size, deleting.</font>");
 5237:                delete $courselogs{$crsid};
 5238:             }
 5239:         }
 5240:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
 5241:             'description' => $coursedescrbuf{$crsid},
 5242:             'inst_code'    => $courseinstcodebuf{$crsid},
 5243:             'type'        => $coursetypebuf{$crsid},
 5244:             'owner'       => $courseownerbuf{$crsid},
 5245:         };
 5246:     }
 5247: #
 5248: # Write course id database (reverse lookup) to homeserver of courses 
 5249: # Is used in pickcourse
 5250: #
 5251:     foreach my $crs_home (keys(%courseidbuffer)) {
 5252:         my $response = &courseidput(&host_domain($crs_home),
 5253:                                     $courseidbuffer{$crs_home},
 5254:                                     $crs_home,'timeonly');
 5255:     }
 5256: #
 5257: # File accesses
 5258: # Writes to the dynamic metadata of resources to get hit counts, etc.
 5259: #
 5260:     foreach my $entry (keys(%accesshash)) {
 5261:         if ($entry =~ /___count$/) {
 5262:             my ($dom,$name);
 5263:             ($dom,$name,undef)=
 5264: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
 5265:             if (! defined($dom) || $dom eq '' || 
 5266:                 ! defined($name) || $name eq '') {
 5267:                 my $cid = $env{'request.course.id'};
 5268: #
 5269: # FIXME 11/29/2021
 5270: # Typo in rev. 1.458 (2003/12/09)??
 5271: # These should likely by $env{'course.'.$cid.'.domain'} and $env{'course.'.$cid.'.num'}
 5272: #
 5273: # While these remain as $env{'request.'.$cid.'.domain'} and $env{'request.'.$cid.'.num'}
 5274: # $dom and $name will always be null, so the &inc() call will default to storing this data
 5275: # in a nohist_accesscount.db file for the user rather than the course.
 5276: #
 5277: # That said there is a lot of noise in the data being stored.
 5278: # So counts for prtspool/  and adm/ etc. are recorded.
 5279: #
 5280: # A review of which items ending '___count' are written to %accesshash should likely be 
 5281: # made before deciding whether to set these to 'course.' instead of 'request.'
 5282: #
 5283: # Under the current scheme each user receives a nohist_accesscount.db file listing 
 5284: # accesses for things which are not published resources, regardless of course, and
 5285: # there is not a nohist_accesscount.db file in a course, which might log accesses from
 5286: # anyone in the course for things which are not published resources.
 5287: #
 5288: # For an author, nohist_accesscount.db ends up having records for other items
 5289: # mixed up with the legitimate access counts for the author's published resources.
 5290: #
 5291:                 $dom  = $env{'request.'.$cid.'.domain'};
 5292:                 $name = $env{'request.'.$cid.'.num'};
 5293:             }
 5294:             my $value = $accesshash{$entry};
 5295:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
 5296:             my %temphash=($url => $value);
 5297:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
 5298:             if ($result eq 'ok') {
 5299:                 delete $accesshash{$entry};
 5300:             }
 5301:         } else {
 5302:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
 5303:             if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
 5304:             my %temphash=($entry => $accesshash{$entry});
 5305:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
 5306:                 delete $accesshash{$entry};
 5307:             }
 5308:         }
 5309:     }
 5310: #
 5311: # Roles
 5312: # Reverse lookup of user roles for course faculty/staff and co-authorship
 5313: #
 5314:     foreach my $entry (keys(%userrolehash)) {
 5315:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
 5316: 	    split(/\:/,$entry);
 5317:         if (&put('nohist_userroles',
 5318:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
 5319:                 $rudom,$runame) eq 'ok') {
 5320: 	    delete $userrolehash{$entry};
 5321:         }
 5322:     }
 5323: #
 5324: # Reverse lookup of domain roles (dc, ad, li, sc, dh, da, au)
 5325: #
 5326:     my %domrolebuffer = ();
 5327:     foreach my $entry (keys(%domainrolehash)) {
 5328:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
 5329:         if ($domrolebuffer{$rudom}) {
 5330:             $domrolebuffer{$rudom}.='&'.&escape($entry).
 5331:                       '='.&escape($domainrolehash{$entry});
 5332:         } else {
 5333:             $domrolebuffer{$rudom}.=&escape($entry).
 5334:                       '='.&escape($domainrolehash{$entry});
 5335:         }
 5336:         delete $domainrolehash{$entry};
 5337:     }
 5338:     foreach my $dom (keys(%domrolebuffer)) {
 5339: 	my %servers;
 5340: 	if (defined(&domain($dom,'primary'))) {
 5341: 	    my $primary=&domain($dom,'primary');
 5342: 	    my $hostname=&hostname($primary);
 5343: 	    $servers{$primary} = $hostname;
 5344: 	} else { 
 5345: 	    %servers = &get_servers($dom,'library');
 5346: 	}
 5347: 	foreach my $tryserver (keys(%servers)) {
 5348: 	    if (&reply('domroleput:'.$dom.':'.
 5349: 		       $domrolebuffer{$dom},$tryserver) eq 'ok') {
 5350: 		last;
 5351: 	    } else {  
 5352: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
 5353: 	    }
 5354:         }
 5355:     }
 5356:     $dumpcount++;
 5357: }
 5358: 
 5359: sub courselog {
 5360:     my $what=shift;
 5361:     $what=time.':'.$what;
 5362:     unless ($env{'request.course.id'}) { return ''; }
 5363:     $coursedombuf{$env{'request.course.id'}}=
 5364:        $env{'course.'.$env{'request.course.id'}.'.domain'};
 5365:     $coursenumbuf{$env{'request.course.id'}}=
 5366:        $env{'course.'.$env{'request.course.id'}.'.num'};
 5367:     $coursehombuf{$env{'request.course.id'}}=
 5368:        $env{'course.'.$env{'request.course.id'}.'.home'};
 5369:     $coursedescrbuf{$env{'request.course.id'}}=
 5370:        $env{'course.'.$env{'request.course.id'}.'.description'};
 5371:     $courseinstcodebuf{$env{'request.course.id'}}=
 5372:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
 5373:     $courseownerbuf{$env{'request.course.id'}}=
 5374:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
 5375:     $coursetypebuf{$env{'request.course.id'}}=
 5376:        $env{'course.'.$env{'request.course.id'}.'.type'};
 5377:     if (defined $courselogs{$env{'request.course.id'}}) {
 5378: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
 5379:     } else {
 5380: 	$courselogs{$env{'request.course.id'}}.=$what;
 5381:     }
 5382:     if (length($courselogs{$env{'request.course.id'}})>4048) {
 5383: 	&flushcourselogs();
 5384:     }
 5385: }
 5386: 
 5387: sub courseacclog {
 5388:     my $fnsymb=shift;
 5389:     unless ($env{'request.course.id'}) { return ''; }
 5390:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
 5391:     if ($fnsymb=~/$LONCAPA::assess_re/) {
 5392:         $what.=':POST';
 5393:         # FIXME: Probably ought to escape things....
 5394: 	foreach my $key (keys(%env)) {
 5395:             if ($key=~/^form\.(.*)/) {
 5396:                 my $formitem = $1;
 5397:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
 5398:                     $what.=':'.$formitem.'='.$env{$key};
 5399:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
 5400:                     if ($formitem eq 'proctorpassword') {
 5401:                         $what.=':'.$formitem.'=' . '*' x length($env{$key});
 5402:                     } else {
 5403:                         $what.=':'.$formitem.'='.$env{$key};
 5404:                     }
 5405:                 }
 5406:             }
 5407:         }
 5408:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
 5409:         # FIXME: We should not be depending on a form parameter that someone
 5410:         # editing lonsearchcat.pm might change in the future.
 5411:         if ($env{'form.phase'} eq 'course_search') {
 5412:             $what.= ':POST';
 5413:             # FIXME: Probably ought to escape things....
 5414:             foreach my $element ('courseexp','crsfulltext','crsrelated',
 5415:                                  'crsdiscuss') {
 5416:                 $what.=':'.$element.'='.$env{'form.'.$element};
 5417:             }
 5418:         }
 5419:     }
 5420:     &courselog($what);
 5421: }
 5422: 
 5423: sub countacc {
 5424:     my $url=&declutter(shift);
 5425:     return if (! defined($url) || $url eq '');
 5426:     unless ($env{'request.course.id'}) { return ''; }
 5427: #
 5428: # Mark that this url was used in this course
 5429: #
 5430:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
 5431: #
 5432: # Increase the access count for this resource in this child process
 5433: #
 5434:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
 5435:     $accesshash{$key}++;
 5436: }
 5437: 
 5438: sub linklog {
 5439:     my ($from,$to)=@_;
 5440:     $from=&declutter($from);
 5441:     $to=&declutter($to);
 5442:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
 5443:     $accesshash{$to.'___'.$from.'___goto'}=1;
 5444: }
 5445: 
 5446: sub statslog {
 5447:     my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
 5448:     if ($users<2) { return; }
 5449:     my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
 5450:             'course'       => $env{'request.course.id'},
 5451:             'sections'     => '"all"',
 5452:             'num_students' => $users,
 5453:             'part'         => $part,
 5454:             'symb'         => $symb,
 5455:             'mean_tries'   => $av_attempts,
 5456:             'deg_of_diff'  => $degdiff});
 5457:     foreach my $key (keys(%dynstore)) {
 5458:         $accesshash{$key}=$dynstore{$key};
 5459:     }
 5460: }
 5461:   
 5462: sub userrolelog {
 5463:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
 5464:     if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
 5465:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 5466:        $userrolehash
 5467:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 5468:                     =$tend.':'.$tstart;
 5469:     }
 5470:     if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
 5471:        $userrolehash
 5472:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
 5473:                     =$tend.':'.$tstart;
 5474:     }
 5475:     if ($trole =~ /^(dc|ad|li|au|dg|sc|dh|da)/ ) {
 5476:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 5477:        $domainrolehash
 5478:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 5479:                     = $tend.':'.$tstart;
 5480:     }
 5481: }
 5482: 
 5483: sub courserolelog {
 5484:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,
 5485:         $context,$othdomby,$requester)=@_;
 5486:     if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
 5487:         my $cdom = $1;
 5488:         my $cnum = $2;
 5489:         my $sec = $3;
 5490:         my $namespace = 'rolelog';
 5491:         my %storehash = (
 5492:                            role    => $trole,
 5493:                            start   => $tstart,
 5494:                            end     => $tend,
 5495:                            selfenroll => $selfenroll,
 5496:                            context    => $context,
 5497:                         );
 5498:         if ($othdomby) {
 5499:             if ($othdomby eq 'othdombydc') {
 5500:                 $storehash{'approval'} = 'domain';
 5501:             } elsif ($othdomby eq 'othdombyuser') {
 5502:                 $storehash{'approval'} = 'user'; 
 5503:             }
 5504:             if ($requester ne '') {
 5505:                 $storehash{'requester'} = $requester;
 5506:             }
 5507:         }
 5508:         if ($trole eq 'gr') {
 5509:             $namespace = 'groupslog';
 5510:             $storehash{'group'} = $sec;
 5511:         } else {
 5512:             $storehash{'section'} = $sec;
 5513:             my ($curruserdomstr,$newuserdomstr);
 5514:             if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.userdomains'})) {
 5515:                 $curruserdomstr = $env{'course.'.$env{'request.course.id'}.'.internal.userdomains'};
 5516:             } else {
 5517:                 my %courseinfo = &coursedescription($cdom.'/'.$cnum);
 5518:                 $curruserdomstr = $courseinfo{'internal.userdomains'};
 5519:             }
 5520:             if ($curruserdomstr ne '') {
 5521:                 my @udoms = split(/,/,$curruserdomstr);
 5522:                 unless (grep(/^\Q$domain\E/,@udoms)) {
 5523:                     push(@udoms,$domain);
 5524:                     $newuserdomstr = join(',',sort(@udoms));
 5525:                 }
 5526:             } else {
 5527:                 $newuserdomstr = $domain;
 5528:             }
 5529:             if ($newuserdomstr ne '') {
 5530:                 my $putresult = &put('environment',{ 'internal.userdomains' => $newuserdomstr },
 5531:                                      $cdom,$cnum);
 5532:                 if ($putresult eq 'ok') {
 5533:                     unless (($selfenroll) || ($context eq 'selfenroll')) { 
 5534:                         if (($context eq 'createcourse') || ($context eq 'requestcourses') ||
 5535:                             ($context eq 'automated') || ($context eq 'domain')) {
 5536:                             $env{'course.'.$cdom.'_'.$cnum.'.internal.userdomains'} = $newuserdomstr;
 5537:                         } elsif ($env{'request.course.id'} eq $cdom.'_'.$cnum) {
 5538:                             &appenv({'course.'.$cdom.'_'.$cnum.'.internal.userdomains' => $newuserdomstr});
 5539:                         }
 5540:                     }
 5541:                 }
 5542:             }
 5543:         }
 5544:         &write_log('course',$namespace,\%storehash,$delflag,$username,
 5545:                    $domain,$cnum,$cdom);
 5546:         if (($trole ne 'st') || ($sec ne '')) {
 5547:             &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
 5548:         }
 5549:     }
 5550:     return;
 5551: }
 5552: 
 5553: sub domainrolelog {
 5554:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,
 5555:         $context,$othdomby,$requester)=@_;
 5556:     if ($area =~ m{^/($match_domain)/$}) {
 5557:         my $cdom = $1;
 5558:         my $domconfiguser = &get_domainconfiguser($cdom);
 5559:         my $namespace = 'rolelog';
 5560:         my %storehash = (
 5561:                            role    => $trole,
 5562:                            start   => $tstart,
 5563:                            end     => $tend,
 5564:                            context => $context,
 5565:                         );
 5566:         if ($othdomby) {
 5567:             if ($othdomby eq 'othdombydc') {
 5568:                 $storehash{'approval'} = 'domain';
 5569:             } elsif ($othdomby eq 'othdombyuser') {
 5570:                 $storehash{'approval'} = 'user';
 5571:             }
 5572:             if ($requester ne '') {
 5573:                 $storehash{'requester'} = $requester;
 5574:             }
 5575:         }
 5576:         &write_log('domain',$namespace,\%storehash,$delflag,$username,
 5577:                    $domain,$domconfiguser,$cdom);
 5578:     }
 5579:     return;
 5580: 
 5581: }
 5582: 
 5583: sub coauthorrolelog {
 5584:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,
 5585:         $context,$othdomby,$requester)=@_;
 5586:     if ($area =~ m{^/($match_domain)/($match_username)$}) {
 5587:         my $audom = $1;
 5588:         my $auname = $2;
 5589:         my $namespace = 'rolelog';
 5590:         my %storehash = (
 5591:                            role    => $trole,
 5592:                            start   => $tstart,
 5593:                            end     => $tend,
 5594:                            context => $context,
 5595:                         );
 5596:         if ($othdomby) {
 5597:             if ($othdomby eq 'othdombydc') {
 5598:                 $storehash{'approval'} = 'domain';
 5599:             } elsif ($othdomby eq 'othdombyuser') {
 5600:                 $storehash{'approval'} = 'user';
 5601:             }
 5602:             if ($requester ne '') {
 5603:                 $storehash{'requester'} = $requester;
 5604:             }
 5605:         }
 5606:         &write_log('author',$namespace,\%storehash,$delflag,$username,
 5607:                    $domain,$auname,$audom);
 5608:     }
 5609:     return;
 5610: }
 5611: 
 5612: sub get_course_adv_roles {
 5613:     my ($cid,$codes) = @_;
 5614:     $cid=$env{'request.course.id'} unless (defined($cid));
 5615:     my %coursehash=&coursedescription($cid);
 5616:     my $crstype = &Apache::loncommon::course_type($cid);
 5617:     my %nothide=();
 5618:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 5619:         if ($user !~ /:/) {
 5620: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
 5621:         } else {
 5622:             $nothide{$user}=1;
 5623:         }
 5624:     }
 5625:     my @possdoms = ($coursehash{'domain'});
 5626:     if ($coursehash{'checkforpriv'}) {
 5627:         push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
 5628:     }
 5629:     my %returnhash=();
 5630:     my %dumphash=
 5631:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
 5632:     my $now=time;
 5633:     my %privileged;
 5634:     foreach my $entry (keys(%dumphash)) {
 5635: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
 5636:         if (($tstart) && ($tstart<0)) { next; }
 5637:         if (($tend) && ($tend<$now)) { next; }
 5638:         if (($tstart) && ($now<$tstart)) { next; }
 5639:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
 5640: 	if ($username eq '' || $domain eq '') { next; }
 5641:         if ((&privileged($username,$domain,\@possdoms)) &&
 5642:             (!$nothide{$username.':'.$domain})) { next; }
 5643: 	if ($role eq 'cr') { next; }
 5644:         if ($codes) {
 5645:             if ($section) { $role .= ':'.$section; }
 5646:             if ($returnhash{$role}) {
 5647:                 $returnhash{$role}.=','.$username.':'.$domain;
 5648:             } else {
 5649:                 $returnhash{$role}=$username.':'.$domain;
 5650:             }
 5651:         } else {
 5652:             my $key=&plaintext($role,$crstype);
 5653:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
 5654:             if ($returnhash{$key}) {
 5655: 	        $returnhash{$key}.=','.$username.':'.$domain;
 5656:             } else {
 5657:                 $returnhash{$key}=$username.':'.$domain;
 5658:             }
 5659:         }
 5660:     }
 5661:     return %returnhash;
 5662: }
 5663: 
 5664: sub get_my_roles {
 5665:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
 5666:     unless (defined($uname)) { $uname=$env{'user.name'}; }
 5667:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
 5668:     my (%dumphash,%nothide);
 5669:     if ($context eq 'userroles') {
 5670:         %dumphash = &dump('roles',$udom,$uname);
 5671:     } else {
 5672:         %dumphash = &dump('nohist_userroles',$udom,$uname);
 5673:         if ($hidepriv) {
 5674:             my %coursehash=&coursedescription($udom.'_'.$uname);
 5675:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 5676:                 if ($user !~ /:/) {
 5677:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
 5678:                 } else {
 5679:                     $nothide{$user} = 1;
 5680:                 }
 5681:             }
 5682:         }
 5683:     }
 5684:     my %returnhash=();
 5685:     my $now=time;
 5686:     my %privileged;
 5687:     foreach my $entry (keys(%dumphash)) {
 5688:         my ($role,$tend,$tstart);
 5689:         if ($context eq 'userroles') {
 5690:             next if ($entry =~ /^rolesdef/);
 5691: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
 5692:         } else {
 5693:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
 5694:         }
 5695:         if (($tstart) && ($tstart<0)) { next; }
 5696:         my $status = 'active';
 5697:         if (($tend) && ($tend<=$now)) {
 5698:             $status = 'previous';
 5699:         } 
 5700:         if (($tstart) && ($now<$tstart)) {
 5701:             $status = 'future';
 5702:         }
 5703:         if (ref($types) eq 'ARRAY') {
 5704:             if (!grep(/^\Q$status\E$/,@{$types})) {
 5705:                 next;
 5706:             } 
 5707:         } else {
 5708:             if ($status ne 'active') {
 5709:                 next;
 5710:             }
 5711:         }
 5712:         my ($rolecode,$username,$domain,$section,$area);
 5713:         if ($context eq 'userroles') {
 5714:             ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
 5715:             (undef,$domain,$username,$section) = split(/\//,$area);
 5716:         } else {
 5717:             ($role,$username,$domain,$section) = split(/\:/,$entry);
 5718:         }
 5719:         if (ref($roledoms) eq 'ARRAY') {
 5720:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
 5721:                 next;
 5722:             }
 5723:         }
 5724:         if (ref($roles) eq 'ARRAY') {
 5725:             if (!grep(/^\Q$role\E$/,@{$roles})) {
 5726:                 if ($role =~ /^cr\//) {
 5727:                     if (!grep(/^cr$/,@{$roles})) {
 5728:                         next;
 5729:                     }
 5730:                 } elsif ($role =~ /^gr\//) {
 5731:                     if (!grep(/^gr$/,@{$roles})) {
 5732:                         next;
 5733:                     }
 5734:                 } else {
 5735:                     next;
 5736:                 }
 5737:             }
 5738:         }
 5739:         if ($hidepriv) {
 5740:             my @privroles = ('dc','su');
 5741:             if ($context eq 'userroles') {
 5742:                 next if (grep(/^\Q$role\E$/,@privroles));
 5743:             } else {
 5744:                 my $possdoms = [$domain];
 5745:                 if (ref($roledoms) eq 'ARRAY') {
 5746:                    push(@{$possdoms},@{$roledoms}); 
 5747:                 }
 5748:                 if (&privileged($username,$domain,$possdoms,\@privroles)) {
 5749:                     if (!$nothide{$username.':'.$domain}) {
 5750:                         next;
 5751:                     }
 5752:                 }
 5753:             }
 5754:         }
 5755:         if ($withsec) {
 5756:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
 5757:                 $tstart.':'.$tend;
 5758:         } else {
 5759:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
 5760:         }
 5761:     }
 5762:     return %returnhash;
 5763: }
 5764: 
 5765: sub get_all_adhocroles {
 5766:     my ($dom) = @_;
 5767:     my @roles_by_num = ();
 5768:     my %domdefaults = &get_domain_defaults($dom);
 5769:     my (%description,%access_in_dom,%access_info);
 5770:     if (ref($domdefaults{'adhocroles'}) eq 'HASH') {
 5771:         my $count = 0;
 5772:         my %domcurrent = %{$domdefaults{'adhocroles'}};
 5773:         my %ordered;
 5774:         foreach my $role (sort(keys(%domcurrent))) {
 5775:             my ($order,$desc,$access_in_dom);
 5776:             if (ref($domcurrent{$role}) eq 'HASH') {
 5777:                 $order = $domcurrent{$role}{'order'};
 5778:                 $desc = $domcurrent{$role}{'desc'};
 5779:                 $access_in_dom{$role} = $domcurrent{$role}{'access'};
 5780:                 $access_info{$role} = $domcurrent{$role}{$access_in_dom{$role}};
 5781:             }
 5782:             if ($order eq '') {
 5783:                 $order = $count;
 5784:             }
 5785:             $ordered{$order} = $role;
 5786:             if ($desc ne '') {
 5787:                 $description{$role} = $desc;
 5788:             } else {
 5789:                 $description{$role}= $role;
 5790:             }
 5791:             $count++;
 5792:         }
 5793:         foreach my $item (sort {$a <=> $b } (keys(%ordered))) {
 5794:             push(@roles_by_num,$ordered{$item});
 5795:         }
 5796:     }
 5797:     return (\@roles_by_num,\%description,\%access_in_dom,\%access_info);
 5798: }
 5799: 
 5800: sub get_my_adhocroles {
 5801:     my ($cid,$checkreg) = @_;
 5802:     my ($cdom,$cnum,%info,@possroles,$description,$roles_by_num);
 5803:     if ($env{'request.course.id'} eq $cid) {
 5804:         $cdom = $env{'course.'.$cid.'.domain'};
 5805:         $cnum = $env{'course.'.$cid.'.num'};
 5806:         $info{'internal.coursecode'} = $env{'course.'.$cid.'.internal.coursecode'};
 5807:     } elsif ($cid =~ /^($match_domain)_($match_courseid)$/) {
 5808:         $cdom = $1;
 5809:         $cnum = $2;
 5810:         %info = &get('environment',['internal.coursecode'],
 5811:                      $cdom,$cnum);
 5812:     }
 5813:     if (($info{'internal.coursecode'} ne '') && ($checkreg)) {
 5814:         my $user = $env{'user.name'}.':'.$env{'user.domain'};
 5815:         my %rosterhash = &get('classlist',[$user],$cdom,$cnum);
 5816:         if ($rosterhash{$user} ne '') {
 5817:             my $type = (split(/:/,$rosterhash{$user}))[5];
 5818:             return ([],{}) if ($type eq 'auto');
 5819:         }
 5820:     }
 5821:     if (($cdom ne '') && ($cnum ne ''))  {
 5822:         if (($env{"user.role.dh./$cdom/"}) || ($env{"user.role.da./$cdom/"})) {
 5823:             my $then=$env{'user.login.time'};
 5824:             my $update=$env{'user.update.time'};
 5825:             if (!$update) {
 5826:                 $update = $then;
 5827:             }
 5828:             my @liveroles;
 5829:             foreach my $role ('dh','da') {
 5830:                 if ($env{"user.role.$role./$cdom/"}) {
 5831:                     my ($tstart,$tend)=split(/\./,$env{"user.role.$role./$cdom/"});
 5832:                     my $limit = $update;
 5833:                     if ($env{'request.role'} eq "$role./$cdom/") {
 5834:                         $limit = $then;
 5835:                     }
 5836:                     my $activerole = 1;
 5837:                     if ($tstart && $tstart>$limit) { $activerole = 0; }
 5838:                     if ($tend   && $tend  <$limit) { $activerole = 0; }
 5839:                     if ($activerole) {
 5840:                         push(@liveroles,$role);
 5841:                     }
 5842:                 }
 5843:             }
 5844:             if (@liveroles) {
 5845:                 if (&homeserver($cnum,$cdom) ne 'no_host') {
 5846:                     my ($accessref,$accessinfo,%access_in_dom);
 5847:                     ($roles_by_num,$description,$accessref,$accessinfo) = &get_all_adhocroles($cdom);
 5848:                     if (ref($roles_by_num) eq 'ARRAY') {
 5849:                         if (@{$roles_by_num}) {
 5850:                             my %settings;
 5851:                             if ($env{'request.course.id'} eq $cid) {
 5852:                                 foreach my $envkey (keys(%env)) {
 5853:                                     if ($envkey =~ /^\Qcourse.$cid.\E(internal\.adhoc.+)$/) {
 5854:                                         $settings{$1} = $env{$envkey};
 5855:                                     }
 5856:                                 }
 5857:                             } else {
 5858:                                 %settings = &dump('environment',$cdom,$cnum,'internal\.adhoc');
 5859:                             }
 5860:                             my %setincrs;
 5861:                             if ($settings{'internal.adhocaccess'}) {
 5862:                                 map { $setincrs{$_} = 1; } split(/,/,$settings{'internal.adhocaccess'});
 5863:                             }
 5864:                             my @statuses;
 5865:                             if ($env{'environment.inststatus'}) {
 5866:                                 @statuses = split(/,/,$env{'environment.inststatus'});
 5867:                             }
 5868:                             my $user = $env{'user.name'}.':'.$env{'user.domain'};
 5869:                             if (ref($accessref) eq 'HASH') {
 5870:                                 %access_in_dom = %{$accessref};
 5871:                             }
 5872:                             foreach my $role (@{$roles_by_num}) {
 5873:                                 my ($curraccess,@okstatus,@personnel);
 5874:                                 if ($setincrs{$role}) {
 5875:                                     ($curraccess,my $rest) = split(/=/,$settings{'internal.adhoc.'.$role});
 5876:                                     if ($curraccess eq 'status') {
 5877:                                         @okstatus = split(/\&/,$rest);
 5878:                                     } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
 5879:                                         @personnel = split(/\&/,$rest);
 5880:                                     }
 5881:                                 } else {
 5882:                                     $curraccess = $access_in_dom{$role};
 5883:                                     if (ref($accessinfo) eq 'HASH') {
 5884:                                         if ($curraccess eq 'status') {
 5885:                                             if (ref($accessinfo->{$role}) eq 'ARRAY') {
 5886:                                                 @okstatus = @{$accessinfo->{$role}};
 5887:                                             }
 5888:                                         } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
 5889:                                             if (ref($accessinfo->{$role}) eq 'ARRAY') {
 5890:                                                 @personnel = @{$accessinfo->{$role}};
 5891:                                             }
 5892:                                         }
 5893:                                     }
 5894:                                 }
 5895:                                 if ($curraccess eq 'none') {
 5896:                                     next;
 5897:                                 } elsif ($curraccess eq 'all') {
 5898:                                     push(@possroles,$role);
 5899:                                 } elsif ($curraccess eq 'dh') {
 5900:                                     if (grep(/^dh$/,@liveroles)) {
 5901:                                         push(@possroles,$role);
 5902:                                     } else {
 5903:                                         next;
 5904:                                     }
 5905:                                 } elsif ($curraccess eq 'da') {
 5906:                                     if (grep(/^da$/,@liveroles)) {
 5907:                                         push(@possroles,$role);
 5908:                                     } else {
 5909:                                         next;
 5910:                                     }
 5911:                                 } elsif ($curraccess eq 'status') {
 5912:                                     if (@okstatus) {
 5913:                                         if (!@statuses) {
 5914:                                             if (grep(/^default$/,@okstatus)) {
 5915:                                                 push(@possroles,$role);
 5916:                                             }
 5917:                                         } else {
 5918:                                             foreach my $status (@okstatus) {
 5919:                                                 if (grep(/^\Q$status\E$/,@statuses)) {
 5920:                                                     push(@possroles,$role);
 5921:                                                     last;
 5922:                                                 }
 5923:                                             }
 5924:                                         }
 5925:                                     }
 5926:                                 } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
 5927:                                     if (grep(/^\Q$user\E$/,@personnel)) {
 5928:                                         if ($curraccess eq 'exc') {
 5929:                                             push(@possroles,$role);
 5930:                                         }
 5931:                                     } elsif ($curraccess eq 'inc') {
 5932:                                         push(@possroles,$role);
 5933:                                     }
 5934:                                 }
 5935:                             }
 5936:                         }
 5937:                     }
 5938:                 }
 5939:             }
 5940:         }
 5941:     }
 5942:     unless (ref($description) eq 'HASH') {
 5943:         if (ref($roles_by_num) eq 'ARRAY') {
 5944:             my %desc;
 5945:             map { $desc{$_} = $_; } (@{$roles_by_num});
 5946:             $description = \%desc;
 5947:         } else {
 5948:             $description = {};
 5949:         }
 5950:     }
 5951:     return (\@possroles,$description);
 5952: }
 5953: 
 5954: # ----------------------------------------------------- Frontpage Announcements
 5955: #
 5956: #
 5957: 
 5958: sub postannounce {
 5959:     my ($server,$text)=@_;
 5960:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
 5961:     unless ($text=~/\w/) { $text=''; }
 5962:     return &reply('setannounce:'.&escape($text),$server);
 5963: }
 5964: 
 5965: sub getannounce {
 5966: 
 5967:     if (open(my $fh,"<",$perlvar{'lonDocRoot'}.'/announcement.txt')) {
 5968: 	my $announcement='';
 5969: 	while (my $line = <$fh>) { $announcement .= $line; }
 5970: 	close($fh);
 5971: 	if ($announcement=~/\w/) { 
 5972: 	    return 
 5973:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
 5974:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
 5975: 	} else {
 5976: 	    return '';
 5977: 	}
 5978:     } else {
 5979: 	return '';
 5980:     }
 5981: }
 5982: 
 5983: # ---------------------------------------------------------- Course ID routines
 5984: # Deal with domain's nohist_courseid.db files
 5985: #
 5986: 
 5987: sub courseidput {
 5988:     my ($domain,$storehash,$coursehome,$caller) = @_;
 5989:     return unless (ref($storehash) eq 'HASH');
 5990:     my $outcome;
 5991:     if ($caller eq 'timeonly') {
 5992:         my $cids = '';
 5993:         foreach my $item (keys(%$storehash)) {
 5994:             $cids.=&escape($item).'&';
 5995:         }
 5996:         $cids=~s/\&$//;
 5997:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
 5998:                           $coursehome);       
 5999:     } else {
 6000:         my $items = '';
 6001:         foreach my $item (keys(%$storehash)) {
 6002:             $items.= &escape($item).'='.
 6003:                      &freeze_escape($$storehash{$item}).'&';
 6004:         }
 6005:         $items=~s/\&$//;
 6006:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
 6007:                           $coursehome);
 6008:     }
 6009:     if ($outcome eq 'unknown_cmd') {
 6010:         my $what;
 6011:         foreach my $cid (keys(%$storehash)) {
 6012:             $what .= &escape($cid).'=';
 6013:             foreach my $item ('description','inst_code','owner','type') {
 6014:                 $what .= &escape($storehash->{$cid}{$item}).':';
 6015:             }
 6016:             $what =~ s/\:$/&/;
 6017:         }
 6018:         $what =~ s/\&$//;  
 6019:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
 6020:     } else {
 6021:         return $outcome;
 6022:     }
 6023: }
 6024: 
 6025: sub courseiddump {
 6026:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
 6027:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
 6028:         $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
 6029:         $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner,
 6030:         $hasuniquecode,$reqcrsdom,$reqinstcode)=@_;
 6031:     my $as_hash = 1;
 6032:     my %returnhash;
 6033:     if (!$domfilter) { $domfilter=''; }
 6034:     my %libserv = &all_library();
 6035:     foreach my $tryserver (keys(%libserv)) {
 6036:         if ( (  $hostidflag == 1 
 6037: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
 6038: 	     || (!defined($hostidflag)) ) {
 6039: 
 6040: 	    if (($domfilter eq '') ||
 6041: 		(&host_domain($tryserver) eq $domfilter)) {
 6042:                 my $rep;
 6043:                 if (grep { $_ eq $tryserver } current_machine_ids()) {
 6044:                     $rep = LONCAPA::Lond::dump_course_id_handler(
 6045:                         join(":", (&host_domain($tryserver), $sincefilter, 
 6046:                                 &escape($descfilter), &escape($instcodefilter), 
 6047:                                 &escape($ownerfilter), &escape($coursefilter),
 6048:                                 &escape($typefilter), &escape($regexp_ok), 
 6049:                                 $as_hash, &escape($selfenrollonly), 
 6050:                                 &escape($catfilter), $showhidden, $caller, 
 6051:                                 &escape($cloner), &escape($cc_clone), $cloneonly, 
 6052:                                 &escape($createdbefore), &escape($createdafter), 
 6053:                                 &escape($creationcontext),$domcloner,$hasuniquecode,
 6054:                                 $reqcrsdom,&escape($reqinstcode))));
 6055:                 } else {
 6056:                     $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
 6057:                              $sincefilter.':'.&escape($descfilter).':'.
 6058:                              &escape($instcodefilter).':'.&escape($ownerfilter).
 6059:                              ':'.&escape($coursefilter).':'.&escape($typefilter).
 6060:                              ':'.&escape($regexp_ok).':'.$as_hash.':'.
 6061:                              &escape($selfenrollonly).':'.&escape($catfilter).':'.
 6062:                              $showhidden.':'.$caller.':'.&escape($cloner).':'.
 6063:                              &escape($cc_clone).':'.$cloneonly.':'.
 6064:                              &escape($createdbefore).':'.&escape($createdafter).':'.
 6065:                              &escape($creationcontext).':'.$domcloner.':'.$hasuniquecode.
 6066:                              ':'.$reqcrsdom.':'.&escape($reqinstcode),$tryserver);
 6067:                 }
 6068:                      
 6069:                 my @pairs=split(/\&/,$rep);
 6070:                 foreach my $item (@pairs) {
 6071:                     my ($key,$value)=split(/\=/,$item,2);
 6072:                     $key = &unescape($key);
 6073:                     next if ($key =~ /^error: 2 /);
 6074:                     my $result = &thaw_unescape($value);
 6075:                     if (ref($result) eq 'HASH') {
 6076:                         $returnhash{$key}=$result;
 6077:                     } else {
 6078:                         my @responses = split(/:/,$value);
 6079:                         my @items = ('description','inst_code','owner','type');
 6080:                         for (my $i=0; $i<@responses; $i++) {
 6081:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
 6082:                         }
 6083:                     }
 6084:                 }
 6085:             }
 6086:         }
 6087:     }
 6088:     return %returnhash;
 6089: }
 6090: 
 6091: sub courselastaccess {
 6092:     my ($cdom,$cnum,$hostidref) = @_;
 6093:     my %returnhash;
 6094:     if ($cdom && $cnum) {
 6095:         my $chome = &homeserver($cnum,$cdom);
 6096:         if ($chome ne 'no_host') {
 6097:             my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
 6098:             &extract_lastaccess(\%returnhash,$rep);
 6099:         }
 6100:     } else {
 6101:         if (!$cdom) { $cdom=''; }
 6102:         my %libserv = &all_library();
 6103:         foreach my $tryserver (keys(%libserv)) {
 6104:             if (ref($hostidref) eq 'ARRAY') {
 6105:                 next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
 6106:             } 
 6107:             if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
 6108:                 my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
 6109:                 &extract_lastaccess(\%returnhash,$rep);
 6110:             }
 6111:         }
 6112:     }
 6113:     return %returnhash;
 6114: }
 6115: 
 6116: sub extract_lastaccess {
 6117:     my ($returnhash,$rep) = @_;
 6118:     if (ref($returnhash) eq 'HASH') {
 6119:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' || 
 6120:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
 6121:                  $rep eq '') {
 6122:             my @pairs=split(/\&/,$rep);
 6123:             foreach my $item (@pairs) {
 6124:                 my ($key,$value)=split(/\=/,$item,2);
 6125:                 $key = &unescape($key);
 6126:                 next if ($key =~ /^error: 2 /);
 6127:                 $returnhash->{$key} = &thaw_unescape($value);
 6128:             }
 6129:         }
 6130:     }
 6131:     return;
 6132: }
 6133: 
 6134: # ---------------------------------------------------------- DC e-mail
 6135: 
 6136: sub dcmailput {
 6137:     my ($domain,$msgid,$message,$server)=@_;
 6138:     my $status = &critical(
 6139:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
 6140:        &escape($message),$server);
 6141:     return $status;
 6142: }
 6143: 
 6144: sub dcmaildump {
 6145:     my ($dom,$startdate,$enddate,$senders) = @_;
 6146:     my %returnhash=();
 6147: 
 6148:     if (defined(&domain($dom,'primary'))) {
 6149:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
 6150:                                                          &escape($enddate).':';
 6151: 	my @esc_senders=map { &escape($_)} @$senders;
 6152: 	$cmd.=&escape(join('&',@esc_senders));
 6153: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
 6154:             my ($key,$value) = split(/\=/,$line,2);
 6155:             if (($key) && ($value)) {
 6156:                 $returnhash{&unescape($key)} = &unescape($value);
 6157:             }
 6158:         }
 6159:     }
 6160:     return %returnhash;
 6161: }
 6162: # ---------------------------------------------------------- Domain roles
 6163: 
 6164: sub get_domain_roles {
 6165:     my ($dom,$roles,$startdate,$enddate)=@_;
 6166:     if ((!defined($startdate)) || ($startdate eq '')) {
 6167:         $startdate = '.';
 6168:     }
 6169:     if ((!defined($enddate)) || ($enddate eq '')) {
 6170:         $enddate = '.';
 6171:     }
 6172:     my $rolelist;
 6173:     if (ref($roles) eq 'ARRAY') {
 6174:         $rolelist = join('&',@{$roles});
 6175:     }
 6176:     my %personnel = ();
 6177: 
 6178:     my %servers = &get_servers($dom,'library');
 6179:     foreach my $tryserver (keys(%servers)) {
 6180: 	%{$personnel{$tryserver}}=();
 6181: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
 6182: 					    &escape($startdate).':'.
 6183: 					    &escape($enddate).':'.
 6184: 					    &escape($rolelist), $tryserver))) {
 6185: 	    my ($key,$value) = split(/\=/,$line,2);
 6186: 	    if (($key) && ($value)) {
 6187: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
 6188: 	    }
 6189: 	}
 6190:     }
 6191:     return %personnel;
 6192: }
 6193: 
 6194: sub get_active_domroles {
 6195:     my ($dom,$roles) = @_;
 6196:     return () unless (ref($roles) eq 'ARRAY');
 6197:     my $now = time;
 6198:     my %dompersonnel = &get_domain_roles($dom,$roles,$now,$now);
 6199:     my %domroles;
 6200:     foreach my $server (keys(%dompersonnel)) {
 6201:         foreach my $user (sort(keys(%{$dompersonnel{$server}}))) {
 6202:             my ($trole,$uname,$udom,$runame,$rudom,$rsec) = split(/:/,$user);
 6203:             $domroles{$uname.':'.$udom} = $dompersonnel{$server}{$user};
 6204:         }
 6205:     }
 6206:     return %domroles;
 6207: }
 6208: 
 6209: # ----------------------------------------------------------- Interval timing 
 6210: 
 6211: {
 6212: # Caches needed for speedup of navmaps
 6213: # We don't want to cache this for very long at all (5 seconds at most)
 6214: # 
 6215: # The user for whom we cache
 6216: my $cachedkey='';
 6217: # The cached times for this user
 6218: my %cachedtimes=();
 6219: # When this was last done
 6220: my $cachedtime='';
 6221: 
 6222: sub load_all_first_access {
 6223:     my ($uname,$udom,$ignorecache)=@_;
 6224:     if (($cachedkey eq $uname.':'.$udom) &&
 6225:         (abs($cachedtime-time)<5) && (!$env{'form.markaccess'}) &&
 6226:         (!$ignorecache)) {
 6227:         return;
 6228:     }
 6229:     $cachedtime=time;
 6230:     $cachedkey=$uname.':'.$udom;
 6231:     %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
 6232: }
 6233: 
 6234: sub get_first_access {
 6235:     my ($type,$argsymb,$argmap,$ignorecache)=@_;
 6236:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 6237:     if ($argsymb) { $symb=$argsymb; }
 6238:     my ($map,$id,$res)=&decode_symb($symb);
 6239:     if ($argmap) { $map = $argmap; }
 6240:     if ($type eq 'course') {
 6241: 	$res='course';
 6242:     } elsif ($type eq 'map') {
 6243: 	$res=&symbread($map);
 6244:     } else {
 6245: 	$res=$symb;
 6246:     }
 6247:     &load_all_first_access($uname,$udom,$ignorecache);
 6248:     return $cachedtimes{"$courseid\0$res"};
 6249: }
 6250: 
 6251: sub set_first_access {
 6252:     my ($type,$interval)=@_;
 6253:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 6254:     my ($map,$id,$res)=&decode_symb($symb);
 6255:     if ($type eq 'course') {
 6256: 	$res='course';
 6257:     } elsif ($type eq 'map') {
 6258: 	$res=&symbread($map);
 6259:     } else {
 6260: 	$res=$symb;
 6261:     }
 6262:     $cachedkey='';
 6263:     my $firstaccess=&get_first_access($type,$symb,$map);
 6264:     if ($firstaccess) {
 6265:         &logthis("First access time already set ($firstaccess) when attempting ".
 6266:                  "to set new value (type: $type, extent: $res) for $uname:$udom ".
 6267:                  "in $courseid");
 6268:         return 'already_set';
 6269:     } else {
 6270:         my $start = time;
 6271: 	my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
 6272:                           $udom,$uname);
 6273:         if ($putres eq 'ok') {
 6274:             &put('timerinterval',{"$courseid\0$res"=>$interval},
 6275:                  $udom,$uname); 
 6276:             &appenv(
 6277:                      {
 6278:                         'course.'.$courseid.'.firstaccess.'.$res   => $start,
 6279:                         'course.'.$courseid.'.timerinterval.'.$res => $interval,
 6280:                      }
 6281:                   );
 6282:             if (($cachedtime) && (abs($start-$cachedtime) < 5)) {
 6283:                 $cachedtimes{"$courseid\0$res"} = $start;
 6284:             }
 6285:         } elsif ($putres ne 'refused') {
 6286:             &logthis("Result: $putres when attempting to set first access time ".
 6287:                      "(type: $type, extent: $res) for $uname:$udom in $courseid");
 6288:         }
 6289:         return $putres;
 6290:     }
 6291:     return 'already_set';
 6292: }
 6293: }
 6294: 
 6295: # --------------------------------------------- Set Expire Date for Spreadsheet
 6296: 
 6297: sub expirespread {
 6298:     my ($uname,$udom,$stype,$usymb)=@_;
 6299:     my $cid=$env{'request.course.id'}; 
 6300:     if ($cid) {
 6301:        my $now=time;
 6302:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
 6303:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
 6304:                             $env{'course.'.$cid.'.num'}.
 6305: 	        	    ':nohist_expirationdates:'.
 6306:                             &escape($key).'='.$now,
 6307:                             $env{'course.'.$cid.'.home'})
 6308:     }
 6309:     return 'ok';
 6310: }
 6311: 
 6312: # ----------------------------------------------------- Devalidate Spreadsheets
 6313: 
 6314: sub devalidate {
 6315:     my ($symb,$uname,$udom)=@_;
 6316:     my $cid=$env{'request.course.id'}; 
 6317:     if ($cid) {
 6318:         # delete the stored spreadsheets for
 6319:         # - the student level sheet of this user in course's homespace
 6320:         # - the assessment level sheet for this resource 
 6321:         #   for this user in user's homespace
 6322: 	# - current conditional state info
 6323: 	my $key=$uname.':'.$udom.':';
 6324:         my $status=
 6325: 	    &del('nohist_calculatedsheets',
 6326: 		 [$key.'studentcalc:'],
 6327: 		 $env{'course.'.$cid.'.domain'},
 6328: 		 $env{'course.'.$cid.'.num'})
 6329: 		.' '.
 6330: 	    &del('nohist_calculatedsheets_'.$cid,
 6331: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
 6332:         unless ($status eq 'ok ok') {
 6333:            &logthis('Could not devalidate spreadsheet '.
 6334:                     $uname.' at '.$udom.' for '.
 6335: 		    $symb.': '.$status);
 6336:         }
 6337: 	&delenv('user.state.'.$cid);
 6338:     }
 6339: }
 6340: 
 6341: sub get_scalar {
 6342:     my ($string,$end) = @_;
 6343:     my $value;
 6344:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
 6345: 	$value = $1;
 6346:     } elsif ($$string =~ s/^([^&]*?)&//) {
 6347: 	$value = $1;
 6348:     }
 6349:     return &unescape($value);
 6350: }
 6351: 
 6352: sub array2str {
 6353:   my (@array) = @_;
 6354:   my $result=&arrayref2str(\@array);
 6355:   $result=~s/^__ARRAY_REF__//;
 6356:   $result=~s/__END_ARRAY_REF__$//;
 6357:   return $result;
 6358: }
 6359: 
 6360: sub arrayref2str {
 6361:   my ($arrayref) = @_;
 6362:   my $result='__ARRAY_REF__';
 6363:   foreach my $elem (@$arrayref) {
 6364:     if(ref($elem) eq 'ARRAY') {
 6365:       $result.=&arrayref2str($elem).'&';
 6366:     } elsif(ref($elem) eq 'HASH') {
 6367:       $result.=&hashref2str($elem).'&';
 6368:     } elsif(ref($elem)) {
 6369:       #print("Got a ref of ".(ref($elem))." skipping.");
 6370:     } else {
 6371:       $result.=&escape($elem).'&';
 6372:     }
 6373:   }
 6374:   $result=~s/\&$//;
 6375:   $result .= '__END_ARRAY_REF__';
 6376:   return $result;
 6377: }
 6378: 
 6379: sub hash2str {
 6380:   my (%hash) = @_;
 6381:   my $result=&hashref2str(\%hash);
 6382:   $result=~s/^__HASH_REF__//;
 6383:   $result=~s/__END_HASH_REF__$//;
 6384:   return $result;
 6385: }
 6386: 
 6387: sub hashref2str {
 6388:   my ($hashref)=@_;
 6389:   my $result='__HASH_REF__';
 6390:   foreach my $key (sort(keys(%$hashref))) {
 6391:     if (ref($key) eq 'ARRAY') {
 6392:       $result.=&arrayref2str($key).'=';
 6393:     } elsif (ref($key) eq 'HASH') {
 6394:       $result.=&hashref2str($key).'=';
 6395:     } elsif (ref($key)) {
 6396:       $result.='=';
 6397:       #print("Got a ref of ".(ref($key))." skipping.");
 6398:     } else {
 6399: 	if (defined($key)) {$result.=&escape($key).'=';} else { last; }
 6400:     }
 6401: 
 6402:     if(ref($hashref->{$key}) eq 'ARRAY') {
 6403:       $result.=&arrayref2str($hashref->{$key}).'&';
 6404:     } elsif(ref($hashref->{$key}) eq 'HASH') {
 6405:       $result.=&hashref2str($hashref->{$key}).'&';
 6406:     } elsif(ref($hashref->{$key})) {
 6407:        $result.='&';
 6408:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
 6409:     } else {
 6410:       $result.=&escape($hashref->{$key}).'&';
 6411:     }
 6412:   }
 6413:   $result=~s/\&$//;
 6414:   $result .= '__END_HASH_REF__';
 6415:   return $result;
 6416: }
 6417: 
 6418: sub str2hash {
 6419:     my ($string)=@_;
 6420:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
 6421:     return %$hash;
 6422: }
 6423: 
 6424: sub str2hashref {
 6425:   my ($string) = @_;
 6426: 
 6427:   my %hash;
 6428: 
 6429:   if($string !~ /^__HASH_REF__/) {
 6430:       if (! ($string eq '' || !defined($string))) {
 6431: 	  $hash{'error'}='Not hash reference';
 6432:       }
 6433:       return (\%hash, $string);
 6434:   }
 6435: 
 6436:   $string =~ s/^__HASH_REF__//;
 6437: 
 6438:   while($string !~ /^__END_HASH_REF__/) {
 6439:       #key
 6440:       my $key='';
 6441:       if($string =~ /^__HASH_REF__/) {
 6442:           ($key, $string)=&str2hashref($string);
 6443:           if(defined($key->{'error'})) {
 6444:               $hash{'error'}='Bad data';
 6445:               return (\%hash, $string);
 6446:           }
 6447:       } elsif($string =~ /^__ARRAY_REF__/) {
 6448:           ($key, $string)=&str2arrayref($string);
 6449:           if($key->[0] eq 'Array reference error') {
 6450:               $hash{'error'}='Bad data';
 6451:               return (\%hash, $string);
 6452:           }
 6453:       } else {
 6454:           $string =~ s/^(.*?)=//;
 6455: 	  $key=&unescape($1);
 6456:       }
 6457:       $string =~ s/^=//;
 6458: 
 6459:       #value
 6460:       my $value='';
 6461:       if($string =~ /^__HASH_REF__/) {
 6462:           ($value, $string)=&str2hashref($string);
 6463:           if(defined($value->{'error'})) {
 6464:               $hash{'error'}='Bad data';
 6465:               return (\%hash, $string);
 6466:           }
 6467:       } elsif($string =~ /^__ARRAY_REF__/) {
 6468:           ($value, $string)=&str2arrayref($string);
 6469:           if($value->[0] eq 'Array reference error') {
 6470:               $hash{'error'}='Bad data';
 6471:               return (\%hash, $string);
 6472:           }
 6473:       } else {
 6474: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
 6475:       }
 6476:       $string =~ s/^&//;
 6477: 
 6478:       $hash{$key}=$value;
 6479:   }
 6480: 
 6481:   $string =~ s/^__END_HASH_REF__//;
 6482: 
 6483:   return (\%hash, $string);
 6484: }
 6485: 
 6486: sub str2array {
 6487:     my ($string)=@_;
 6488:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
 6489:     return @$array;
 6490: }
 6491: 
 6492: sub str2arrayref {
 6493:   my ($string) = @_;
 6494:   my @array;
 6495: 
 6496:   if($string !~ /^__ARRAY_REF__/) {
 6497:       if (! ($string eq '' || !defined($string))) {
 6498: 	  $array[0]='Array reference error';
 6499:       }
 6500:       return (\@array, $string);
 6501:   }
 6502: 
 6503:   $string =~ s/^__ARRAY_REF__//;
 6504: 
 6505:   while($string !~ /^__END_ARRAY_REF__/) {
 6506:       my $value='';
 6507:       if($string =~ /^__HASH_REF__/) {
 6508:           ($value, $string)=&str2hashref($string);
 6509:           if(defined($value->{'error'})) {
 6510:               $array[0] ='Array reference error';
 6511:               return (\@array, $string);
 6512:           }
 6513:       } elsif($string =~ /^__ARRAY_REF__/) {
 6514:           ($value, $string)=&str2arrayref($string);
 6515:           if($value->[0] eq 'Array reference error') {
 6516:               $array[0] ='Array reference error';
 6517:               return (\@array, $string);
 6518:           }
 6519:       } else {
 6520: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
 6521:       }
 6522:       $string =~ s/^&//;
 6523: 
 6524:       push(@array, $value);
 6525:   }
 6526: 
 6527:   $string =~ s/^__END_ARRAY_REF__//;
 6528: 
 6529:   return (\@array, $string);
 6530: }
 6531: 
 6532: # -------------------------------------------------------------------Temp Store
 6533: 
 6534: sub tmpreset {
 6535:   my ($symb,$namespace,$domain,$stuname) = @_;
 6536:   if (!$symb) {
 6537:     $symb=&symbread();
 6538:     if (!$symb) { $symb= $env{'request.url'}; }
 6539:   }
 6540:   $symb=escape($symb);
 6541: 
 6542:   if (!$namespace) { $namespace=$env{'request.state'}; }
 6543:   $namespace=~s/\//\_/g;
 6544:   $namespace=~s/\W//g;
 6545: 
 6546:   if (!$domain) { $domain=$env{'user.domain'}; }
 6547:   if (!$stuname) { $stuname=$env{'user.name'}; }
 6548:   if ($domain eq 'public' && $stuname eq 'public') {
 6549:       $stuname=&get_requestor_ip();
 6550:   }
 6551:   my $path=LONCAPA::tempdir();
 6552:   my %hash;
 6553:   if (tie(%hash,'GDBM_File',
 6554: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 6555: 	  &GDBM_WRCREAT(),0640)) {
 6556:     foreach my $key (keys(%hash)) {
 6557:       if ($key=~ /:$symb/) {
 6558: 	delete($hash{$key});
 6559:       }
 6560:     }
 6561:   }
 6562: }
 6563: 
 6564: sub tmpstore {
 6565:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 6566: 
 6567:   if (!$symb) {
 6568:     $symb=&symbread();
 6569:     if (!$symb) { $symb= $env{'request.url'}; }
 6570:   }
 6571:   $symb=escape($symb);
 6572: 
 6573:   if (!$namespace) {
 6574:     # I don't think we would ever want to store this for a course.
 6575:     # it seems this will only be used if we don't have a course.
 6576:     #$namespace=$env{'request.course.id'};
 6577:     #if (!$namespace) {
 6578:       $namespace=$env{'request.state'};
 6579:     #}
 6580:   }
 6581:   $namespace=~s/\//\_/g;
 6582:   $namespace=~s/\W//g;
 6583:   if (!$domain) { $domain=$env{'user.domain'}; }
 6584:   if (!$stuname) { $stuname=$env{'user.name'}; }
 6585:   if ($domain eq 'public' && $stuname eq 'public') {
 6586:       $stuname=&get_requestor_ip();
 6587:   }
 6588:   my $now=time;
 6589:   my %hash;
 6590:   my $path=LONCAPA::tempdir();
 6591:   if (tie(%hash,'GDBM_File',
 6592: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 6593: 	  &GDBM_WRCREAT(),0640)) {
 6594:     $hash{"version:$symb"}++;
 6595:     my $version=$hash{"version:$symb"};
 6596:     my $allkeys=''; 
 6597:     foreach my $key (keys(%$storehash)) {
 6598:       $allkeys.=$key.':';
 6599:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
 6600:     }
 6601:     $hash{"$version:$symb:timestamp"}=$now;
 6602:     $allkeys.='timestamp';
 6603:     $hash{"$version:keys:$symb"}=$allkeys;
 6604:     if (untie(%hash)) {
 6605:       return 'ok';
 6606:     } else {
 6607:       return "error:$!";
 6608:     }
 6609:   } else {
 6610:     return "error:$!";
 6611:   }
 6612: }
 6613: 
 6614: # -----------------------------------------------------------------Temp Restore
 6615: 
 6616: sub tmprestore {
 6617:   my ($symb,$namespace,$domain,$stuname) = @_;
 6618: 
 6619:   if (!$symb) {
 6620:     $symb=&symbread();
 6621:     if (!$symb) { $symb= $env{'request.url'}; }
 6622:   }
 6623:   $symb=escape($symb);
 6624: 
 6625:   if (!$namespace) { $namespace=$env{'request.state'}; }
 6626: 
 6627:   if (!$domain) { $domain=$env{'user.domain'}; }
 6628:   if (!$stuname) { $stuname=$env{'user.name'}; }
 6629:   if ($domain eq 'public' && $stuname eq 'public') {
 6630:       $stuname=&get_requestor_ip();
 6631:   }
 6632:   my %returnhash;
 6633:   $namespace=~s/\//\_/g;
 6634:   $namespace=~s/\W//g;
 6635:   my %hash;
 6636:   my $path=LONCAPA::tempdir();
 6637:   if (tie(%hash,'GDBM_File',
 6638: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 6639: 	  &GDBM_READER(),0640)) {
 6640:     my $version=$hash{"version:$symb"};
 6641:     $returnhash{'version'}=$version;
 6642:     my $scope;
 6643:     for ($scope=1;$scope<=$version;$scope++) {
 6644:       my $vkeys=$hash{"$scope:keys:$symb"};
 6645:       my @keys=split(/:/,$vkeys);
 6646:       my $key;
 6647:       $returnhash{"$scope:keys"}=$vkeys;
 6648:       foreach $key (@keys) {
 6649: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 6650: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 6651:       }
 6652:     }
 6653:     if (!(untie(%hash))) {
 6654:       return "error:$!";
 6655:     }
 6656:   } else {
 6657:     return "error:$!";
 6658:   }
 6659:   return %returnhash;
 6660: }
 6661: 
 6662: # ----------------------------------------------------------------------- Store
 6663: 
 6664: sub store {
 6665:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
 6666:     my $home='';
 6667: 
 6668:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 6669: 
 6670:     $symb=&symbclean($symb);
 6671:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 6672: 
 6673:     if (!$domain) { $domain=$env{'user.domain'}; }
 6674:     if (!$stuname) { $stuname=$env{'user.name'}; }
 6675: 
 6676:     &devalidate($symb,$stuname,$domain);
 6677: 
 6678:     $symb=escape($symb);
 6679:     if (!$namespace) { 
 6680:        unless ($namespace=$env{'request.course.id'}) { 
 6681:           return ''; 
 6682:        } 
 6683:     }
 6684:     if (!$home) { $home=$env{'user.home'}; }
 6685: 
 6686:     $$storehash{'ip'}=&get_requestor_ip();
 6687:     $$storehash{'host'}=$perlvar{'lonHostID'};
 6688: 
 6689:     my $namevalue='';
 6690:     foreach my $key (keys(%$storehash)) {
 6691:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 6692:     }
 6693:     $namevalue=~s/\&$//;
 6694:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
 6695:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
 6696: }
 6697: 
 6698: # -------------------------------------------------------------- Critical Store
 6699: 
 6700: sub cstore {
 6701:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
 6702:     my $home='';
 6703: 
 6704:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 6705: 
 6706:     $symb=&symbclean($symb);
 6707:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 6708: 
 6709:     if (!$domain) { $domain=$env{'user.domain'}; }
 6710:     if (!$stuname) { $stuname=$env{'user.name'}; }
 6711: 
 6712:     &devalidate($symb,$stuname,$domain);
 6713: 
 6714:     $symb=escape($symb);
 6715:     if (!$namespace) { 
 6716:        unless ($namespace=$env{'request.course.id'}) { 
 6717:           return ''; 
 6718:        } 
 6719:     }
 6720:     if (!$home) { $home=$env{'user.home'}; }
 6721: 
 6722:     $$storehash{'ip'}=&get_requestor_ip();
 6723:     $$storehash{'host'}=$perlvar{'lonHostID'};
 6724: 
 6725:     my $namevalue='';
 6726:     foreach my $key (keys(%$storehash)) {
 6727:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 6728:     }
 6729:     $namevalue=~s/\&$//;
 6730:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
 6731:     return critical
 6732:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
 6733: }
 6734: 
 6735: # --------------------------------------------------------------------- Restore
 6736: 
 6737: sub restore {
 6738:     my ($symb,$namespace,$domain,$stuname) = @_;
 6739:     my $home='';
 6740: 
 6741:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 6742: 
 6743:     if (!$symb) {
 6744:         return if ($namespace eq 'courserequests');
 6745:         unless ($symb=escape(&symbread())) { return ''; }
 6746:     } else {
 6747:         unless ($namespace eq 'courserequests') {
 6748:             $symb=&escape(&symbclean($symb));
 6749:         }
 6750:     }
 6751:     if (!$namespace) { 
 6752:        unless ($namespace=$env{'request.course.id'}) { 
 6753:           return ''; 
 6754:        } 
 6755:     }
 6756:     if (!$domain) { $domain=$env{'user.domain'}; }
 6757:     if (!$stuname) { $stuname=$env{'user.name'}; }
 6758:     if (!$home) { $home=$env{'user.home'}; }
 6759:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
 6760: 
 6761:     my %returnhash=();
 6762:     foreach my $line (split(/\&/,$answer)) {
 6763: 	my ($name,$value)=split(/\=/,$line);
 6764:         $returnhash{&unescape($name)}=&thaw_unescape($value);
 6765:     }
 6766:     my $version;
 6767:     for ($version=1;$version<=$returnhash{'version'};$version++) {
 6768:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
 6769:           $returnhash{$item}=$returnhash{$version.':'.$item};
 6770:        }
 6771:     }
 6772:     return %returnhash;
 6773: }
 6774: 
 6775: # ---------------------------------------------------------- Course Description
 6776: #
 6777: #  
 6778: 
 6779: sub coursedescription {
 6780:     my ($courseid,$args)=@_;
 6781:     $courseid=~s/^\///;
 6782:     $courseid=~s/\_/\//g;
 6783:     my ($cdomain,$cnum)=split(/\//,$courseid);
 6784:     my $chome=&homeserver($cnum,$cdomain);
 6785:     my $normalid=$cdomain.'_'.$cnum;
 6786:     # need to always cache even if we get errors otherwise we keep 
 6787:     # trying and trying and trying to get the course description.
 6788:     my %envhash=();
 6789:     my %returnhash=();
 6790:     
 6791:     my $expiretime=600;
 6792:     if ($env{'request.course.id'} eq $normalid) {
 6793: 	$expiretime=120;
 6794:     }
 6795: 
 6796:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
 6797:     if (!$args->{'freshen_cache'}
 6798: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
 6799: 	foreach my $key (keys(%env)) {
 6800: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
 6801: 	    my ($setting) = $1;
 6802: 	    $returnhash{$setting} = $env{$key};
 6803: 	}
 6804: 	return %returnhash;
 6805:     }
 6806: 
 6807:     # get the data again
 6808: 
 6809:     if (!$args->{'one_time'}) {
 6810: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
 6811:     }
 6812: 
 6813:     if ($chome ne 'no_host') {
 6814:        %returnhash=&dump('environment',$cdomain,$cnum);
 6815:        if (!exists($returnhash{'con_lost'})) {
 6816: 	   my $username = $env{'user.name'}; # Defult username
 6817: 	   if(defined $args->{'user'}) {
 6818: 	       $username = $args->{'user'};
 6819: 	   }
 6820:            $returnhash{'home'}= $chome;
 6821: 	   $returnhash{'domain'} = $cdomain;
 6822: 	   $returnhash{'num'} = $cnum;
 6823:            if (!defined($returnhash{'type'})) {
 6824:                $returnhash{'type'} = 'Course';
 6825:            }
 6826:            while (my ($name,$value) = each %returnhash) {
 6827:                $envhash{'course.'.$normalid.'.'.$name}=$value;
 6828:            }
 6829:            $returnhash{'url'}=&clutter($returnhash{'url'});
 6830:            $returnhash{'fn'}=LONCAPA::tempdir() .
 6831: 	       $username.'_'.$cdomain.'_'.$cnum;
 6832:            $envhash{'course.'.$normalid.'.home'}=$chome;
 6833:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
 6834:            $envhash{'course.'.$normalid.'.num'}=$cnum;
 6835:        }
 6836:     }
 6837:     if (!$args->{'one_time'}) {
 6838: 	&appenv(\%envhash);
 6839:     }
 6840:     return %returnhash;
 6841: }
 6842: 
 6843: sub update_released_required {
 6844:     my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
 6845:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
 6846:         $cid = $env{'request.course.id'};
 6847:         $cdom = $env{'course.'.$cid.'.domain'};
 6848:         $cnum = $env{'course.'.$cid.'.num'};
 6849:         $chome = $env{'course.'.$cid.'.home'};
 6850:     }
 6851:     if ($needsrelease) {
 6852:         my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
 6853:         my $needsupdate;
 6854:         if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
 6855:             $needsupdate = 1;
 6856:         } else {
 6857:             my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
 6858:             my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
 6859:             if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
 6860:                 $needsupdate = 1;
 6861:             }
 6862:         }
 6863:         if ($needsupdate) {
 6864:             my %needshash = (
 6865:                              'internal.releaserequired' => $needsrelease,
 6866:                             );
 6867:             my $putresult = &put('environment',\%needshash,$cdom,$cnum);
 6868:             if ($putresult eq 'ok') {
 6869:                 &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
 6870:                 my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
 6871:                 if (ref($crsinfo{$cid}) eq 'HASH') {
 6872:                     $crsinfo{$cid}{'releaserequired'} = $needsrelease;
 6873:                     &courseidput($cdom,\%crsinfo,$chome,'notime');
 6874:                 }
 6875:             }
 6876:         }
 6877:     }
 6878:     return;
 6879: }
 6880: 
 6881: # -------------------------------------------------See if a user is privileged
 6882: 
 6883: sub privileged {
 6884:     my ($username,$domain,$possdomains,$possroles)=@_;
 6885:     my $now = time;
 6886:     my $roles;
 6887:     if (ref($possroles) eq 'ARRAY') {
 6888:         $roles = $possroles; 
 6889:     } else {
 6890:         $roles = ['dc','su'];
 6891:     }
 6892:     if (ref($possdomains) eq 'ARRAY') {
 6893:         my %privileged = &privileged_by_domain($possdomains,$roles);
 6894:         foreach my $dom (@{$possdomains}) {
 6895:             if (($username =~ /^$match_username$/) && ($domain =~ /^$match_domain$/) &&
 6896:                 (ref($privileged{$dom}) eq 'HASH')) {
 6897:                 foreach my $role (@{$roles}) {
 6898:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
 6899:                         if (exists($privileged{$dom}{$role}{$username.':'.$domain})) {
 6900:                             my ($end,$start) = split(/:/,$privileged{$dom}{$role}{$username.':'.$domain});
 6901:                             return 1 unless (($end && $end < $now) ||
 6902:                                              ($start && $start > $now));
 6903:                         }
 6904:                     }
 6905:                 }
 6906:             }
 6907:         }
 6908:     } else {
 6909:         my %rolesdump = &dump("roles", $domain, $username) or return 0;
 6910:         my $now = time;
 6911: 
 6912:         for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys(%rolesdump)}) {
 6913:             my ($trole, $tend, $tstart) = split(/_/, $role);
 6914:             if (grep(/^\Q$trole\E$/,@{$roles})) {
 6915:                 return 1 unless ($tend && $tend < $now) 
 6916:                         or ($tstart && $tstart > $now);
 6917:             }
 6918:         }
 6919:     }
 6920:     return 0;
 6921: }
 6922: 
 6923: sub privileged_by_domain {
 6924:     my ($domains,$roles) = @_;
 6925:     my %privileged = ();
 6926:     my $cachetime = 60*60*24;
 6927:     my $now = time;
 6928:     unless ((ref($domains) eq 'ARRAY') && (ref($roles) eq 'ARRAY')) {
 6929:         return %privileged;
 6930:     }
 6931:     foreach my $dom (@{$domains}) {
 6932:         next if (ref($privileged{$dom}) eq 'HASH');
 6933:         my $needroles;
 6934:         foreach my $role (@{$roles}) {
 6935:             my ($result,$cached)=&is_cached_new('priv_'.$role,$dom);
 6936:             if (defined($cached)) {
 6937:                 if (ref($result) eq 'HASH') {
 6938:                     $privileged{$dom}{$role} = $result;
 6939:                 }
 6940:             } else {
 6941:                 $needroles = 1;
 6942:             }
 6943:         }
 6944:         if ($needroles) {
 6945:             my %dompersonnel = &get_domain_roles($dom,$roles);
 6946:             $privileged{$dom} = {};
 6947:             foreach my $server (keys(%dompersonnel)) {
 6948:                 if (ref($dompersonnel{$server}) eq 'HASH') {
 6949:                     foreach my $item (keys(%{$dompersonnel{$server}})) {
 6950:                         my ($trole,$uname,$udom,$rest) = split(/:/,$item,4);
 6951:                         my ($end,$start) = split(/:/,$dompersonnel{$server}{$item});
 6952:                         next if ($end && $end < $now);
 6953:                         $privileged{$dom}{$trole}{$uname.':'.$udom} = 
 6954:                             $dompersonnel{$server}{$item};
 6955:                     }
 6956:                 }
 6957:             }
 6958:             if (ref($privileged{$dom}) eq 'HASH') {
 6959:                 foreach my $role (@{$roles}) {
 6960:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
 6961:                         &do_cache_new('priv_'.$role,$dom,$privileged{$dom}{$role},$cachetime);
 6962:                     } else {
 6963:                         my %hash = ();
 6964:                         &do_cache_new('priv_'.$role,$dom,\%hash,$cachetime);
 6965:                     }
 6966:                 }
 6967:             }
 6968:         }
 6969:     }
 6970:     return %privileged;
 6971: }
 6972: 
 6973: # -------------------------------------------------------- Get user privileges
 6974: 
 6975: sub rolesinit {
 6976:     my ($domain, $username) = @_;
 6977:     my %userroles = ('user.login.time' => time);
 6978:     my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
 6979: 
 6980:     # firstaccess and timerinterval are related to timed maps/resources. 
 6981:     # also, blocking can be triggered by an activating timer
 6982:     # it's saved in the user's %env.
 6983:     my %firstaccess = &dump('firstaccesstimes', $domain, $username);
 6984:     my %timerinterval = &dump('timerinterval', $domain, $username);
 6985:     my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
 6986:         %timerintchk, %timerintenv, %coauthorenv);
 6987: 
 6988:     foreach my $key (keys(%firstaccess)) {
 6989:         my ($cid, $rest) = split(/\0/, $key);
 6990:         $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
 6991:     }
 6992: 
 6993:     foreach my $key (keys(%timerinterval)) {
 6994:         my ($cid,$rest) = split(/\0/,$key);
 6995:         $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
 6996:     }
 6997: 
 6998:     my %allroles=();
 6999:     my %allgroups=();
 7000:     my %gotcoauconfig=();
 7001: 
 7002:     for my $area (grep { ! /^rolesdef_/ } keys(%rolesdump)) {
 7003:         my $role = $rolesdump{$area};
 7004:         $area =~ s/\_\w\w$//;
 7005: 
 7006:         my ($trole, $tend, $tstart, $group_privs);
 7007: 
 7008:         if ($role =~ /^cr/) {
 7009:         # Custom role, defined by a user 
 7010:         # e.g., user.role.cr/msu/smith/mynewrole
 7011:             if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
 7012:                 $trole = $1;
 7013:                 ($tend, $tstart) = split('_', $2);
 7014:             } else {
 7015:                 $trole = $role;
 7016:             }
 7017:         } elsif ($role =~ m|^gr/|) {
 7018:         # Role of member in a group, defined within a course/community
 7019:         # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
 7020:             ($trole, $tend, $tstart) = split(/_/, $role);
 7021:             next if $tstart eq '-1';
 7022:             ($trole, $group_privs) = split(/\//, $trole);
 7023:             $group_privs = &unescape($group_privs);
 7024:         } else {
 7025:         # Just a normal role, defined in roles.tab
 7026:             ($trole, $tend, $tstart) = split(/_/,$role);
 7027:         }
 7028: 
 7029:         my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
 7030:                  $username);
 7031:         @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
 7032: 
 7033:         # role expired or not available yet?
 7034:         $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or 
 7035:             ($tstart != 0 && $tstart > $userroles{'user.login.time'});
 7036: 
 7037:         next if $area eq '' or $trole eq '';
 7038: 
 7039:         my $spec = "$trole.$area";
 7040:         my ($tdummy, $tdomain, $trest) = split(/\//, $area);
 7041: 
 7042:         if ($trole =~ /^cr\//) {
 7043:         # Custom role, defined by a user
 7044:             &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
 7045:         } elsif ($trole eq 'gr') {
 7046:         # Role of a member in a group, defined within a course/community
 7047:             &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
 7048:             next;
 7049:         } else {
 7050:         # Normal role, defined in roles.tab
 7051:             &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
 7052:             if (($trole eq 'ca') || ($trole eq 'aa')) {
 7053:                 (undef,my ($audom,$auname)) = split(/\//,$area);
 7054:                 unless ($gotcoauconfig{$area}) {
 7055:                     my @ca_settings = ('authoreditors','coauthorlist','coauthoroptin');
 7056:                     my %info = &userenvironment($audom,$auname,@ca_settings);
 7057:                     $gotcoauconfig{$area} = 1;
 7058:                     foreach my $item (@ca_settings) {
 7059:                         if (exists($info{$item})) {
 7060:                             my $name = $item;
 7061:                             if ($item eq 'authoreditors') {
 7062:                                 $name = 'editors';
 7063:                             }
 7064:                             $coauthorenv{"environment.internal.$name.$area"} = $info{$item};
 7065:                         }
 7066:                     }
 7067:                 }
 7068:             }
 7069:         }
 7070: 
 7071:         my $cid = $tdomain.'_'.$trest;
 7072:         unless ($firstaccchk{$cid}) {
 7073:             if (ref($coursetimerstarts{$cid}) eq 'HASH') {
 7074:                 foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
 7075:                     $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} = 
 7076:                         $coursetimerstarts{$cid}{$item}; 
 7077:                 }
 7078:             }
 7079:             $firstaccchk{$cid} = 1;
 7080:         }
 7081:         unless ($timerintchk{$cid}) {
 7082:             if (ref($coursetimerintervals{$cid}) eq 'HASH') {
 7083:                 foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
 7084:                     $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
 7085:                        $coursetimerintervals{$cid}{$item};
 7086:                 }
 7087:             }
 7088:             $timerintchk{$cid} = 1;
 7089:         }
 7090:     }
 7091: 
 7092:     @userroles{'user.author','user.adv','user.rar'} = &set_userprivs(\%userroles,
 7093:                                                           \%allroles, \%allgroups);
 7094:     $env{'user.adv'} = $userroles{'user.adv'};
 7095:     $env{'user.rar'} = $userroles{'user.rar'};
 7096: 
 7097:     return (\%userroles,\%firstaccenv,\%timerintenv,\%coauthorenv);
 7098: }
 7099: 
 7100: sub set_arearole {
 7101:     my ($trole,$area,$tstart,$tend,$domain,$username,$nolog) = @_;
 7102:     unless ($nolog) {
 7103: # log the associated role with the area
 7104:         &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
 7105:     }
 7106:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
 7107: }
 7108: 
 7109: sub custom_roleprivs {
 7110:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
 7111:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
 7112:     my $homsvr = &homeserver($rauthor,$rdomain);
 7113:     if (&hostname($homsvr) ne '') {
 7114:         my ($rdummy,$roledef)=
 7115:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
 7116:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
 7117:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
 7118:             if (defined($syspriv)) {
 7119:                 if ($trest =~ /^$match_community$/) {
 7120:                     $syspriv =~ s/bre\&S//; 
 7121:                 }
 7122:                 $$allroles{'cm./'}.=':'.$syspriv;
 7123:                 $$allroles{$spec.'./'}.=':'.$syspriv;
 7124:             }
 7125:             if ($tdomain ne '') {
 7126:                 if (defined($dompriv)) {
 7127:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
 7128:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
 7129:                 }
 7130:                 if (($trest ne '') && (defined($coursepriv))) {
 7131:                     if ($trole =~ m{^cr/$tdomain/$tdomain\Q-domainconfig\E/([^/]+)$}) {
 7132:                         my $rolename = $1;
 7133:                         $coursepriv = &course_adhocrole_privs($rolename,$tdomain,$trest,$coursepriv);
 7134:                     }
 7135:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
 7136:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
 7137:                 }
 7138:             }
 7139:         }
 7140:     }
 7141: }
 7142: 
 7143: sub course_adhocrole_privs {
 7144:     my ($rolename,$cdom,$cnum,$coursepriv) = @_;
 7145:     my %overrides = &get('environment',["internal.adhocpriv.$rolename"],$cdom,$cnum);
 7146:     if ($overrides{"internal.adhocpriv.$rolename"}) {
 7147:         my (%currprivs,%storeprivs);
 7148:         foreach my $item (split(/:/,$coursepriv)) {
 7149:             my ($priv,$restrict) = split(/\&/,$item);
 7150:             $currprivs{$priv} = $restrict;
 7151:         }
 7152:         my (%possadd,%possremove,%full);
 7153:         foreach my $item (split(/\:/,$Apache::lonnet::pr{'cr:c'})) {
 7154:             my ($priv,$restrict)=split(/\&/,$item);
 7155:             $full{$priv} = $restrict;
 7156:         }
 7157:         foreach my $item (split(/,/,$overrides{"internal.adhocpriv.$rolename"})) {
 7158:             next if ($item eq '');
 7159:             my ($rule,$rest) = split(/=/,$item);
 7160:             next unless (($rule eq 'off') || ($rule eq 'on'));
 7161:             foreach my $priv (split(/:/,$rest)) {
 7162:                 if ($priv ne '') {
 7163:                     if ($rule eq 'off') {
 7164:                         $possremove{$priv} = 1;
 7165:                     } else {
 7166:                         $possadd{$priv} = 1;
 7167:                     }
 7168:                 }
 7169:             }
 7170:         }
 7171:         foreach my $priv (sort(keys(%full))) {
 7172:             if (exists($currprivs{$priv})) {
 7173:                 unless (exists($possremove{$priv})) {
 7174:                     $storeprivs{$priv} = $currprivs{$priv};
 7175:                 }
 7176:             } elsif (exists($possadd{$priv})) {
 7177:                 $storeprivs{$priv} = $full{$priv};
 7178:             }
 7179:         }
 7180:         $coursepriv = ':'.join(':',map { $_.'&'.$storeprivs{$_}; } sort(keys(%storeprivs)));
 7181:     }
 7182:     return $coursepriv;
 7183: }
 7184: 
 7185: sub group_roleprivs {
 7186:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
 7187:     my $access = 1;
 7188:     my $now = time;
 7189:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
 7190:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
 7191:     if ($access) {
 7192:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
 7193:         $$allgroups{$course}{$group} .=':'.$group_privs;
 7194:     }
 7195: }
 7196: 
 7197: sub standard_roleprivs {
 7198:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
 7199:     if (defined($pr{$trole.':s'})) {
 7200:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
 7201:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
 7202:     }
 7203:     if ($tdomain ne '') {
 7204:         if (defined($pr{$trole.':d'})) {
 7205:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 7206:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 7207:         }
 7208:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
 7209:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
 7210:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
 7211:         }
 7212:     }
 7213: }
 7214: 
 7215: sub set_userprivs {
 7216:     my ($userroles,$allroles,$allgroups,$groups_roles) = @_; 
 7217:     my $author=0;
 7218:     my $adv=0;
 7219:     my $rar=0;
 7220:     my %grouproles = ();
 7221:     if (keys(%{$allgroups}) > 0) {
 7222:         my @groupkeys; 
 7223:         foreach my $role (keys(%{$allroles})) {
 7224:             push(@groupkeys,$role);
 7225:         }
 7226:         if (ref($groups_roles) eq 'HASH') {
 7227:             foreach my $key (keys(%{$groups_roles})) {
 7228:                 unless (grep(/^\Q$key\E$/,@groupkeys)) {
 7229:                     push(@groupkeys,$key);
 7230:                 }
 7231:             }
 7232:         }
 7233:         if (@groupkeys > 0) {
 7234:             foreach my $role (@groupkeys) {
 7235:                 my ($trole,$area,$sec,$extendedarea);
 7236:                 if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
 7237:                     $trole = $1;
 7238:                     $area = $2;
 7239:                     $sec = $3;
 7240:                     $extendedarea = $area.$sec;
 7241:                     if (exists($$allgroups{$area})) {
 7242:                         foreach my $group (keys(%{$$allgroups{$area}})) {
 7243:                             my $spec = $trole.'.'.$extendedarea;
 7244:                             $grouproles{$spec.'.'.$area.'/'.$group} = 
 7245:                                                 $$allgroups{$area}{$group};
 7246:                         }
 7247:                     }
 7248:                 }
 7249:             }
 7250:         }
 7251:     }
 7252:     foreach my $group (keys(%grouproles)) {
 7253:         $$allroles{$group} = $grouproles{$group};
 7254:     }
 7255:     foreach my $role (keys(%{$allroles})) {
 7256:         my %thesepriv;
 7257:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
 7258:         foreach my $item (split(/:/,$$allroles{$role})) {
 7259:             if ($item ne '') {
 7260:                 my ($privilege,$restrictions)=split(/&/,$item);
 7261:                 if ($restrictions eq '') {
 7262:                     $thesepriv{$privilege}='F';
 7263:                 } elsif ($thesepriv{$privilege} ne 'F') {
 7264:                     $thesepriv{$privilege}.=$restrictions;
 7265:                 }
 7266:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
 7267:                 if ($thesepriv{'rar'} eq 'F') { $rar=1; }
 7268:             }
 7269:         }
 7270:         my $thesestr='';
 7271:         foreach my $priv (sort(keys(%thesepriv))) {
 7272: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
 7273: 	}
 7274:         $userroles->{'user.priv.'.$role} = $thesestr;
 7275:     }
 7276:     return ($author,$adv,$rar);
 7277: }
 7278: 
 7279: sub role_status {
 7280:     my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
 7281:     if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
 7282:         my ($one,$two) = split(m{\./},$rolekey,2);
 7283:         (undef,undef,$$role) = split(/\./,$one,3);
 7284:         unless (!defined($$role) || $$role eq '') {
 7285:             $$where = '/'.$two;
 7286:             $$trolecode=$$role.'.'.$$where;
 7287:             ($$tstart,$$tend)=split(/\./,$env{$rolekey});
 7288:             $$tstatus='is';
 7289:             if ($$tstart && $$tstart>$update) {
 7290:                 $$tstatus='future';
 7291:                 if ($$tstart<$now) {
 7292:                     if ($$tstart && $$tstart>$refresh) {
 7293:                         if (($$where ne '') && ($$role ne '')) {
 7294:                             my (%allroles,%allgroups,$group_privs,
 7295:                                 %groups_roles,@rolecodes);
 7296:                             my %userroles = (
 7297:                                 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
 7298:                             );
 7299:                             @rolecodes = ('cm'); 
 7300:                             my $spec=$$role.'.'.$$where;
 7301:                             my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
 7302:                             if ($$role =~ /^cr\//) {
 7303:                                 &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
 7304:                                 push(@rolecodes,'cr');
 7305:                             } elsif ($$role eq 'gr') {
 7306:                                 push(@rolecodes,$$role);
 7307:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
 7308:                                                     $env{'user.name'});
 7309:                                 my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
 7310:                                 (undef,my $group_privs) = split(/\//,$trole);
 7311:                                 $group_privs = &unescape($group_privs);
 7312:                                 &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
 7313:                                 my %course_roles = &get_my_roles($env{'user.name'},$env{'user.domain'},'userroles',['active'],['cc','co','in','ta','ep','ad','st','cr'],[$tdomain],1);
 7314:                                 &get_groups_roles($tdomain,$trest,
 7315:                                                   \%course_roles,\@rolecodes,
 7316:                                                   \%groups_roles);
 7317:                             } else {
 7318:                                 push(@rolecodes,$$role);
 7319:                                 &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
 7320:                             }
 7321:                             my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%allroles,\%allgroups,
 7322:                                                                    \%groups_roles);
 7323:                             &appenv(\%userroles,\@rolecodes);
 7324:                             &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
 7325:                         }
 7326:                     }
 7327:                     $$tstatus = 'is';
 7328:                 }
 7329:             }
 7330:             if ($$tend) {
 7331:                 if ($$tend<$update) {
 7332:                     $$tstatus='expired';
 7333:                 } elsif ($$tend<$now) {
 7334:                     $$tstatus='will_not';
 7335:                 }
 7336:             }
 7337:         }
 7338:     }
 7339: }
 7340: 
 7341: sub get_groups_roles {
 7342:     my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
 7343:     return unless((ref($cdom_courseroles) eq 'HASH') && 
 7344:                   (ref($rolecodes) eq 'ARRAY') && 
 7345:                   (ref($groups_roles) eq 'HASH')); 
 7346:     if (keys(%{$cdom_courseroles}) > 0) {
 7347:         my ($cnum) = ($rest =~ /^($match_courseid)/);
 7348:         if ($cdom ne '' && $cnum ne '') {
 7349:             foreach my $key (keys(%{$cdom_courseroles})) {
 7350:                 if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
 7351:                     my $crsrole = $1;
 7352:                     my $crssec = $2;
 7353:                     if ($crsrole =~ /^cr/) {
 7354:                         unless (grep(/^cr$/,@{$rolecodes})) {
 7355:                             push(@{$rolecodes},'cr');
 7356:                         }
 7357:                     } else {
 7358:                         unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
 7359:                             push(@{$rolecodes},$crsrole);
 7360:                         }
 7361:                     }
 7362:                     my $rolekey = "$crsrole./$cdom/$cnum";
 7363:                     if ($crssec ne '') {
 7364:                         $rolekey .= "/$crssec";
 7365:                     }
 7366:                     $rolekey .= './';
 7367:                     $groups_roles->{$rolekey} = $rolecodes;
 7368:                 }
 7369:             }
 7370:         }
 7371:     }
 7372:     return;
 7373: }
 7374: 
 7375: sub delete_env_groupprivs {
 7376:     my ($where,$courseroles,$possroles) = @_;
 7377:     return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
 7378:     my ($dummy,$udom,$uname,$group) = split(/\//,$where);
 7379:     unless (ref($courseroles->{$udom}) eq 'HASH') {
 7380:         %{$courseroles->{$udom}} =
 7381:             &get_my_roles('','','userroles',['active'],
 7382:                           $possroles,[$udom],1);
 7383:     }
 7384:     if (ref($courseroles->{$udom}) eq 'HASH') {
 7385:         foreach my $item (keys(%{$courseroles->{$udom}})) {
 7386:             my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
 7387:             my $area = '/'.$cdom.'/'.$cnum;
 7388:             my $privkey = "user.priv.$crsrole.$area";
 7389:             if ($crssec ne '') {
 7390:                 $privkey .= '/'.$crssec;
 7391:             }
 7392:             $privkey .= ".$area/$group";
 7393:             &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
 7394:         }
 7395:     }
 7396:     return;
 7397: }
 7398: 
 7399: sub check_adhoc_privs {
 7400:     my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller,$sec) = @_;
 7401:     my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
 7402:     if ($sec) {
 7403:         $cckey .= '/'.$sec;
 7404:     } 
 7405:     my $setprivs;
 7406:     if ($env{$cckey}) {
 7407:         my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
 7408:         &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
 7409:         unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
 7410:             &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
 7411:             $setprivs = 1;
 7412:         }
 7413:     } else {
 7414:         &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
 7415:         $setprivs = 1;
 7416:     }
 7417:     return $setprivs;
 7418: }
 7419: 
 7420: sub set_adhoc_privileges {
 7421: # role can be cc, ca, or cr/<dom>/<dom>-domainconfig/role
 7422:     my ($dcdom,$pickedcourse,$role,$caller,$sec) = @_;
 7423:     my $area = '/'.$dcdom.'/'.$pickedcourse;
 7424:     if ($sec ne '') {
 7425:         $area .= '/'.$sec;
 7426:     }
 7427:     my $spec = $role.'.'.$area;
 7428:     my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
 7429:                                   $env{'user.name'},1);
 7430:     my %rolehash = ();
 7431:     if ($role =~ m{^\Qcr/$dcdom/$dcdom\E\-domainconfig/(\w+)$}) {
 7432:         my $rolename = $1;
 7433:         &custom_roleprivs(\%rolehash,$role,$dcdom,$pickedcourse,$spec,$area);
 7434:         my %domdef = &get_domain_defaults($dcdom);
 7435:         if (ref($domdef{'adhocroles'}) eq 'HASH') {
 7436:             if (ref($domdef{'adhocroles'}{$rolename}) eq 'HASH') {
 7437:                 &appenv({'request.role.desc' => $domdef{'adhocroles'}{$rolename}{'desc'},});
 7438:             }
 7439:         }
 7440:     } else {
 7441:         &standard_roleprivs(\%rolehash,$role,$dcdom,$spec,$pickedcourse,$area);
 7442:     }
 7443:     my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%rolehash);
 7444:     &appenv(\%userroles,[$role,'cm']);
 7445:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
 7446:     unless (($caller eq 'constructaccess' && $env{'request.course.id'}) ||
 7447:             ($caller eq 'tiny')) {
 7448:         &appenv( {'request.role'        => $spec,
 7449:                   'request.role.domain' => $dcdom,
 7450:                   'request.course.sec'  => $sec,
 7451:                  }
 7452:                );
 7453:         my $tadv=0;
 7454:         if (&allowed('adv') eq 'F') { $tadv=1; }
 7455:         &appenv({'request.role.adv'    => $tadv});
 7456:     }
 7457: }
 7458: 
 7459: # --------------------------------------------------------------- get interface
 7460: 
 7461: sub get {
 7462:    my ($namespace,$storearr,$udomain,$uname)=@_;
 7463:    my $items='';
 7464:    foreach my $item (@$storearr) {
 7465:        $items.=&escape($item).'&';
 7466:    }
 7467:    $items=~s/\&$//;
 7468:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 7469:    if (!$uname) { $uname=$env{'user.name'}; }
 7470:    my $uhome=&homeserver($uname,$udomain);
 7471: 
 7472:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
 7473:    my @pairs=split(/\&/,$rep);
 7474:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
 7475:      return @pairs;
 7476:    }
 7477:    my %returnhash=();
 7478:    my $i=0;
 7479:    foreach my $item (@$storearr) {
 7480:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 7481:       $i++;
 7482:    }
 7483:    return %returnhash;
 7484: }
 7485: 
 7486: # --------------------------------------------------------------- del interface
 7487: 
 7488: sub del {
 7489:    my ($namespace,$storearr,$udomain,$uname)=@_;
 7490:    my $items='';
 7491:    foreach my $item (@$storearr) {
 7492:        $items.=&escape($item).'&';
 7493:    }
 7494: 
 7495:    $items=~s/\&$//;
 7496:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 7497:    if (!$uname) { $uname=$env{'user.name'}; }
 7498:    my $uhome=&homeserver($uname,$udomain);
 7499:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
 7500: }
 7501: 
 7502: # -------------------------------------------------------------- dump interface
 7503: 
 7504: sub unserialize {
 7505:     my ($rep, $escapedkeys) = @_;
 7506: 
 7507:     return {} if $rep =~ /^error/;
 7508: 
 7509:     my %returnhash=();
 7510: 	foreach my $item (split(/\&/,$rep)) {
 7511: 	    my ($key, $value) = split(/=/, $item, 2);
 7512: 	    $key = unescape($key) unless $escapedkeys;
 7513: 	    next if $key =~ /^error: 2 /;
 7514: 	    $returnhash{$key} = &thaw_unescape($value);
 7515: 	}
 7516:     #return %returnhash;
 7517:     return \%returnhash;
 7518: }        
 7519: 
 7520: # see Lond::dump_with_regexp
 7521: # if $escapedkeys hash keys won't get unescaped.
 7522: sub dump {
 7523:     my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys,$encrypt)=@_;
 7524:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 7525:     if (!$uname) { $uname=$env{'user.name'}; }
 7526:     my $uhome=&homeserver($uname,$udomain);
 7527: 
 7528:     if ($regexp) {
 7529:         $regexp=&escape($regexp);
 7530:     } else {
 7531:         $regexp='.';
 7532:     }
 7533:     if (grep { $_ eq $uhome } current_machine_ids()) {
 7534:         # user is hosted on this machine
 7535:         my $reply = LONCAPA::Lond::dump_with_regexp(join(":", ($udomain,
 7536:                     $uname, $namespace, $regexp, $range)), $perlvar{'lonVersion'});
 7537:         return %{unserialize($reply, $escapedkeys)};
 7538:     }
 7539:     my $rep;
 7540:     if ($encrypt) {
 7541:         $rep=&reply("encrypt:edump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
 7542:     } else {
 7543:         $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
 7544:     }
 7545:     my @pairs=split(/\&/,$rep);
 7546:     my %returnhash=();
 7547:     if (!($rep =~ /^error/ )) {
 7548: 	foreach my $item (@pairs) {
 7549: 	    my ($key,$value)=split(/=/,$item,2);
 7550:         $key = unescape($key) unless $escapedkeys;
 7551:         #$key = &unescape($key);
 7552: 	    next if ($key =~ /^error: 2 /);
 7553: 	    $returnhash{$key}=&thaw_unescape($value);
 7554: 	}
 7555:     }
 7556:     return %returnhash;
 7557: }
 7558: 
 7559: 
 7560: # --------------------------------------------------------- dumpstore interface
 7561: 
 7562: sub dumpstore {
 7563:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
 7564:    # same as dump but keys must be escaped. They may contain colon separated
 7565:    # lists of values that may themself contain colons (e.g. symbs).
 7566:    return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
 7567: }
 7568: 
 7569: # -------------------------------------------------------------- keys interface
 7570: 
 7571: sub getkeys {
 7572:    my ($namespace,$udomain,$uname)=@_;
 7573:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 7574:    if (!$uname) { $uname=$env{'user.name'}; }
 7575:    my $uhome=&homeserver($uname,$udomain);
 7576:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
 7577:    my @keyarray=();
 7578:    foreach my $key (split(/\&/,$rep)) {
 7579:       next if ($key =~ /^error: 2 /);
 7580:       push(@keyarray,&unescape($key));
 7581:    }
 7582:    return @keyarray;
 7583: }
 7584: 
 7585: # --------------------------------------------------------------- currentdump
 7586: sub currentdump {
 7587:    my ($courseid,$sdom,$sname)=@_;
 7588:    $courseid = $env{'request.course.id'} if (! defined($courseid));
 7589:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
 7590:    $sname    = $env{'user.name'}         if (! defined($sname));
 7591:    my $uhome = &homeserver($sname,$sdom);
 7592:    my $rep;
 7593: 
 7594:    if (grep { $_ eq $uhome } current_machine_ids()) {
 7595:        $rep = LONCAPA::Lond::dump_profile_database(join(":", ($sdom, $sname, 
 7596:                    $courseid)));
 7597:    } else {
 7598:        $rep = reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
 7599:    }
 7600: 
 7601:    return if ($rep =~ /^(error:|no_such_host)/);
 7602:    #
 7603:    my %returnhash=();
 7604:    #
 7605:    if ($rep eq 'unknown_cmd') {
 7606:        # an old lond will not know currentdump
 7607:        # Do a dump and make it look like a currentdump
 7608:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
 7609:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
 7610:        my %hash = @tmp;
 7611:        @tmp=();
 7612:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
 7613:    } else {
 7614:        my @pairs=split(/\&/,$rep);
 7615:        foreach my $pair (@pairs) {
 7616:            my ($key,$value)=split(/=/,$pair,2);
 7617:            my ($symb,$param) = split(/:/,$key);
 7618:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
 7619:                                                         &thaw_unescape($value);
 7620:        }
 7621:    }
 7622:    return %returnhash;
 7623: }
 7624: 
 7625: sub convert_dump_to_currentdump{
 7626:     my %hash = %{shift()};
 7627:     my %returnhash;
 7628:     # Code ripped from lond, essentially.  The only difference
 7629:     # here is the unescaping done by lonnet::dump().  Conceivably
 7630:     # we might run in to problems with parameter names =~ /^v\./
 7631:     while (my ($key,$value) = each(%hash)) {
 7632:         my ($v,$symb,$param) = split(/:/,$key);
 7633: 	$symb  = &unescape($symb);
 7634: 	$param = &unescape($param);
 7635:         next if ($v eq 'version' || $symb eq 'keys');
 7636:         next if (exists($returnhash{$symb}) &&
 7637:                  exists($returnhash{$symb}->{$param}) &&
 7638:                  $returnhash{$symb}->{'v.'.$param} > $v);
 7639:         $returnhash{$symb}->{$param}=$value;
 7640:         $returnhash{$symb}->{'v.'.$param}=$v;
 7641:     }
 7642:     #
 7643:     # Remove all of the keys in the hashes which keep track of
 7644:     # the version of the parameter.
 7645:     while (my ($symb,$param_hash) = each(%returnhash)) {
 7646:         # use a foreach because we are going to delete from the hash.
 7647:         foreach my $key (keys(%$param_hash)) {
 7648:             delete($param_hash->{$key}) if ($key =~ /^v\./);
 7649:         }
 7650:     }
 7651:     return \%returnhash;
 7652: }
 7653: 
 7654: # ------------------------------------------------------ critical inc interface
 7655: 
 7656: sub cinc {
 7657:     return &inc(@_,'critical');
 7658: }
 7659: 
 7660: # --------------------------------------------------------------- inc interface
 7661: 
 7662: sub inc {
 7663:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
 7664:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 7665:     if (!$uname) { $uname=$env{'user.name'}; }
 7666:     my $uhome=&homeserver($uname,$udomain);
 7667:     my $items='';
 7668:     if (! ref($store)) {
 7669:         # got a single value, so use that instead
 7670:         $items = &escape($store).'=&';
 7671:     } elsif (ref($store) eq 'SCALAR') {
 7672:         $items = &escape($$store).'=&';        
 7673:     } elsif (ref($store) eq 'ARRAY') {
 7674:         $items = join('=&',map {&escape($_);} @{$store});
 7675:     } elsif (ref($store) eq 'HASH') {
 7676:         while (my($key,$value) = each(%{$store})) {
 7677:             $items.= &escape($key).'='.&escape($value).'&';
 7678:         }
 7679:     }
 7680:     $items=~s/\&$//;
 7681:     if ($critical) {
 7682: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
 7683:     } else {
 7684: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
 7685:     }
 7686: }
 7687: 
 7688: # --------------------------------------------------------------- put interface
 7689: 
 7690: sub put {
 7691:    my ($namespace,$storehash,$udomain,$uname,$encrypt)=@_;
 7692:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 7693:    if (!$uname) { $uname=$env{'user.name'}; }
 7694:    my $uhome=&homeserver($uname,$udomain);
 7695:    my $items='';
 7696:    foreach my $item (keys(%$storehash)) {
 7697:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 7698:    }
 7699:    $items=~s/\&$//;
 7700:    if ($encrypt) {
 7701:        return &reply("encrypt:put:$udomain:$uname:$namespace:$items",$uhome);
 7702:    } else {
 7703:        return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 7704:    }
 7705: }
 7706: 
 7707: # ------------------------------------------------------------ newput interface
 7708: 
 7709: sub newput {
 7710:    my ($namespace,$storehash,$udomain,$uname)=@_;
 7711:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 7712:    if (!$uname) { $uname=$env{'user.name'}; }
 7713:    my $uhome=&homeserver($uname,$udomain);
 7714:    my $items='';
 7715:    foreach my $key (keys(%$storehash)) {
 7716:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 7717:    }
 7718:    $items=~s/\&$//;
 7719:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
 7720: }
 7721: 
 7722: # ---------------------------------------------------------  putstore interface
 7723: 
 7724: sub putstore {
 7725:    my ($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog)=@_;
 7726:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 7727:    if (!$uname) { $uname=$env{'user.name'}; }
 7728:    my $uhome=&homeserver($uname,$udomain);
 7729:    my $items='';
 7730:    foreach my $key (keys(%$storehash)) {
 7731:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
 7732:    }
 7733:    $items=~s/\&$//;
 7734:    my $esc_symb=&escape($symb);
 7735:    my $esc_v=&escape($version);
 7736:    my $reply =
 7737:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
 7738: 	      $uhome);
 7739:    if (($tolog) && ($reply eq 'ok')) {
 7740:        my $namevalue='';
 7741:        foreach my $key (keys(%{$storehash})) {
 7742:            $namevalue.=&escape($key).'='.&freeze_escape($storehash->{$key}).'&';
 7743:        }
 7744:        my $ip = &get_requestor_ip();
 7745:        $namevalue .= 'ip='.&escape($ip).
 7746:                      '&host='.&escape($perlvar{'lonHostID'}).
 7747:                      '&version='.$esc_v.
 7748:                      '&by='.&escape($env{'user.name'}.':'.$env{'user.domain'});
 7749:        &courselog($symb.':'.$uname.':'.$udomain.':PUTSTORE:'.$namevalue);
 7750:    }
 7751:    if ($reply eq 'unknown_cmd') {
 7752:        # gfall back to way things use to be done
 7753:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
 7754: 			    $uname);
 7755:    }
 7756:    return $reply;
 7757: }
 7758: 
 7759: sub old_putstore {
 7760:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
 7761:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 7762:     if (!$uname) { $uname=$env{'user.name'}; }
 7763:     my $uhome=&homeserver($uname,$udomain);
 7764:     my %newstorehash;
 7765:     foreach my $item (keys(%$storehash)) {
 7766: 	my $key = $version.':'.&escape($symb).':'.$item;
 7767: 	$newstorehash{$key} = $storehash->{$item};
 7768:     }
 7769:     my $items='';
 7770:     my %allitems = ();
 7771:     foreach my $item (keys(%newstorehash)) {
 7772: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
 7773: 	    my $key = $1.':keys:'.$2;
 7774: 	    $allitems{$key} .= $3.':';
 7775: 	}
 7776: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
 7777:     }
 7778:     foreach my $item (keys(%allitems)) {
 7779: 	$allitems{$item} =~ s/\:$//;
 7780: 	$items.= $item.'='.$allitems{$item}.'&';
 7781:     }
 7782:     $items=~s/\&$//;
 7783:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 7784: }
 7785: 
 7786: # ------------------------------------------------------ critical put interface
 7787: 
 7788: sub cput {
 7789:    my ($namespace,$storehash,$udomain,$uname)=@_;
 7790:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 7791:    if (!$uname) { $uname=$env{'user.name'}; }
 7792:    my $uhome=&homeserver($uname,$udomain);
 7793:    my $items='';
 7794:    foreach my $item (keys(%$storehash)) {
 7795:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 7796:    }
 7797:    $items=~s/\&$//;
 7798:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
 7799: }
 7800: 
 7801: # -------------------------------------------------------------- eget interface
 7802: 
 7803: sub eget {
 7804:    my ($namespace,$storearr,$udomain,$uname)=@_;
 7805:    my $items='';
 7806:    foreach my $item (@$storearr) {
 7807:        $items.=&escape($item).'&';
 7808:    }
 7809:    $items=~s/\&$//;
 7810:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 7811:    if (!$uname) { $uname=$env{'user.name'}; }
 7812:    my $uhome=&homeserver($uname,$udomain);
 7813:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
 7814:    my @pairs=split(/\&/,$rep);
 7815:    my %returnhash=();
 7816:    my $i=0;
 7817:    foreach my $item (@$storearr) {
 7818:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 7819:       $i++;
 7820:    }
 7821:    return %returnhash;
 7822: }
 7823: 
 7824: # ------------------------------------------------------------ tmpput interface
 7825: sub tmpput {
 7826:     my ($storehash,$server,$context)=@_;
 7827:     my $items='';
 7828:     foreach my $item (keys(%$storehash)) {
 7829: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 7830:     }
 7831:     $items=~s/\&$//;
 7832:     if (defined($context)) {
 7833:         $items .= ':'.&escape($context);
 7834:     }
 7835:     return &reply("tmpput:$items",$server);
 7836: }
 7837: 
 7838: # ------------------------------------------------------------ tmpget interface
 7839: sub tmpget {
 7840:     my ($token,$server)=@_;
 7841:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 7842:     my $rep=&reply("tmpget:$token",$server);
 7843:     my %returnhash;
 7844:     if ($rep =~ /^(con_lost|error|no_such_host)/i) {
 7845:         return %returnhash;
 7846:     }
 7847:     foreach my $item (split(/\&/,$rep)) {
 7848: 	my ($key,$value)=split(/=/,$item);
 7849: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
 7850:     }
 7851:     return %returnhash;
 7852: }
 7853: 
 7854: # ------------------------------------------------------------ tmpdel interface
 7855: sub tmpdel {
 7856:     my ($token,$server)=@_;
 7857:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 7858:     return &reply("tmpdel:$token",$server);
 7859: }
 7860: 
 7861: # ------------------------------------------------------------ get_timebased_id 
 7862: 
 7863: sub get_timebased_id {
 7864:     my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
 7865:         $maxtries) = @_;
 7866:     my ($newid,$error,$dellock);
 7867:     unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {  
 7868:         return ('','ok','invalid call to get suffix');
 7869:     }
 7870: 
 7871: # set defaults for any optional args for which values were not supplied
 7872:     if ($who eq '') {
 7873:         $who = $env{'user.name'}.':'.$env{'user.domain'};
 7874:     }
 7875:     if (!$locktries) {
 7876:         $locktries = 3;
 7877:     }
 7878:     if (!$maxtries) {
 7879:         $maxtries = 10;
 7880:     }
 7881:     
 7882:     if (($cdom eq '') || ($cnum eq '')) {
 7883:         if ($env{'request.course.id'}) {
 7884:             $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 7885:             $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 7886:         }
 7887:         if (($cdom eq '') || ($cnum eq '')) {
 7888:             return ('','ok','call to get suffix not in course context');
 7889:         }
 7890:     }
 7891: 
 7892: # construct locking item
 7893:     my $lockhash = {
 7894:                       $prefix."\0".'locked_'.$keyid => $who,
 7895:                    };
 7896:     my $tries = 0;
 7897: 
 7898: # attempt to get lock on nohist_$namespace file
 7899:     my $gotlock = &newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
 7900:     while (($gotlock ne 'ok') && $tries <$locktries) {
 7901:         $tries ++;
 7902:         sleep 1;
 7903:         $gotlock = &newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
 7904:     }
 7905: 
 7906: # attempt to get unique identifier, based on current timestamp
 7907:     if ($gotlock eq 'ok') {
 7908:         my %inuse = &dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
 7909:         my $id = time;
 7910:         $newid = $id;
 7911:         if ($idtype eq 'addcode') {
 7912:             $newid .= &sixnum_code();
 7913:         }
 7914:         my $idtries = 0;
 7915:         while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
 7916:             if ($idtype eq 'concat') {
 7917:                 $newid = $id.$idtries;
 7918:             } elsif ($idtype eq 'addcode') {
 7919:                 $newid = $newid.&sixnum_code();
 7920:             } else {
 7921:                 $newid ++;
 7922:             }
 7923:             $idtries ++;
 7924:         }
 7925:         if (!exists($inuse{$prefix."\0".$newid})) {
 7926:             my %new_item =  (
 7927:                               $prefix."\0".$newid => $who,
 7928:                             );
 7929:             my $putresult = &put('nohist_'.$namespace,\%new_item,
 7930:                                                  $cdom,$cnum);
 7931:             if ($putresult ne 'ok') {
 7932:                 undef($newid);
 7933:                 $error = 'error saving new item: '.$putresult;
 7934:             }
 7935:         } else {
 7936:              undef($newid);
 7937:              $error = ('error: no unique suffix available for the new item ');
 7938:         }
 7939: #  remove lock
 7940:         my @del_lock = ($prefix."\0".'locked_'.$keyid);
 7941:         $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
 7942:     } else {
 7943:         $error = "error: could not obtain lockfile\n";
 7944:         $dellock = 'ok';
 7945:         if (($prefix eq 'paste') && ($namespace eq 'courseeditor') && ($keyid eq 'num')) {
 7946:             $dellock = 'nolock';
 7947:         }
 7948:     }
 7949:     return ($newid,$dellock,$error);
 7950: }
 7951: 
 7952: sub sixnum_code {
 7953:     my $code;
 7954:     for (0..6) {
 7955:         $code .= int( rand(9) );
 7956:     }
 7957:     return $code;
 7958: }
 7959: 
 7960: # -------------------------------------------------- portfolio access checking
 7961: 
 7962: sub portfolio_access {
 7963:     my ($requrl,$clientip) = @_;
 7964:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
 7965:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group,$clientip);
 7966:     if ($result) {
 7967:         my %setters;
 7968:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 7969:             my ($startblock,$endblock,$triggerblock,$by_ip,$blockdom) =
 7970:                 &Apache::loncommon::blockcheck(\%setters,'port',$clientip,$unum,$udom);
 7971:             if (($startblock && $endblock) || ($by_ip)) {
 7972:                 return 'B';
 7973:             }
 7974:         } else {
 7975:             my ($startblock,$endblock,$triggerblock,$by_ip,$blockdom) =
 7976:                 &Apache::loncommon::blockcheck(\%setters,'port',$clientip);
 7977:             if (($startblock && $endblock) || ($by_ip)) {
 7978:                 return 'B';
 7979:             }
 7980:         }
 7981:     }
 7982:     if ($result eq 'ok') {
 7983:        return 'F';
 7984:     } elsif ($result =~ /^[^:]+:guest_/) {
 7985:        return 'A';
 7986:     }
 7987:     return '';
 7988: }
 7989: 
 7990: sub get_portfolio_access {
 7991:     my ($udom,$unum,$file_name,$group,$clientip,$access_hash,$portaccessref) = @_;
 7992: 
 7993:     if (!ref($access_hash)) {
 7994: 	my $current_perms = &get_portfile_permissions($udom,$unum);
 7995: 	my %access_controls = &get_access_controls($current_perms,$group,
 7996: 						   $file_name);
 7997: 	$access_hash = $access_controls{$file_name};
 7998:     }
 7999: 
 8000:     my $portaccess;
 8001:     if (ref($portaccess) eq 'SCALAR') {
 8002:         $portaccess = $$portaccessref;
 8003:     } else {
 8004:         $portaccess = &usertools_access($unum,$udom,'portaccess',undef,'tools');
 8005:     }
 8006: 
 8007:     my ($public,$guest,@domains,@users,@courses,@groups,@ips,@userips);
 8008:     my $now = time;
 8009:     if (ref($access_hash) eq 'HASH') {
 8010:         foreach my $key (keys(%{$access_hash})) {
 8011:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
 8012:             next if (($scope ne 'ip') && ($portaccess == 0));
 8013:             if ($start > $now) {
 8014:                 next;
 8015:             }
 8016:             if ($end && $end<$now) {
 8017:                 next;
 8018:             }
 8019:             if ($scope eq 'public') {
 8020:                 $public = $key;
 8021:                 last;
 8022:             } elsif ($scope eq 'guest') {
 8023:                 $guest = $key;
 8024:             } elsif ($scope eq 'domains') {
 8025:                 push(@domains,$key);
 8026:             } elsif ($scope eq 'users') {
 8027:                 push(@users,$key);
 8028:             } elsif ($scope eq 'course') {
 8029:                 push(@courses,$key);
 8030:             } elsif ($scope eq 'group') {
 8031:                 push(@groups,$key);
 8032:             } elsif ($scope eq 'ip') {
 8033:                 push(@ips,$key);
 8034:             } elsif ($scope eq 'userip') {
 8035:                 push(@userips,$key);
 8036:             }
 8037:         }
 8038:         if ($public) {
 8039:             return 'ok';
 8040:         } elsif (@ips > 0) {
 8041:             my $allowed;
 8042:             foreach my $ipkey (@ips) {
 8043:                 if (ref($access_hash->{$ipkey}{'ip'}) eq 'ARRAY') {
 8044:                     if (&Apache::loncommon::check_ip_acc(join(',',@{$access_hash->{$ipkey}{'ip'}}),$clientip)) {
 8045:                         $allowed = 1;
 8046:                         last; 
 8047:                     }
 8048:                 }
 8049:             }
 8050:             if ($allowed) {
 8051:                 return 'ok';
 8052:             }
 8053:         } elsif (@userips > 0) {
 8054:             my $allowed;
 8055:             foreach my $useripkey (@userips) {
 8056:                 if (ref($access_hash->{$useripkey}{'ip'}) eq 'ARRAY') {
 8057:                     if (&Apache::loncommon::check_ip_acc(join(',',@{$access_hash->{$useripkey}{'ip'}}),$clientip)) {
 8058:                         $allowed = 1;
 8059:                         last;
 8060:                     }
 8061:                 }
 8062:             }
 8063:             if ($allowed) {
 8064:                 return 'ok';
 8065:             }
 8066:         }
 8067:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 8068:             if ($guest) {
 8069:                 return $guest;
 8070:             }
 8071:         } else {
 8072:             if (@domains > 0) {
 8073:                 foreach my $domkey (@domains) {
 8074:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
 8075:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
 8076:                             return 'ok';
 8077:                         }
 8078:                     }
 8079:                 }
 8080:             }
 8081:             if (@users > 0) {
 8082:                 foreach my $userkey (@users) {
 8083:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
 8084:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
 8085:                             if (ref($item) eq 'HASH') {
 8086:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
 8087:                                     ($item->{'udom'} eq $env{'user.domain'})) {
 8088:                                     return 'ok';
 8089:                                 }
 8090:                             }
 8091:                         }
 8092:                     } 
 8093:                 }
 8094:             }
 8095:             my %roleshash;
 8096:             my @courses_and_groups = @courses;
 8097:             push(@courses_and_groups,@groups); 
 8098:             if (@courses_and_groups > 0) {
 8099:                 my (%allgroups,%allroles); 
 8100:                 my ($start,$end,$role,$sec,$group);
 8101:                 foreach my $envkey (%env) {
 8102:                     if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
 8103:                         my $cid = $2.'_'.$3; 
 8104:                         if ($1 eq 'gr') {
 8105:                             $group = $4;
 8106:                             $allgroups{$cid}{$group} = $env{$envkey};
 8107:                         } else {
 8108:                             if ($4 eq '') {
 8109:                                 $sec = 'none';
 8110:                             } else {
 8111:                                 $sec = $4;
 8112:                             }
 8113:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
 8114:                         }
 8115:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
 8116:                         my $cid = $2.'_'.$3;
 8117:                         if ($4 eq '') {
 8118:                             $sec = 'none';
 8119:                         } else {
 8120:                             $sec = $4;
 8121:                         }
 8122:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
 8123:                     }
 8124:                 }
 8125:                 if (keys(%allroles) == 0) {
 8126:                     return;
 8127:                 }
 8128:                 foreach my $key (@courses_and_groups) {
 8129:                     my %content = %{$$access_hash{$key}};
 8130:                     my $cnum = $content{'number'};
 8131:                     my $cdom = $content{'domain'};
 8132:                     my $cid = $cdom.'_'.$cnum;
 8133:                     if (!exists($allroles{$cid})) {
 8134:                         next;
 8135:                     }    
 8136:                     foreach my $role_id (keys(%{$content{'roles'}})) {
 8137:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
 8138:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
 8139:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
 8140:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
 8141:                         foreach my $role (keys(%{$allroles{$cid}})) {
 8142:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
 8143:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
 8144:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
 8145:                                         if (grep/^all$/,@sections) {
 8146:                                             return 'ok';
 8147:                                         } else {
 8148:                                             if (grep/^$sec$/,@sections) {
 8149:                                                 return 'ok';
 8150:                                             }
 8151:                                         }
 8152:                                     }
 8153:                                 }
 8154:                                 if (keys(%{$allgroups{$cid}}) == 0) {
 8155:                                     if (grep/^none$/,@groups) {
 8156:                                         return 'ok';
 8157:                                     }
 8158:                                 } else {
 8159:                                     if (grep/^all$/,@groups) {
 8160:                                         return 'ok';
 8161:                                     } 
 8162:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
 8163:                                         if (grep/^$group$/,@groups) {
 8164:                                             return 'ok';
 8165:                                         }
 8166:                                     }
 8167:                                 } 
 8168:                             }
 8169:                         }
 8170:                     }
 8171:                 }
 8172:             }
 8173:             if ($guest) {
 8174:                 return $guest;
 8175:             }
 8176:         }
 8177:     }
 8178:     return;
 8179: }
 8180: 
 8181: sub course_group_datechecker {
 8182:     my ($dates,$now,$status) = @_;
 8183:     my ($start,$end) = split(/\./,$dates);
 8184:     if (!$start && !$end) {
 8185:         return 'ok';
 8186:     }
 8187:     if (grep/^active$/,@{$status}) {
 8188:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
 8189:             return 'ok';
 8190:         }
 8191:     }
 8192:     if (grep/^previous$/,@{$status}) {
 8193:         if ($end > $now ) {
 8194:             return 'ok';
 8195:         }
 8196:     }
 8197:     if (grep/^future$/,@{$status}) {
 8198:         if ($start > $now) {
 8199:             return 'ok';
 8200:         }
 8201:     }
 8202:     return; 
 8203: }
 8204: 
 8205: sub parse_portfolio_url {
 8206:     my ($url) = @_;
 8207: 
 8208:     my ($type,$udom,$unum,$group,$file_name);
 8209:     
 8210:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
 8211: 	$type = 1;
 8212:         $udom = $1;
 8213:         $unum = $2;
 8214:         $file_name = $3;
 8215:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
 8216: 	$type = 2;
 8217:         $udom = $1;
 8218:         $unum = $2;
 8219:         $group = $3;
 8220:         $file_name = $3.'/'.$4;
 8221:     }
 8222:     if (wantarray) {
 8223: 	return ($type,$udom,$unum,$file_name,$group);
 8224:     }
 8225:     return $type;
 8226: }
 8227: 
 8228: sub is_portfolio_url {
 8229:     my ($url) = @_;
 8230:     return scalar(&parse_portfolio_url($url));
 8231: }
 8232: 
 8233: sub is_portfolio_file {
 8234:     my ($file) = @_;
 8235:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
 8236:         return 1;
 8237:     }
 8238:     return;
 8239: }
 8240: 
 8241: sub is_coursetool_logo {
 8242:     my ($uri) = @_;
 8243:     if ($env{'request.course.id'}) {
 8244:         my $courseurl = &courseid_to_courseurl($env{'request.course.id'});
 8245:         if ($uri =~ m{^/*uploaded\Q$courseurl\E/toollogo/\d+/[^/]+$}) {
 8246:             return 1;
 8247:         }
 8248:     }
 8249:     return;
 8250: }
 8251: 
 8252: sub usertools_access {
 8253:     my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
 8254:     my ($access,%tools);
 8255:     if ($context eq '') {
 8256:         $context = 'tools';
 8257:     }
 8258:     if ($context eq 'requestcourses') {
 8259:         %tools = (
 8260:                       official   => 1,
 8261:                       unofficial => 1,
 8262:                       community  => 1,
 8263:                       textbook   => 1,
 8264:                       placement  => 1,
 8265:                       lti        => 1,
 8266:                  );
 8267:     } elsif ($context eq 'requestauthor') {
 8268:         %tools = (
 8269:                       requestauthor => 1,
 8270:                  );
 8271:     } elsif ($context eq 'authordefaults') {
 8272:         %tools = (
 8273:                       webdav    => 1,
 8274:                  );
 8275:     } else {
 8276:         %tools = (
 8277:                       aboutme   => 1,
 8278:                       blog      => 1,
 8279:                       portfolio => 1,
 8280:                       portaccess => 1,
 8281:                       timezone  => 1,
 8282:                  );
 8283:     }
 8284:     return if (!defined($tools{$tool}));
 8285: 
 8286:     if (($udom eq '') || ($uname eq '')) {
 8287:         $udom = $env{'user.domain'};
 8288:         $uname = $env{'user.name'};
 8289:     }
 8290: 
 8291:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 8292:         if ($action ne 'reload') {
 8293:             if ($context eq 'requestcourses') {
 8294:                 return $env{'environment.canrequest.'.$tool};
 8295:             } elsif ($context eq 'requestauthor') {
 8296:                 return $env{'environment.canrequest.author'};
 8297:             } elsif ($context eq 'authordefaults') {
 8298:                 if ($tool eq 'webdav') {
 8299:                     return $env{'environment.availabletools.'.$tool};
 8300:                 }
 8301:             } else {
 8302:                 return $env{'environment.availabletools.'.$tool};
 8303:             }
 8304:         }
 8305:     }
 8306: 
 8307:     my ($toolstatus,$inststatus,$envkey);
 8308:     if ($context eq 'requestauthor') {
 8309:         $envkey = $context;
 8310:     } elsif ($context eq 'authordefaults') {
 8311:         if ($tool eq 'webdav') {
 8312:             $envkey = 'tools.'.$tool;
 8313:         }
 8314:     } else {
 8315:         $envkey = $context.'.'.$tool;
 8316:     }
 8317: 
 8318:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
 8319:          ($action ne 'reload')) {
 8320:         $toolstatus = $env{'environment.'.$envkey};
 8321:         $inststatus = $env{'environment.inststatus'};
 8322:     } else {
 8323:         if (ref($userenvref) eq 'HASH') {
 8324:             $toolstatus = $userenvref->{$envkey};
 8325:             $inststatus = $userenvref->{'inststatus'};
 8326:         } else {
 8327:             my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
 8328:             $toolstatus = $userenv{$envkey};
 8329:             $inststatus = $userenv{'inststatus'};
 8330:         }
 8331:     }
 8332: 
 8333:     if ($toolstatus ne '') {
 8334:         if ($toolstatus) {
 8335:             $access = 1;
 8336:         } else {
 8337:             $access = 0;
 8338:         }
 8339:         return $access;
 8340:     }
 8341: 
 8342:     my ($is_adv,%domdef);
 8343:     if (ref($is_advref) eq 'HASH') {
 8344:         $is_adv = $is_advref->{'is_adv'};
 8345:     } else {
 8346:         $is_adv = &is_advanced_user($udom,$uname);
 8347:     }
 8348:     if (ref($domdefref) eq 'HASH') {
 8349:         %domdef = %{$domdefref};
 8350:     } else {
 8351:         %domdef = &get_domain_defaults($udom);
 8352:     }
 8353:     if (ref($domdef{$tool}) eq 'HASH') {
 8354:         if ($is_adv) {
 8355:             if ($domdef{$tool}{'_LC_adv'} ne '') {
 8356:                 if ($domdef{$tool}{'_LC_adv'}) { 
 8357:                     $access = 1;
 8358:                 } else {
 8359:                     $access = 0;
 8360:                 }
 8361:                 return $access;
 8362:             }
 8363:         }
 8364:         if ($inststatus ne '') {
 8365:             my ($hasaccess,$hasnoaccess);
 8366:             foreach my $affiliation (split(/:/,$inststatus)) {
 8367:                 if ($domdef{$tool}{$affiliation} ne '') { 
 8368:                     if ($domdef{$tool}{$affiliation}) {
 8369:                         $hasaccess = 1;
 8370:                     } else {
 8371:                         $hasnoaccess = 1;
 8372:                     }
 8373:                 }
 8374:             }
 8375:             if ($hasaccess || $hasnoaccess) {
 8376:                 if ($hasaccess) {
 8377:                     $access = 1;
 8378:                 } elsif ($hasnoaccess) {
 8379:                     $access = 0; 
 8380:                 }
 8381:                 return $access;
 8382:             }
 8383:         } else {
 8384:             if ($domdef{$tool}{'default'} ne '') {
 8385:                 if ($domdef{$tool}{'default'}) {
 8386:                     $access = 1;
 8387:                 } elsif ($domdef{$tool}{'default'} == 0) {
 8388:                     $access = 0;
 8389:                 }
 8390:                 return $access;
 8391:             }
 8392:         }
 8393:     } else {
 8394:         if (($context eq 'tools') && ($tool ne 'webdav')) {
 8395:             $access = 1;
 8396:         } else {
 8397:             $access = 0;
 8398:         }
 8399:         return $access;
 8400:     }
 8401: }
 8402: 
 8403: sub is_course_owner {
 8404:     my ($cdom,$cnum,$udom,$uname) = @_;
 8405:     if (($udom eq '') || ($uname eq '')) {
 8406:         $udom = $env{'user.domain'};
 8407:         $uname = $env{'user.name'};
 8408:     }
 8409:     unless (($udom eq '') || ($uname eq '')) {
 8410:         if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
 8411:             if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
 8412:                 return 1;
 8413:             } else {
 8414:                 my %courseinfo = &coursedescription($cdom.'/'.$cnum);
 8415:                 if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
 8416:                     return 1;
 8417:                 }
 8418:             }
 8419:         }
 8420:     }
 8421:     return;
 8422: }
 8423: 
 8424: sub is_advanced_user {
 8425:     my ($udom,$uname,$nocache) = @_;
 8426:     my ($is_adv,$is_author,$use_cache,$hashid);
 8427:     if ($udom ne '' && $uname ne '') {
 8428:         if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 8429:             if (wantarray) {
 8430:                 return ($env{'user.adv'},$env{'user.author'});
 8431:             } else {
 8432:                 return $env{'user.adv'};
 8433:             }
 8434:         } elsif (!$nocache) {
 8435:             $use_cache = 1;
 8436:             $hashid = "$udom:$uname";  
 8437:             my ($info,$cached)=&is_cached_new('isadvau',$hashid);
 8438:             if ($cached) {
 8439:                 ($is_adv,$is_author) = split(/:/,$info);
 8440:                 if (wantarray) {
 8441:                     return ($is_adv,$is_author);
 8442:                 }
 8443:                 return $is_adv; 
 8444:             }
 8445:         }
 8446:     }
 8447:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
 8448:     my %allroles;
 8449:     foreach my $role (keys(%roleshash)) {
 8450:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
 8451:         my $area = '/'.$tdomain.'/'.$trest;
 8452:         if ($sec ne '') {
 8453:             $area .= '/'.$sec;
 8454:         }
 8455:         if (($area ne '') && ($trole ne '')) {
 8456:             my $spec=$trole.'.'.$area;
 8457:             if ($trole =~ /^cr\//) {
 8458:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
 8459:             } elsif ($trole ne 'gr') {
 8460:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
 8461:             }
 8462:             if ($trole eq 'au') {
 8463:                 $is_author = 1;
 8464:             }
 8465:         }
 8466:     }
 8467:     foreach my $role (keys(%allroles)) {
 8468:         last if ($is_adv);
 8469:         foreach my $item (split(/:/,$allroles{$role})) {
 8470:             if ($item ne '') {
 8471:                 my ($privilege,$restrictions)=split(/&/,$item);
 8472:                 if ($privilege eq 'adv') {
 8473:                     $is_adv = 1;
 8474:                     last;
 8475:                 }
 8476:             }
 8477:         }
 8478:     }
 8479:     if ($use_cache) {
 8480:         my $cachetime = 600;
 8481:         &do_cache_new('isadvau',$hashid,$is_adv.':'.$is_author,$cachetime);
 8482:     }
 8483:     if (wantarray) {
 8484:         return ($is_adv,$is_author);
 8485:     }
 8486:     return $is_adv;
 8487: }
 8488: 
 8489: sub check_can_request {
 8490:     my ($dom,$can_request,$request_domains,$uname,$udom) = @_;
 8491:     my $canreq = 0;
 8492:     if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
 8493:         $uname = $env{'user.name'};
 8494:         $udom = $env{'user.domain'};
 8495:     }
 8496:     my ($types,$typename) = &Apache::loncommon::course_types();
 8497:     my @options = ('approval','validate','autolimit');
 8498:     my $optregex = join('|',@options);
 8499:     if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
 8500:         my %willtrust;
 8501:         foreach my $type (@{$types}) {
 8502:             if (&usertools_access($uname,$udom,$type,undef,
 8503:                                   'requestcourses')) {
 8504:                 $canreq ++;
 8505:                 if (ref($request_domains) eq 'HASH') {
 8506:                     push(@{$request_domains->{$type}},$udom);
 8507:                 }
 8508:                 if ($dom eq $udom) {
 8509:                     $can_request->{$type} = 1;
 8510:                 }
 8511:             }
 8512:             if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '') &&
 8513:                 ($env{'environment.reqcrsotherdom.'.$type} ne '')) {
 8514:                 my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
 8515:                 if (@curr > 0) {
 8516:                     foreach my $item (@curr) {
 8517:                         if (ref($request_domains) eq 'HASH') {
 8518:                             my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
 8519:                             if ($otherdom ne '') {
 8520:                                 unless (exists($willtrust{$otherdom})) {
 8521:                                     $willtrust{$otherdom} = &will_trust('reqcrs',$env{'user.domain'},$otherdom);
 8522:                                 }
 8523:                                 if ($willtrust{$otherdom}) {
 8524:                                     if (ref($request_domains->{$type}) eq 'ARRAY') {
 8525:                                         unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
 8526:                                             push(@{$request_domains->{$type}},$otherdom);
 8527:                                         }
 8528:                                     } else {
 8529:                                         push(@{$request_domains->{$type}},$otherdom);
 8530:                                     }
 8531:                                 }
 8532:                             }
 8533:                         }
 8534:                     }
 8535:                     unless ($dom eq $env{'user.domain'}) {
 8536:                         $canreq ++;
 8537:                         if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
 8538:                             $can_request->{$type} = 1;
 8539:                         }
 8540:                     }
 8541:                 }
 8542:             }
 8543:         }
 8544:     }
 8545:     return $canreq;
 8546: }
 8547: 
 8548: # ---------------------------------------------- Custom access rule evaluation
 8549: 
 8550: sub customaccess {
 8551:     my ($priv,$uri)=@_;
 8552:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
 8553:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
 8554:     $udom = &LONCAPA::clean_domain($udom);
 8555:     $ucrs = &LONCAPA::clean_username($ucrs);
 8556:     my $access=0;
 8557:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
 8558: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
 8559: 	if ($type eq 'user') {
 8560: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
 8561: 		my ($tdom,$tuname)=split(m{/},$scope);
 8562: 		if ($tdom) {
 8563: 		    if ($tdom ne $env{'user.domain'}) { next; }
 8564: 		}
 8565: 		if ($tuname) {
 8566: 		    if ($tuname ne $env{'user.name'}) { next; }
 8567: 		}
 8568: 		$access=($effect eq 'allow');
 8569: 		last;
 8570: 	    }
 8571: 	} else {
 8572: 	    if ($role) {
 8573: 		if ($role ne $urole) { next; }
 8574: 	    }
 8575: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
 8576: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
 8577: 		if ($tdom) {
 8578: 		    if ($tdom ne $udom) { next; }
 8579: 		}
 8580: 		if ($tcrs) {
 8581: 		    if ($tcrs ne $ucrs) { next; }
 8582: 		}
 8583: 		if ($tsec) {
 8584: 		    if ($tsec ne $usec) { next; }
 8585: 		}
 8586: 		$access=($effect eq 'allow');
 8587: 		last;
 8588: 	    }
 8589: 	    if ($realm eq '' && $role eq '') {
 8590: 		$access=($effect eq 'allow');
 8591: 	    }
 8592: 	}
 8593:     }
 8594:     return $access;
 8595: }
 8596: 
 8597: # ------------------------------------------------- Check for a user privilege
 8598: 
 8599: sub allowed {
 8600:     my ($priv,$uri,$symb,$role,$clientip,$noblockcheck,$ignorecache,$nodeeplinkcheck,$nodeeplinkout)=@_;
 8601:     my $ver_orguri=$uri;
 8602:     $uri=&deversion($uri);
 8603:     my $orguri=$uri;
 8604:     $uri=&declutter($uri);
 8605: 
 8606:     if ($priv eq 'evb') {
 8607: # Evade communication block restrictions for specified role in a course or domain
 8608:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
 8609:             return $1;
 8610:         } else {
 8611:             return;
 8612:         }
 8613:     }
 8614: 
 8615:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
 8616: # Free bre access to adm and meta resources
 8617:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard|viewclasslist|aboutme|ext\.tool)$})) 
 8618: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
 8619: 	&& ($priv eq 'bre')) {
 8620: 	return 'F';
 8621:     }
 8622: 
 8623: # Free bre access to user's own portfolio contents
 8624:     my ($space,$domain,$name,@dir)=split('/',$uri);
 8625:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
 8626: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
 8627:         my %setters;
 8628:         my ($startblock,$endblock,$triggerblock,$by_ip,$blockdom) = 
 8629:             &Apache::loncommon::blockcheck(\%setters,'port',$clientip);
 8630:         if (($startblock && $endblock) || ($by_ip)) {
 8631:             return 'B';
 8632:         } else {
 8633:             return 'F';
 8634:         }
 8635:     }
 8636: 
 8637: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
 8638:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
 8639:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
 8640:         if (exists($env{'request.course.id'})) {
 8641:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 8642:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 8643:             if (($domain eq $cdom) && ($name eq $cnum)) {
 8644:                 my $courseprivid=$env{'request.course.id'};
 8645:                 $courseprivid=~s/\_/\//;
 8646:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
 8647:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
 8648:                     return $1; 
 8649:                 } else {
 8650:                     if ($env{'request.course.sec'}) {
 8651:                         $courseprivid.='/'.$env{'request.course.sec'};
 8652:                     }
 8653:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
 8654:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
 8655:                         return $2;
 8656:                     }
 8657:                 }
 8658:             }
 8659:         }
 8660:     }
 8661: 
 8662: # Free bre to public access
 8663: 
 8664:     if ($priv eq 'bre') {
 8665:         my $copyright;
 8666:         unless ($uri =~ /ext\.tool/) {
 8667:             $copyright=&metadata($uri,'copyright');
 8668:         }
 8669: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
 8670:            return 'F'; 
 8671:         }
 8672:         if ($copyright eq 'priv') {
 8673:             $uri=~/([^\/]+)\/([^\/]+)\//;
 8674: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
 8675: 		return '';
 8676:             }
 8677:         }
 8678:         if ($copyright eq 'domain') {
 8679:             $uri=~/([^\/]+)\/([^\/]+)\//;
 8680: 	    unless (($env{'user.domain'} eq $1) ||
 8681:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
 8682: 		return '';
 8683:             }
 8684:         }
 8685:         if ($env{'request.role'}=~ /li\.\//) {
 8686:             # Library role, so allow browsing of resources in this domain.
 8687:             return 'F';
 8688:         }
 8689:         if ($copyright eq 'custom') {
 8690: 	    unless (&customaccess($priv,$uri)) { return ''; }
 8691:         }
 8692:     }
 8693:     # Domain coordinator is trying to create a course
 8694:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
 8695:         # uri is the requested domain in this case.
 8696:         # comparison to 'request.role.domain' shows if the user has selected
 8697:         # a role of dc for the domain in question.
 8698:         return 'F' if ($uri eq $env{'request.role.domain'});
 8699:     }
 8700: 
 8701:     my $thisallowed='';
 8702:     my $statecond=0;
 8703:     my $courseprivid='';
 8704: 
 8705:     my $ownaccess;
 8706:     # Community Coordinator or Assistant Co-author browsing resource space.
 8707:     if (($priv eq 'bro') && ($env{'user.author'})) {
 8708:         if ($uri eq '') {
 8709:             $ownaccess = 1;
 8710:         } else {
 8711:             if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
 8712:                 my $udom = $env{'user.domain'};
 8713:                 my $uname = $env{'user.name'};
 8714:                 if ($uri =~ m{^\Q$udom\E/?$}) {
 8715:                     $ownaccess = 1;
 8716:                 } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
 8717:                     unless ($uri =~ m{\.\./}) {
 8718:                         $ownaccess = 1;
 8719:                     }
 8720:                 } elsif (($udom ne 'public') && ($uname ne 'public')) {
 8721:                     my $now = time;
 8722:                     if ($uri =~ m{^([^/]+)/?$}) {
 8723:                         my $adom = $1;
 8724:                         foreach my $key (keys(%env)) {
 8725:                             if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
 8726:                                 my ($start,$end) = split(/\./,$env{$key});
 8727:                                 if (($now >= $start) && (!$end || $end > $now)) {
 8728:                                     $ownaccess = 1;
 8729:                                     last;
 8730:                                 }
 8731:                             }
 8732:                         }
 8733:                     } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
 8734:                         my $adom = $1;
 8735:                         my $aname = $2;
 8736:                         foreach my $role ('ca','aa') { 
 8737:                             if ($env{"user.role.$role./$adom/$aname"}) {
 8738:                                 my ($start,$end) =
 8739:                                     split(/\./,$env{"user.role.$role./$adom/$aname"});
 8740:                                 if (($now >= $start) && (!$end || $end > $now)) {
 8741:                                     $ownaccess = 1;
 8742:                                     last;
 8743:                                 }
 8744:                             }
 8745:                         }
 8746:                     }
 8747:                 }
 8748:             }
 8749:         }
 8750:     }
 8751: 
 8752: # Course
 8753: 
 8754:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
 8755:         unless (($priv eq 'bro') && (!$ownaccess)) {
 8756:             $thisallowed.=$1;
 8757:         }
 8758:     }
 8759: 
 8760: # Domain
 8761: 
 8762:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
 8763:        =~/\Q$priv\E\&([^\:]*)/) {
 8764:         unless (($priv eq 'bro') && (!$ownaccess)) {
 8765:             $thisallowed.=$1;
 8766:         }
 8767:     }
 8768: 
 8769: # User who is not author or co-author might still be able to edit
 8770: # resource of an author in the domain (e.g., if Domain Coordinator).
 8771:     if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
 8772:         (&allowed('mdc',$env{'request.course.id'}))) {
 8773:         if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
 8774:             $thisallowed.=$1;
 8775:         }
 8776:     }
 8777: 
 8778: # Course: uri itself is a course
 8779:     my $courseuri=$uri;
 8780:     $courseuri=~s/\_(\d)/\/$1/;
 8781:     $courseuri=~s/^([^\/])/\/$1/;
 8782: 
 8783:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
 8784:        =~/\Q$priv\E\&([^\:]*)/) {
 8785:         if ($priv eq 'mip') {
 8786:             my $rem = $1;
 8787:             if (($uri ne '') && ($env{'request.course.id'} eq $uri) &&
 8788:                 ($env{'course.'.$env{'request.course.id'}.'.internal.courseowner'} eq $env{'user.name'}.':'.$env{'user.domain'})) {
 8789:                 my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 8790:                 if ($cdom ne '') {
 8791:                     my %passwdconf = &get_passwdconf($cdom);
 8792:                     if (ref($passwdconf{'crsownerchg'}) eq 'HASH') {
 8793:                         if (ref($passwdconf{'crsownerchg'}{'by'}) eq 'ARRAY') {
 8794:                             if (@{$passwdconf{'crsownerchg'}{'by'}}) {
 8795:                                 my @inststatuses = split(':',$env{'environment.inststatus'});
 8796:                                 unless (@inststatuses) {
 8797:                                     @inststatuses = ('default');
 8798:                                 }
 8799:                                 foreach my $status (@inststatuses) {
 8800:                                     if (grep(/^\Q$status\E$/,@{$passwdconf{'crsownerchg'}{'by'}})) {
 8801:                                         $thisallowed.=$rem;
 8802:                                     }
 8803:                                 }
 8804:                             }
 8805:                         }
 8806:                     }
 8807:                 }
 8808:             }
 8809:         } else {
 8810:             unless (($priv eq 'bro') && (!$ownaccess)) {
 8811:                 $thisallowed.=$1;
 8812:             }
 8813:         }
 8814:     }
 8815: 
 8816: # URI is an uploaded document for this course, default permissions don't matter
 8817: # not allowing 'edit' access (editupload) to uploaded course docs
 8818:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
 8819: 	$thisallowed='';
 8820:         my ($match)=&is_on_map($uri);
 8821:         if ($match) {
 8822:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
 8823:                   =~/\Q$priv\E\&([^\:]*)/) {
 8824:                 my $value = $1;
 8825:                 my $deeplinkblock;
 8826:                 unless ($nodeeplinkcheck) {
 8827:                     $deeplinkblock = &deeplink_check($priv,$symb,$uri);
 8828:                 }
 8829:                 if ($deeplinkblock) {
 8830:                     $thisallowed='D';
 8831:                 } elsif ($noblockcheck) {
 8832:                     $thisallowed.=$value;
 8833:                 } else {
 8834:                     my @blockers = &has_comm_blocking($priv,$symb,$uri,$ignorecache);
 8835:                     if (@blockers > 0) {
 8836:                         $thisallowed = 'B';
 8837:                     } else {
 8838:                         $thisallowed.=$value;
 8839:                     }
 8840:                 }
 8841:             }
 8842:         } else {
 8843:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
 8844:             if ($refuri) {
 8845:                 if ($refuri =~ m|^/adm/|) {
 8846:                     $thisallowed='F';
 8847:                 } else {
 8848:                     $refuri=&declutter($refuri);
 8849:                     my ($match) = &is_on_map($refuri);
 8850:                     if ($match) {
 8851:                         my $deeplinkblock;
 8852:                         unless ($nodeeplinkcheck) {
 8853:                             $deeplinkblock = &deeplink_check($priv,$symb,$refuri);
 8854:                         }
 8855:                         if ($deeplinkblock) {
 8856:                             $thisallowed='D';
 8857:                         } elsif ($noblockcheck) {
 8858:                             $thisallowed='F';
 8859:                         } else {
 8860:                             my @blockers = &has_comm_blocking($priv,'',$refuri,'',1);
 8861:                             if (@blockers > 0) {
 8862:                                 $thisallowed = 'B';
 8863:                             } else {
 8864:                                 $thisallowed='F';
 8865:                             }
 8866:                         }
 8867:                     }
 8868:                 }
 8869:             }
 8870:         }
 8871:     }
 8872: 
 8873:     if ($priv eq 'bre'
 8874: 	&& $thisallowed ne 'F' 
 8875: 	&& $thisallowed ne '2'
 8876: 	&& &is_portfolio_url($uri)) {
 8877: 	$thisallowed = &portfolio_access($uri,$clientip);
 8878:     }
 8879: 
 8880: # Full access at system, domain or course-wide level? Exit.
 8881:     if ($thisallowed=~/F/) {
 8882: 	return 'F';
 8883:     }
 8884: 
 8885: # If this is generating or modifying users, exit with special codes
 8886: 
 8887:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:vca:vaa:'=~/\:\Q$priv\E\:/) {
 8888: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
 8889: 	    my ($audom,$auname)=split('/',$uri);
 8890: # no author name given, so this just checks on the general right to make a co-author in this domain
 8891: 	    unless ($auname) { return $thisallowed; }
 8892: # an author name is given, so we are about to actually make a co-author for a certain account
 8893: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
 8894: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
 8895: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
 8896: 	} elsif (($priv eq 'vca') || ($priv eq 'vaa')) {
 8897:             my ($audom,$auname)=split('/',$uri);
 8898:             unless ($auname) { return $thisallowed; }
 8899:             unless (($env{'request.role'} eq "dc./$audom") ||
 8900:                     ($env{'request.role'} eq "ca./$uri")) {
 8901:                 return '';
 8902:             }
 8903: 	}
 8904: 	return $thisallowed;
 8905:     }
 8906: #
 8907: # Gathered so far: system, domain and course wide privileges
 8908: #
 8909: # Course: See if uri or referer is an individual resource that is part of 
 8910: # the course
 8911: 
 8912:     if ($env{'request.course.id'}) {
 8913: 
 8914:         if ($priv eq 'bre') {
 8915:             if (&is_coursetool_logo($uri)) {
 8916:                 return 'F';
 8917:             }
 8918:         }
 8919: 
 8920: # If this is modifying password (internal auth) domains must match for user and user's role.
 8921: 
 8922:         if ($priv eq 'mip') {
 8923:             if ($env{'user.domain'} eq $env{'request.role.domain'}) {
 8924:                 return $thisallowed;
 8925:             } else {
 8926:                 return '';
 8927:             }
 8928:         }
 8929: 
 8930:        $courseprivid=$env{'request.course.id'};
 8931:        if ($env{'request.course.sec'}) {
 8932:           $courseprivid.='/'.$env{'request.course.sec'};
 8933:        }
 8934:        $courseprivid=~s/\_/\//;
 8935:        my $checkreferer=1;
 8936:        my ($match,$cond)=&is_on_map($uri);
 8937:        if ($match) {
 8938:            $statecond=$cond;
 8939:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 8940:                =~/\Q$priv\E\&([^\:]*)/) {
 8941:                my $value = $1;
 8942:                if ($priv eq 'bre') {
 8943:                    my $deeplinkblock;
 8944:                    unless ($nodeeplinkcheck) {
 8945:                        $deeplinkblock = &deeplink_check($priv,$symb,$uri);
 8946:                    }
 8947:                    if ($deeplinkblock) {
 8948:                        $thisallowed = 'D';
 8949:                    } elsif ($noblockcheck) {
 8950:                        $thisallowed.=$value;
 8951:                    } else {
 8952:                        my @blockers = &has_comm_blocking($priv,$symb,$uri,$ignorecache);
 8953:                        if (@blockers > 0) {
 8954:                            $thisallowed = 'B';
 8955:                        } else {
 8956:                            $thisallowed.=$value;
 8957:                        }
 8958:                    }
 8959:                } else {
 8960:                    $thisallowed.=$value;
 8961:                }
 8962:                $checkreferer=0;
 8963:            }
 8964:        }
 8965: 
 8966:        if ($checkreferer) {
 8967: 	  my $refuri=$env{'httpref.'.$orguri};
 8968:             unless ($refuri) {
 8969:                 foreach my $key (keys(%env)) {
 8970: 		    if ($key=~/^httpref\..*\*/) {
 8971: 			my $pattern=$key;
 8972:                         $pattern=~s/^httpref\.\/res\///;
 8973:                         $pattern=~s/\*/\[\^\/\]\+/g;
 8974:                         $pattern=~s/\//\\\//g;
 8975:                         if ($orguri=~/$pattern/) {
 8976: 			    $refuri=$env{$key};
 8977:                         }
 8978:                     }
 8979:                 }
 8980:             }
 8981: 
 8982:          if ($refuri) { 
 8983: 	  $refuri=&declutter($refuri);
 8984:           my ($match,$cond)=&is_on_map($refuri);
 8985:             if ($match) {
 8986:               my $refstatecond=$cond;
 8987:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 8988:                   =~/\Q$priv\E\&([^\:]*)/) {
 8989:                   my $value = $1;
 8990:                   if ($priv eq 'bre') {
 8991:                       my $deeplinkblock;
 8992:                       unless ($nodeeplinkcheck) {
 8993:                           $deeplinkblock = &deeplink_check($priv,$symb,$refuri);
 8994:                       }
 8995:                       if ($deeplinkblock) {
 8996:                           $thisallowed = 'D';
 8997:                       } elsif ($noblockcheck) {
 8998:                           $thisallowed.=$value;
 8999:                       } else {
 9000:                           my @blockers = &has_comm_blocking($priv,'',$refuri,'',1);
 9001:                           if (@blockers > 0) {
 9002:                               $thisallowed = 'B';
 9003:                           } else {
 9004:                               $thisallowed.=$value;
 9005:                           }
 9006:                       }
 9007:                   } else {
 9008:                       $thisallowed.=$value;
 9009:                   }
 9010:                   $uri=$refuri;
 9011:                   $statecond=$refstatecond;
 9012:               }
 9013:           }
 9014:         }
 9015:        }
 9016:    }
 9017: 
 9018: #
 9019: # Gathered now: all privileges that could apply, and condition number
 9020: # 
 9021: #
 9022: # Full or no access?
 9023: #
 9024: 
 9025:     if ($thisallowed=~/F/) {
 9026: 	return 'F';
 9027:     }
 9028: 
 9029:     unless ($thisallowed) {
 9030:         return '';
 9031:     }
 9032: 
 9033: # Restrictions exist, deal with them
 9034: #
 9035: #   C:according to course preferences
 9036: #   R:according to resource settings
 9037: #   L:unless locked
 9038: #   X:according to user session state
 9039: #
 9040: 
 9041: # Possibly locked functionality, check all courses
 9042: # In roles.tab, L (unless locked) available for bre, pch, plc, pac and sma.
 9043: # Locks might take effect only after 10 minutes cache expiration for other
 9044: # courses, and 2 minutes for current course, in which user has st or ta role
 9045: # which is neither expired nor a future role (unless current course).
 9046: 
 9047:     my ($needlockcheck,$now,$crsonly);
 9048:     if ($thisallowed=~/L/) {
 9049:         $now = time;
 9050:         if ($priv eq 'bre') {
 9051:             if ($uri ne '') {
 9052:                 if ($orguri =~ m{^/+res/}) {
 9053:                     if ($uri =~ m{^lib/templates/}) {
 9054:                         if ($env{'request.course.id'}) {
 9055:                             $crsonly = 1;
 9056:                             $needlockcheck = 1;
 9057:                         }
 9058:                     } else {
 9059:                         $needlockcheck = 1;
 9060:                     }
 9061:                 } elsif ($env{'request.course.id'}) {
 9062:                     my ($crsdom,$crsnum) = split('_',$env{'request.course.id'});
 9063:                     if (($uri =~ m{^(adm|uploaded|public)/$crsdom/$crsnum/}) ||
 9064:                         ($uri =~ m{^adm/$match_domain/$match_username/\d+/(smppg|bulletinboard)$})) {
 9065:                         $crsonly = 1;
 9066:                     }
 9067:                     $needlockcheck = 1;
 9068:                 }
 9069:             }
 9070:         } elsif (($priv eq 'pch') || ($priv eq 'plc') || ($priv eq 'pac') || ($priv eq 'sma')) {
 9071:             $needlockcheck = 1;
 9072:         }
 9073:     }
 9074:     if ($needlockcheck) {
 9075:         foreach my $envkey (keys(%env)) {
 9076:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
 9077:                my $courseid=$2;
 9078:                my $roleid=$1.'.'.$2;
 9079:                $courseid=~s/^\///;
 9080:                unless ($env{'request.role'} eq $roleid) {
 9081:                    my ($start,$end) = split(/\./,$env{$envkey});
 9082:                    next unless (($now >= $start) && (!$end || $end > $now));
 9083:                }
 9084:                my $expiretime=600;
 9085:                if ($env{'request.role'} eq $roleid) {
 9086: 		  $expiretime=120;
 9087:                }
 9088: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
 9089:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
 9090:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
 9091: 		   &coursedescription($courseid,{'freshen_cache' => 1});
 9092:                }
 9093:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
 9094:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
 9095: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
 9096:                        &log($env{'user.domain'},$env{'user.name'},
 9097:                             $env{'user.home'},
 9098:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
 9099:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 9100:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 9101: 		       return '';
 9102:                    }
 9103:                }
 9104:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
 9105:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
 9106: 		   if ($env{$prefix.'priv.'.$priv.'.lock.expire'}>time) {
 9107:                        &log($env{'user.domain'},$env{'user.name'},
 9108:                             $env{'user.home'},
 9109:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
 9110:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 9111:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 9112: 		       return '';
 9113:                    }
 9114:                }
 9115: 	   }
 9116:        }
 9117:     }
 9118: 
 9119: #
 9120: # Rest of the restrictions depend on selected course
 9121: #
 9122: 
 9123:     unless ($env{'request.course.id'}) {
 9124: 	if ($thisallowed eq 'A') {
 9125: 	    return 'A';
 9126:         } elsif ($thisallowed eq 'B') {
 9127:             return 'B';
 9128: 	} else {
 9129: 	    return '1';
 9130: 	}
 9131:     }
 9132: 
 9133: #
 9134: # Now user is definitely in a course
 9135: #
 9136: 
 9137: 
 9138: # Course preferences
 9139: 
 9140:    if ($thisallowed=~/C/) {
 9141:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 9142:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
 9143:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
 9144: 	   =~/\Q$rolecode\E/) {
 9145: 	   if (($priv ne 'pch') && ($priv ne 'plc') && ($priv ne 'pac')) {
 9146: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 9147: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
 9148: 			$env{'request.course.id'});
 9149: 	   }
 9150:            return '';
 9151:        }
 9152: 
 9153:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
 9154: 	   =~/\Q$unamedom\E/) {
 9155: 	   if (($priv ne 'pch') && ($priv ne 'plc') && ($priv ne 'pac')) {
 9156: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
 9157: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
 9158: 			$env{'request.course.id'});
 9159: 	   }
 9160:            return '';
 9161:        }
 9162:    }
 9163: 
 9164: # Resource preferences
 9165: 
 9166:    if ($thisallowed=~/R/) {
 9167:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 9168:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
 9169: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
 9170: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 9171: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
 9172: 	   }
 9173: 	   return '';
 9174:        }
 9175:    }
 9176: 
 9177: # Restricted for deeplinked session?
 9178: 
 9179:     if ($env{'request.deeplink.login'}) {
 9180:         if ($env{'acc.deeplinkout'} && !$nodeeplinkout) {
 9181:             if (!$symb) { $symb=&symbread($uri,1); }
 9182:             if (($symb) && ($env{'acc.deeplinkout'}=~/\&\Q$symb\E\&/)) {
 9183:                 return '';
 9184:             }
 9185:         }
 9186:     }
 9187: 
 9188: # Restricted by state or randomout?
 9189: 
 9190:    if ($thisallowed=~/X/) {
 9191:       if ($env{'acc.randomout'}) {
 9192: 	 if (!$symb) { $symb=&symbread($uri,1); }
 9193:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
 9194:             return ''; 
 9195:          }
 9196:       }
 9197:       if (&condval($statecond)) {
 9198: 	 return '2';
 9199:       } else {
 9200:          return '';
 9201:       }
 9202:    }
 9203: 
 9204:     if ($thisallowed eq 'A') {
 9205: 	return 'A';
 9206:     } elsif ($thisallowed eq 'B') {
 9207:         return 'B';
 9208:     } elsif ($thisallowed eq 'D') {
 9209:         return 'D';
 9210:     }
 9211:    return 'F';
 9212: }
 9213: 
 9214: # ------------------------------------------- Check construction space access
 9215: 
 9216: sub constructaccess {
 9217:     my ($url,$setpriv)=@_;
 9218: 
 9219: # We do not allow editing of previous versions of files
 9220:     if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
 9221: 
 9222: # Get username and domain from URL
 9223:     my ($ownername,$ownerdomain,$ownerhome);
 9224: 
 9225:     ($ownerdomain,$ownername) =
 9226:         ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)(?:/daxepage|/daxeopen)?/priv/($match_domain)/($match_username)(?:/|$)});
 9227: 
 9228: # The URL does not really point to any authorspace, forget it
 9229:     unless (($ownername) && ($ownerdomain)) { return ''; }
 9230: 
 9231: # Now we need to see if the user has access to the authorspace of
 9232: # $ownername at $ownerdomain
 9233: 
 9234:     if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
 9235: # Real author for this?
 9236:        $ownerhome = $env{'user.home'};
 9237:        if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
 9238:           return ($ownername,$ownerdomain,$ownerhome);
 9239:        }
 9240:     } elsif (&is_course($ownerdomain,$ownername)) {
 9241: # Course Authoring Space?
 9242:         if ($env{'request.course.id'}) {
 9243:             if (($ownername eq $env{'course.'.$env{'request.course.id'}.'.num'}) &&
 9244:                 ($ownerdomain eq $env{'course.'.$env{'request.course.id'}.'.domain'})) {
 9245:                 if (&allowed('mdc',$env{'request.course.id'})) {
 9246:                     return if ($env{'course.'.$env{'request.course.id'}.'.internal.crsauthor'} eq '0');
 9247:                     unless ($env{'course.'.$env{'request.course.id'}.'.internal.crsauthor'}) {
 9248:                         my %domdefs = &get_domain_defaults($ownerdomain);
 9249:                         my $type = lc($env{'course.'.$env{'request.course.id'}.'.type'});
 9250:                         unless (($type eq 'community') || ($type eq 'placement')) {
 9251:                             $type = 'unofficial';
 9252:                             if ($env{'course.'.$env{'request.course.id'}.'internal.coursecode'} ne '') {
 9253:                                 $type = 'official';
 9254:                             } elsif ($env{'course.'.$env{'request.course.id'}.'internal.textbook'} ne '') {
 9255:                                 $type = 'textbook';
 9256:                             } else {
 9257:                                 $type = 'unofficial';
 9258:                             }
 9259:                         }
 9260:                         return if ($domdefs{$type.'crsauthor'} eq '0');
 9261:                     }
 9262:                     $ownerhome = $env{'course.'.$env{'request.course.id'}.'.home'};
 9263:                     return ($ownername,$ownerdomain,$ownerhome);
 9264:                 }
 9265:             }
 9266:         }
 9267:         return '';
 9268:     } else {
 9269: # Co-author for this?
 9270:         if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
 9271:             exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
 9272:             $ownerhome = &homeserver($ownername,$ownerdomain);
 9273:             return ($ownername,$ownerdomain,$ownerhome);
 9274:         }
 9275:     }
 9276: 
 9277: # We don't have any access right now. If we are not possibly going to do anything about this,
 9278: # we might as well leave
 9279:    unless ($setpriv) { return ''; }
 9280: 
 9281: # Backdoor access?
 9282:     my $allowed=&allowed('eco',$ownerdomain);
 9283: # Nope
 9284:     unless ($allowed) { return ''; }
 9285: # Looks like we may have access, but could be locked by the owner of the construction space
 9286:     if ($allowed eq 'U') {
 9287:         my %blocked=&get('environment',['domcoord.author'],
 9288:                          $ownerdomain,$ownername);
 9289: # Is blocked by owner
 9290:         if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
 9291:     }
 9292:     if (($allowed eq 'F') || ($allowed eq 'U')) {
 9293: # Grant temporary access
 9294:         my $then=$env{'user.login.time'};
 9295:         my $update=$env{'user.update.time'};
 9296:         if (!$update) { $update = $then; }
 9297:         my $refresh=$env{'user.refresh.time'};
 9298:         if (!$refresh) { $refresh = $update; }
 9299:         my $now = time;
 9300:         &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
 9301:                            $now,'ca','constructaccess');
 9302:         $ownerhome = &homeserver($ownername,$ownerdomain);
 9303:         return($ownername,$ownerdomain,$ownerhome);
 9304:     }
 9305: # No business here
 9306:     return '';
 9307: }
 9308: 
 9309: # ----------------------------------------------------------- Content Blocking
 9310: 
 9311: {
 9312: # Caches for faster Course Contents display where content blocking
 9313: # is in operation (i.e., interval param set) for timed quiz.
 9314: #
 9315: # User for whom data are being temporarily cached.
 9316: my $cacheduser='';
 9317: # Course for which data are being temporarily cached.
 9318: my $cachedcid='';
 9319: # Cached blockers for this user (a hash of blocking items). 
 9320: my %cachedblockers=();
 9321: # When the data were last cached.
 9322: my $cachedlast='';
 9323: 
 9324: sub load_all_blockers {
 9325:     my ($uname,$udom)=@_;
 9326:     if (($uname ne '') && ($udom ne '')) { 
 9327:         if (($cacheduser eq $uname.':'.$udom) &&
 9328:             ($cachedcid eq $env{'request.course.id'}) &&
 9329:             (abs($cachedlast-time)<5)) {
 9330:             return;
 9331:         }
 9332:     }
 9333:     $cachedlast=time;
 9334:     $cacheduser=$uname.':'.$udom;
 9335:     $cachedcid=$env{'request.course.id'};
 9336:     %cachedblockers = &get_commblock_resources();
 9337:     return;
 9338: }
 9339: 
 9340: sub get_comm_blocks {
 9341:     my ($cdom,$cnum) = @_;
 9342:     if ($cdom eq '' || $cnum eq '') {
 9343:         return unless ($env{'request.course.id'});
 9344:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 9345:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 9346:     }
 9347:     my %commblocks;
 9348:     my $hashid=$cdom.'_'.$cnum;
 9349:     my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
 9350:     if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
 9351:         %commblocks = %{$blocksref};
 9352:     } else {
 9353:         %commblocks = &dump('comm_block',$cdom,$cnum);
 9354:         my $cachetime = 600;
 9355:         &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
 9356:     }
 9357:     return %commblocks;
 9358: }
 9359: 
 9360: sub get_commblock_resources {
 9361:     my ($blocks) = @_;
 9362:     my %blockers = ();
 9363:     return %blockers unless ($env{'request.course.id'});
 9364:     my $courseurl = &courseid_to_courseurl($env{'request.course.id'});
 9365:     if ($env{'request.course.sec'}) {
 9366:         $courseurl .= '/'.$env{'request.course.sec'};
 9367:     }
 9368:     return %blockers if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseurl} =~/evb\&([^\:]*)/);
 9369:     my %commblocks;
 9370:     if (ref($blocks) eq 'HASH') {
 9371:         %commblocks = %{$blocks};
 9372:     } else {
 9373:         %commblocks = &get_comm_blocks();
 9374:     }
 9375:     return %blockers unless (keys(%commblocks) > 0); 
 9376:     my $navmap = Apache::lonnavmaps::navmap->new();
 9377:     return %blockers unless (ref($navmap));
 9378:     my $now = time;
 9379:     foreach my $block (keys(%commblocks)) {
 9380:         if ($block =~ /^(\d+)____(\d+)$/) {
 9381:             my ($start,$end) = ($1,$2);
 9382:             if ($start <= $now && $end >= $now) {
 9383:                 if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
 9384:                     if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
 9385:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
 9386:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
 9387:                                 $blockers{$block}{maps} = $commblocks{$block}{'blocks'}{'docs'}{'maps'}; 
 9388:                             }
 9389:                         }
 9390:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
 9391:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
 9392:                                 $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
 9393:                             }
 9394:                         }
 9395:                     }
 9396:                 }
 9397:             }
 9398:         } elsif ($block =~ /^firstaccess____(.+)$/) {
 9399:             my $item = $1;
 9400:             if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
 9401:                 if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
 9402:                     my (@interval,$mapname);
 9403:                     my $type = 'map';
 9404:                     if ($item eq 'course') {
 9405:                         $type = 'course';
 9406:                         @interval=&EXT("resource.0.interval");
 9407:                     } else {
 9408:                         if ($item =~ /___\d+___/) {
 9409:                             $type = 'resource';
 9410:                             @interval=&EXT("resource.0.interval",$item);
 9411:                         } else {
 9412:                             $mapname = &deversion($item);
 9413:                             if (ref($navmap)) {
 9414:                                 my $timelimit = $navmap->get_mapparam(undef,$mapname,'0.interval');
 9415:                                 @interval = ($timelimit,'map');
 9416:                             }
 9417:                         }
 9418:                     }
 9419:                     if ($interval[0] =~ /^(\d+)/) {
 9420:                         my $timelimit = $1; 
 9421:                         my $first_access;
 9422:                         if ($type eq 'resource') {
 9423:                             $first_access=&get_first_access($interval[1],$item);
 9424:                         } elsif ($type eq 'map') {
 9425:                             $first_access=&get_first_access($interval[1],undef,$item);
 9426:                         } else {
 9427:                             $first_access=&get_first_access($interval[1]);
 9428:                         }
 9429:                         if ($first_access) {
 9430:                             my $timesup = $first_access+$timelimit;
 9431:                             if ($timesup > $now) {
 9432:                                 my $activeblock;
 9433:                                 if ($type eq 'resource') {
 9434:                                     if (ref($navmap)) {
 9435:                                         my $res = $navmap->getBySymb($item);
 9436:                                         if ($res->answerable()) {
 9437:                                             $activeblock = 1;
 9438:                                         }
 9439:                                     }
 9440:                                 } elsif ($type eq 'map') {
 9441:                                     my $mapsymb = &symbread($mapname,1);
 9442:                                     if (($mapsymb) && (ref($navmap))) {
 9443:                                         my $mapres = $navmap->getBySymb($mapsymb);
 9444:                                         if (ref($mapres)) {
 9445:                                             my $first = $mapres->map_start();
 9446:                                             my $finish = $mapres->map_finish();
 9447:                                             my $it = $navmap->getIterator($first,$finish,undef,0,0);
 9448:                                             if (ref($it)) {
 9449:                                                 my $res;
 9450:                                                 while ($res = $it->next(undef,1)) {
 9451:                                                     next unless (ref($res));
 9452:                                                     my $symb = $res->symb();
 9453:                                                     next if (($symb eq $mapsymb) || ($symb eq ''));
 9454:                                                     @interval=&EXT("resource.0.interval",$symb);
 9455:                                                     if ($interval[1] eq 'map') {
 9456:                                                         if ($res->answerable()) {
 9457:                                                             $activeblock = 1;
 9458:                                                             last;
 9459:                                                         }
 9460:                                                     }
 9461:                                                 }
 9462:                                             }
 9463:                                         }
 9464:                                     }
 9465:                                 }
 9466:                                 if ($activeblock) {
 9467:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
 9468:                                          if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
 9469:                                              $blockers{$block}{'maps'} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
 9470:                                          }
 9471:                                     }
 9472:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
 9473:                                         if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
 9474:                                             $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
 9475:                                         }
 9476:                                     }
 9477:                                 }
 9478:                             }
 9479:                         }
 9480:                     }
 9481:                 }
 9482:             }
 9483:         }
 9484:     }
 9485:     return %blockers;
 9486: }
 9487: 
 9488: sub has_comm_blocking {
 9489:     my ($priv,$symb,$uri,$ignoresymbdb,$noenccheck,$blocked,$blocks) = @_;
 9490:     my @blockers;
 9491:     return unless ($env{'request.course.id'});
 9492:     return unless ($priv eq 'bre');
 9493:     return if ($env{'request.state'} eq 'construct');
 9494:     my $courseurl = &courseid_to_courseurl($env{'request.course.id'});
 9495:     if ($env{'request.course.sec'}) {
 9496:         $courseurl .= '/'.$env{'request.course.sec'};
 9497:     }
 9498:     return if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseurl} =~/evb\&([^\:]*)/);
 9499:     my %blockinfo;
 9500:     if (ref($blocks) eq 'HASH') {
 9501:         %blockinfo = &get_commblock_resources($blocks);
 9502:     } else {
 9503:         &load_all_blockers($env{'user.name'},$env{'user.domain'});
 9504:         %blockinfo = %cachedblockers;
 9505:     }
 9506:     return unless (keys(%blockinfo) > 0);
 9507:     my (%possibles,@symbs);
 9508:     if (!$symb) {
 9509:         $symb = &symbread($uri,1,1,1,\%possibles,$ignoresymbdb,$noenccheck);
 9510:     }
 9511:     if ($symb) {
 9512:         @symbs = ($symb);
 9513:     } elsif (keys(%possibles)) { 
 9514:         @symbs = keys(%possibles);
 9515:     }
 9516:     my $noblock;
 9517:     foreach my $symb (@symbs) {
 9518:         last if ($noblock);
 9519:         my ($map,$resid,$resurl)=&decode_symb($symb);
 9520:         foreach my $block (keys(%blockinfo)) {
 9521:             if ($block =~ /^firstaccess____(.+)$/) {
 9522:                 my $item = $1;
 9523:                 unless ($blocked) {
 9524:                     if (($item eq $map) || ($item eq $symb)) {
 9525:                         $noblock = 1;
 9526:                         last;
 9527:                     }
 9528:                 }
 9529:             }
 9530:             if (ref($blockinfo{$block}) eq 'HASH') {
 9531:                 if (ref($blockinfo{$block}{'resources'}) eq 'HASH') {
 9532:                     if ($blockinfo{$block}{'resources'}{$symb}) {
 9533:                         unless (grep(/^\Q$block\E$/,@blockers)) {
 9534:                             push(@blockers,$block);
 9535:                         }
 9536:                     }
 9537:                 }
 9538:                 if (ref($blockinfo{$block}{'maps'}) eq 'HASH') {
 9539:                     if ($blockinfo{$block}{'maps'}{$map}) {
 9540:                         unless (grep(/^\Q$block\E$/,@blockers)) {
 9541:                             push(@blockers,$block);
 9542:                         }
 9543:                     }
 9544:                 }
 9545:             }
 9546:         }
 9547:     }
 9548:     unless ($noblock) { 
 9549:         return @blockers;
 9550:     }
 9551:     return;
 9552: }
 9553: }
 9554: 
 9555: sub deeplink_check {
 9556:     my ($priv,$symb,$uri) = @_;
 9557:     return unless ($env{'request.course.id'});
 9558:     return unless ($priv eq 'bre');
 9559:     return if ($env{'request.state'} eq 'construct');
 9560:     return if ($env{'request.role.adv'});
 9561:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 9562:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 9563:     my (%possibles,@symbs);
 9564:     if (!$symb) {
 9565:         $symb = &symbread($uri,1,1,1,\%possibles);
 9566:     }
 9567:     if ($symb) {
 9568:         @symbs = ($symb);
 9569:     } elsif (keys(%possibles)) {
 9570:         @symbs = keys(%possibles);
 9571:     }
 9572: 
 9573:     my ($deeplink_symb,$allow);
 9574:     if ($env{'request.deeplink.login'}) {
 9575:         $deeplink_symb = &Apache::loncommon::deeplink_login_symb($cnum,$cdom);
 9576:     }
 9577:     foreach my $symb (@symbs) {
 9578:         last if ($allow);
 9579:         my $deeplink = &EXT("resource.0.deeplink",$symb);
 9580:         if ($deeplink eq '') {
 9581:             $allow = 1;
 9582:         } else {
 9583:             my ($state,$others,$listed,$scope,$protect) = split(/,/,$deeplink);
 9584:             if ($state ne 'only') {
 9585:                 $allow = 1;
 9586:             } else {
 9587:                 my $check_deeplink_entry;
 9588:                 if ($protect ne 'none') {
 9589:                     my ($acctype,$item) = split(/:/,$protect);
 9590:                     if (($acctype eq 'ltic') && ($env{'user.linkprotector'})) {
 9591:                         if (grep(/^\Q$item\Ec$/,split(/,/,$env{'user.linkprotector'}))) {
 9592:                             $check_deeplink_entry = 1
 9593:                         }
 9594:                     } elsif (($acctype eq 'ltid') && ($env{'user.linkprotector'})) {
 9595:                         if (grep(/^\Q$item\Ed$/,split(/,/,$env{'user.linkprotector'}))) {
 9596:                             $check_deeplink_entry = 1;
 9597:                         }
 9598:                     } elsif (($acctype eq 'key') && ($env{'user.deeplinkkey'})) {
 9599:                         if (grep(/^\Q$item\E$/,split(/,/,$env{'user.deeplinkkey'}))) {
 9600:                             $check_deeplink_entry = 1;
 9601:                         }
 9602:                     }
 9603:                 }
 9604:                 if (($protect eq 'none') || ($check_deeplink_entry)) {
 9605:                     if ($scope eq 'res') {
 9606:                         if ($symb eq $deeplink_symb) {
 9607:                             $allow = 1;
 9608:                         }
 9609:                     } elsif (($scope eq 'map') || ($scope eq 'rec')) {
 9610:                         my ($map_from_symb,$map_from_login);
 9611:                         $map_from_symb = &deversion((&decode_symb($symb))[0]);
 9612:                         if ($deeplink_symb =~ /\.(page|sequence)$/) {
 9613:                             $map_from_login = &deversion((&decode_symb($deeplink_symb))[2]);
 9614:                         } else {
 9615:                             $map_from_login = &deversion((&decode_symb($deeplink_symb))[0]);
 9616:                         }
 9617:                         if (($map_from_symb) && ($map_from_login)) {
 9618:                             if ($map_from_symb eq $map_from_login) {
 9619:                                 $allow = 1;
 9620:                             } elsif ($scope eq 'rec') {
 9621:                                 my @recurseup = &get_map_hierarchy($map_from_symb,$env{'request.course.id'});
 9622:                                 if (grep(/^\Q$map_from_login\E$/,@recurseup)) {
 9623:                                     $allow = 1;
 9624:                                 }
 9625:                             }
 9626:                         }
 9627:                     }
 9628:                 }
 9629:             }
 9630:         }
 9631:     }
 9632:     return if ($allow);
 9633:     return 1;
 9634: }
 9635: 
 9636: # -------------------------------- Deversion and split uri into path an filename   
 9637: 
 9638: #
 9639: #   Removes the version from a URI and
 9640: #   splits it in to its filename and path to the filename.
 9641: #   Seems like File::Basename could have done this more clearly.
 9642: #   Parameters:
 9643: #      $uri   - input URI
 9644: #   Returns:
 9645: #     Two element list consisting of 
 9646: #     $pathname  - the URI up to and excluding the trailing /
 9647: #     $filename  - The part of the URI following the last /
 9648: #  NOTE:
 9649: #    Another realization of this is simply:
 9650: #    use File::Basename;
 9651: #    ...
 9652: #    $uri = shift;
 9653: #    $filename = basename($uri);
 9654: #    $path     = dirname($uri);
 9655: #    return ($filename, $path);
 9656: #
 9657: #     The implementation below is probably faster however.
 9658: #
 9659: sub split_uri_for_cond {
 9660:     my $uri=&deversion(&declutter(shift));
 9661:     my @uriparts=split(/\//,$uri);
 9662:     my $filename=pop(@uriparts);
 9663:     my $pathname=join('/',@uriparts);
 9664:     return ($pathname,$filename);
 9665: }
 9666: # --------------------------------------------------- Is a resource on the map?
 9667: 
 9668: sub is_on_map {
 9669:     my ($pathname,$filename) = &split_uri_for_cond(shift);
 9670:     #Trying to find the conditional for the file
 9671:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
 9672: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
 9673:     if ($match) {
 9674: 	return (1,$1);
 9675:     } else {
 9676: 	return (0,0);
 9677:     }
 9678: }
 9679: 
 9680: # --------------------------------------------------------- Get symb from alias
 9681: 
 9682: sub get_symb_from_alias {
 9683:     my $symb=shift;
 9684:     my ($map,$resid,$url)=&decode_symb($symb);
 9685: # Already is a symb
 9686:     if ($url) { return $symb; }
 9687: # Must be an alias
 9688:     my $aliassymb='';
 9689:     my %bighash;
 9690:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 9691:                             &GDBM_READER(),0640)) {
 9692:         my $rid=$bighash{'mapalias_'.$symb};
 9693: 	if ($rid) {
 9694: 	    my ($mapid,$resid)=split(/\./,$rid);
 9695: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
 9696: 				    $resid,$bighash{'src_'.$rid});
 9697: 	}
 9698:         untie %bighash;
 9699:     }
 9700:     return $aliassymb;
 9701: }
 9702: 
 9703: # ----------------------------------------------------------------- Define Role
 9704: 
 9705: sub definerole {
 9706:   if (allowed('mcr','/')) {
 9707:     my ($rolename,$sysrole,$domrole,$courole,$uname,$udom)=@_;
 9708:     foreach my $role (split(':',$sysrole)) {
 9709: 	my ($crole,$cqual)=split(/\&/,$role);
 9710:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
 9711:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
 9712: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 9713:                return "refused:s:$crole&$cqual"; 
 9714:             }
 9715:         }
 9716:     }
 9717:     foreach my $role (split(':',$domrole)) {
 9718: 	my ($crole,$cqual)=split(/\&/,$role);
 9719:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
 9720:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
 9721: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
 9722:                return "refused:d:$crole&$cqual"; 
 9723:             }
 9724:         }
 9725:     }
 9726:     foreach my $role (split(':',$courole)) {
 9727: 	my ($crole,$cqual)=split(/\&/,$role);
 9728:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
 9729:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
 9730: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 9731:                return "refused:c:$crole&$cqual"; 
 9732:             }
 9733:         }
 9734:     }
 9735:     my $uhome;
 9736:     if (($uname ne '') && ($udom ne '')) {
 9737:         $uhome = &homeserver($uname,$udom);
 9738:         return $uhome if ($uhome eq 'no_host');
 9739:     } else {
 9740:         $uname = $env{'user.name'};
 9741:         $udom = $env{'user.domain'};
 9742:         $uhome = $env{'user.home'};
 9743:     }
 9744:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
 9745:                 "$udom:$uname:rolesdef_$rolename=".
 9746:                 escape($sysrole.'_'.$domrole.'_'.$courole);
 9747:     return reply($command,$uhome);
 9748:   } else {
 9749:     return 'refused';
 9750:   }
 9751: }
 9752: 
 9753: # ---------------- Make a metadata query against the network of library servers
 9754: 
 9755: sub metadata_query {
 9756:     my ($query,$custom,$customshow,$server_array,$domains_hash)=@_;
 9757:     my %rhash;
 9758:     my %libserv = &all_library();
 9759:     my @server_list = (defined($server_array) ? @$server_array
 9760:                                               : keys(%libserv) );
 9761:     for my $server (@server_list) {
 9762:         my $domains = ''; 
 9763:         if (ref($domains_hash) eq 'HASH') {
 9764:             $domains = $domains_hash->{$server}; 
 9765:         }
 9766: 	unless ($custom or $customshow) {
 9767: 	    my $reply=&reply("querysend:".&escape($query).':::'.&escape($domains),$server);
 9768: 	    $rhash{$server}=$reply;
 9769: 	}
 9770: 	else {
 9771: 	    my $reply=&reply("querysend:".&escape($query).':'.
 9772: 			     &escape($custom).':'.&escape($customshow).':'.&escape($domains),
 9773: 			     $server);
 9774: 	    $rhash{$server}=$reply;
 9775: 	}
 9776:     }
 9777:     return \%rhash;
 9778: }
 9779: 
 9780: # ----------------------------------------- Send log queries and wait for reply
 9781: 
 9782: sub log_query {
 9783:     my ($uname,$udom,$query,%filters)=@_;
 9784:     my $uhome=&homeserver($uname,$udom);
 9785:     if ($uhome eq 'no_host') { return 'error: no_host'; }
 9786:     my $uhost=&hostname($uhome);
 9787:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
 9788:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
 9789:                        $uhome);
 9790:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
 9791:     return get_query_reply($queryid);
 9792: }
 9793: 
 9794: # -------------------------- Update MySQL table for portfolio file
 9795: 
 9796: sub update_portfolio_table {
 9797:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
 9798:     if ($group ne '') {
 9799:         $file_name =~s /^\Q$group\E//;
 9800:     }
 9801:     my $homeserver = &homeserver($uname,$udom);
 9802:     my $queryid=
 9803:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
 9804:                ':'.&escape($file_name).':'.$action,$homeserver);
 9805:     my $reply = &get_query_reply($queryid);
 9806:     return $reply;
 9807: }
 9808: 
 9809: # -------------------------- Update MySQL allusers table
 9810: 
 9811: sub update_allusers_table {
 9812:     my ($uname,$udom,$names) = @_;
 9813:     my $homeserver = &homeserver($uname,$udom);
 9814:     my $queryid=
 9815:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
 9816:                'lastname='.&escape($names->{'lastname'}).'%%'.
 9817:                'firstname='.&escape($names->{'firstname'}).'%%'.
 9818:                'middlename='.&escape($names->{'middlename'}).'%%'.
 9819:                'generation='.&escape($names->{'generation'}).'%%'.
 9820:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
 9821:                'id='.&escape($names->{'id'}),$homeserver);
 9822:     return;
 9823: }
 9824: 
 9825: # ------- Request retrieval of institutional classlists for course(s)
 9826: 
 9827: sub fetch_enrollment_query {
 9828:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
 9829:     my ($homeserver,$sleep,$loopmax);
 9830:     my $maxtries = 1;
 9831:     if ($context eq 'automated') {
 9832:         $homeserver = $perlvar{'lonHostID'};
 9833:         $sleep = 2;
 9834:         $loopmax = 100;
 9835:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
 9836:     } else {
 9837:         $homeserver = &homeserver($cnum,$dom);
 9838:     }
 9839:     my $host=&hostname($homeserver);
 9840:     my $cmd = '';
 9841:     foreach my $affiliate (keys(%{$affiliatesref})) {
 9842:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
 9843:     }
 9844:     $cmd =~ s/%%$//;
 9845:     $cmd = &escape($cmd);
 9846:     my $query = 'fetchenrollment';
 9847:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
 9848:     unless ($queryid=~/^\Q$host\E\_/) { 
 9849:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
 9850:         return 'error: '.$queryid;
 9851:     }
 9852:     my $reply = &get_query_reply($queryid,$sleep,$loopmax);
 9853:     my $tries = 1;
 9854:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 9855:         $reply = &get_query_reply($queryid,$sleep,$loopmax);
 9856:         $tries ++;
 9857:     }
 9858:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 9859:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 9860:     } else {
 9861:         my @responses = split(/:/,$reply);
 9862:         if (grep { $_ eq $homeserver } &current_machine_ids()) {
 9863:             foreach my $line (@responses) {
 9864:                 my ($key,$value) = split(/=/,$line,2);
 9865:                 $$replyref{$key} = $value;
 9866:             }
 9867:         } else {
 9868:             my $pathname = LONCAPA::tempdir();
 9869:             foreach my $line (@responses) {
 9870:                 my ($key,$value) = split(/=/,$line);
 9871:                 $$replyref{$key} = $value;
 9872:                 if ($value > 0) {
 9873:                     foreach my $item (@{$$affiliatesref{$key}}) {
 9874:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
 9875:                         my $destname = $pathname.'/'.$filename;
 9876:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
 9877:                         if ($xml_classlist =~ /^error/) {
 9878:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
 9879:                         } else {
 9880:                             if ( open(FILE,">",$destname) ) {
 9881:                                 print FILE &unescape($xml_classlist);
 9882:                                 close(FILE);
 9883:                             } else {
 9884:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
 9885:                             }
 9886:                         }
 9887:                     }
 9888:                 }
 9889:             }
 9890:         }
 9891:         return 'ok';
 9892:     }
 9893:     return 'error';
 9894: }
 9895: 
 9896: sub get_query_reply {
 9897:     my ($queryid,$sleep,$loopmax) = @_;
 9898:     if (($sleep eq '') || ($sleep !~ /^\d+\.?\d*$/)) {
 9899:         $sleep = 0.2;
 9900:     }
 9901:     if (($loopmax eq '') || ($loopmax =~ /\D/)) {
 9902:         $loopmax = 100;
 9903:     }
 9904:     my $replyfile=LONCAPA::tempdir().$queryid;
 9905:     my $reply='';
 9906:     for (1..$loopmax) {
 9907: 	sleep($sleep);
 9908:         if (-e $replyfile.'.end') {
 9909: 	    if (open(my $fh,"<",$replyfile)) {
 9910: 		$reply = join('',<$fh>);
 9911: 		close($fh);
 9912: 	   } else { return 'error: reply_file_error'; }
 9913:            return &unescape($reply);
 9914: 	}
 9915:     }
 9916:     return 'timeout:'.$queryid;
 9917: }
 9918: 
 9919: sub courselog_query {
 9920: #
 9921: # possible filters:
 9922: # url: url or symb
 9923: # username
 9924: # domain
 9925: # action: view, submit, grade
 9926: # start: timestamp
 9927: # end: timestamp
 9928: #
 9929:     my (%filters)=@_;
 9930:     unless ($env{'request.course.id'}) { return 'no_course'; }
 9931:     if ($filters{'url'}) {
 9932: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
 9933:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
 9934:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
 9935:     }
 9936:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 9937:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 9938:     return &log_query($cname,$cdom,'courselog',%filters);
 9939: }
 9940: 
 9941: sub userlog_query {
 9942: #
 9943: # possible filters:
 9944: # action: log check role
 9945: # start: timestamp
 9946: # end: timestamp
 9947: #
 9948:     my ($uname,$udom,%filters)=@_;
 9949:     return &log_query($uname,$udom,'userlog',%filters);
 9950: }
 9951: 
 9952: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
 9953: 
 9954: sub auto_run {
 9955:     my ($cnum,$cdom) = @_;
 9956:     my $response = 0;
 9957:     my $settings;
 9958:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
 9959:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
 9960:         $settings = $domconfig{'autoenroll'};
 9961:         if ($settings->{'run'} eq '1') {
 9962:             $response = 1;
 9963:         }
 9964:     } else {
 9965:         my $homeserver;
 9966:         if (&is_course($cdom,$cnum)) {
 9967:             $homeserver = &homeserver($cnum,$cdom);
 9968:         } else {
 9969:             $homeserver = &domain($cdom,'primary');
 9970:         }
 9971:         if ($homeserver ne 'no_host') {
 9972:             $response = &reply('autorun:'.$cdom,$homeserver);
 9973:         }
 9974:     }
 9975:     return $response;
 9976: }
 9977: 
 9978: sub auto_get_sections {
 9979:     my ($cnum,$cdom,$inst_coursecode) = @_;
 9980:     my $homeserver;
 9981:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) { 
 9982:         $homeserver = &homeserver($cnum,$cdom);
 9983:     }
 9984:     if (!defined($homeserver)) { 
 9985:         if ($cdom =~ /^$match_domain$/) {
 9986:             $homeserver = &domain($cdom,'primary');
 9987:         }
 9988:     }
 9989:     my @secs;
 9990:     if (defined($homeserver)) {
 9991:         my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
 9992:         unless ($response eq 'refused') {
 9993:             @secs = split(/:/,$response);
 9994:         }
 9995:     }
 9996:     return @secs;
 9997: }
 9998: 
 9999: sub auto_new_course {
10000:     my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
10001:     my $homeserver = &homeserver($cnum,$cdom);
10002:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
10003:     return $response;
10004: }
10005: 
10006: sub auto_validate_courseID {
10007:     my ($cnum,$cdom,$inst_course_id) = @_;
10008:     my $homeserver = &homeserver($cnum,$cdom);
10009:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
10010:     return $response;
10011: }
10012: 
10013: sub auto_validate_instcode {
10014:     my ($cnum,$cdom,$instcode,$owner) = @_;
10015:     my ($homeserver,$response);
10016:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
10017:         $homeserver = &homeserver($cnum,$cdom);
10018:     }
10019:     if (!defined($homeserver)) {
10020:         if ($cdom =~ /^$match_domain$/) {
10021:             $homeserver = &domain($cdom,'primary');
10022:         }
10023:     }
10024:     $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
10025:                         &escape($instcode).':'.&escape($owner),$homeserver));
10026:     my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
10027:     return ($outcome,$description,$defaultcredits);
10028: }
10029: 
10030: sub auto_validate_inst_crosslist {
10031:     my ($cnum,$cdom,$instcode,$inst_xlist,$coowner) = @_;
10032:     my ($homeserver,$response);
10033:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
10034:         $homeserver = &homeserver($cnum,$cdom);
10035:     }
10036:     if (!defined($homeserver)) {
10037:         if ($cdom =~ /^$match_domain$/) {
10038:             $homeserver = &domain($cdom,'primary');
10039:         }
10040:     }
10041:     unless (($homeserver eq '') || ($homeserver eq 'no_host')) {
10042:         $response=&reply('autovalidateinstcrosslist:'.$cdom.':'.
10043:                          &escape($instcode).':'.&escape($inst_xlist).':'.
10044:                          &escape($coowner),$homeserver);
10045:     }
10046:     return $response;
10047: }
10048: 
10049: sub auto_create_password {
10050:     my ($cnum,$cdom,$authparam,$udom) = @_;
10051:     my ($homeserver,$response);
10052:     my $create_passwd = 0;
10053:     my $authchk = '';
10054:     if ($udom =~ /^$match_domain$/) {
10055:         $homeserver = &domain($udom,'primary');
10056:     }
10057:     if ($homeserver eq '') {
10058:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
10059:             $homeserver = &homeserver($cnum,$cdom);
10060:         }
10061:     }
10062:     if ($homeserver eq '') {
10063:         $authchk = 'nodomain';
10064:     } else {
10065:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
10066:         if ($response eq 'refused') {
10067:             $authchk = 'refused';
10068:         } else {
10069:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
10070:         }
10071:     }
10072:     return ($authparam,$create_passwd,$authchk);
10073: }
10074: 
10075: sub auto_photo_permission {
10076:     my ($cnum,$cdom,$students) = @_;
10077:     my $homeserver = &homeserver($cnum,$cdom);
10078:     my ($outcome,$perm_reqd,$conditions) = 
10079: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
10080:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
10081: 	return (undef,undef);
10082:     }
10083:     return ($outcome,$perm_reqd,$conditions);
10084: }
10085: 
10086: sub auto_checkphotos {
10087:     my ($uname,$udom,$pid) = @_;
10088:     my $homeserver = &homeserver($uname,$udom);
10089:     my ($result,$resulttype);
10090:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
10091: 				   &escape($uname).':'.&escape($pid),
10092: 				   $homeserver));
10093:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
10094: 	return (undef,undef);
10095:     }
10096:     if ($outcome) {
10097:         ($result,$resulttype) = split(/:/,$outcome);
10098:     } 
10099:     return ($result,$resulttype);
10100: }
10101: 
10102: sub auto_photochoice {
10103:     my ($cnum,$cdom) = @_;
10104:     my $homeserver = &homeserver($cnum,$cdom);
10105:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
10106: 						       &escape($cdom),
10107: 						       $homeserver)));
10108:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
10109: 	return (undef,undef);
10110:     }
10111:     return ($update,$comment);
10112: }
10113: 
10114: sub auto_photoupdate {
10115:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
10116:     my $homeserver = &homeserver($cnum,$dom);
10117:     my $host=&hostname($homeserver);
10118:     my $cmd = '';
10119:     my $maxtries = 1;
10120:     foreach my $affiliate (keys(%{$affiliatesref})) {
10121:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
10122:     }
10123:     $cmd =~ s/%%$//;
10124:     $cmd = &escape($cmd);
10125:     my $query = 'institutionalphotos';
10126:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
10127:     unless ($queryid=~/^\Q$host\E\_/) {
10128:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
10129:         return 'error: '.$queryid;
10130:     }
10131:     my $reply = &get_query_reply($queryid);
10132:     my $tries = 1;
10133:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
10134:         $reply = &get_query_reply($queryid);
10135:         $tries ++;
10136:     }
10137:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
10138:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
10139:     } else {
10140:         my @responses = split(/:/,$reply);
10141:         my $outcome = shift(@responses); 
10142:         foreach my $item (@responses) {
10143:             my ($key,$value) = split(/=/,$item);
10144:             $$photo{$key} = $value;
10145:         }
10146:         return $outcome;
10147:     }
10148:     return 'error';
10149: }
10150: 
10151: sub auto_instcode_format {
10152:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
10153: 	$cat_order) = @_;
10154:     my $courses = '';
10155:     my @homeservers;
10156:     if ($caller eq 'global') {
10157: 	my %servers = &get_servers($codedom,'library');
10158: 	foreach my $tryserver (keys(%servers)) {
10159: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
10160: 		push(@homeservers,$tryserver);
10161: 	    }
10162:         }
10163:     } elsif ($caller eq 'requests') {
10164:         if ($codedom =~ /^$match_domain$/) {
10165:             my $chome = &domain($codedom,'primary');
10166:             unless ($chome eq 'no_host') {
10167:                 push(@homeservers,$chome);
10168:             }
10169:         }
10170:     } else {
10171:         push(@homeservers,&homeserver($caller,$codedom));
10172:     }
10173:     foreach my $code (keys(%{$instcodes})) {
10174:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
10175:     }
10176:     chop($courses);
10177:     my $ok_response = 0;
10178:     my $response;
10179:     while (@homeservers > 0 && $ok_response == 0) {
10180:         my $server = shift(@homeservers); 
10181:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
10182:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
10183:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
10184: 		split(/:/,$response);
10185:             %{$codes} = (%{$codes},&str2hash($codes_str));
10186:             push(@{$codetitles},&str2array($codetitles_str));
10187:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
10188:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
10189:             $ok_response = 1;
10190:         }
10191:     }
10192:     if ($ok_response) {
10193:         return 'ok';
10194:     } else {
10195:         return $response;
10196:     }
10197: }
10198: 
10199: sub auto_instcode_defaults {
10200:     my ($domain,$returnhash,$code_order) = @_;
10201:     my @homeservers;
10202: 
10203:     my %servers = &get_servers($domain,'library');
10204:     foreach my $tryserver (keys(%servers)) {
10205: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
10206: 	    push(@homeservers,$tryserver);
10207: 	}
10208:     }
10209: 
10210:     my $response;
10211:     foreach my $server (@homeservers) {
10212:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
10213:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
10214: 	
10215: 	foreach my $pair (split(/\&/,$response)) {
10216: 	    my ($name,$value)=split(/\=/,$pair);
10217: 	    if ($name eq 'code_order') {
10218: 		@{$code_order} = split(/\&/,&unescape($value));
10219: 	    } else {
10220: 		$returnhash->{&unescape($name)}=&unescape($value);
10221: 	    }
10222: 	}
10223: 	return 'ok';
10224:     }
10225: 
10226:     return $response;
10227: }
10228: 
10229: sub auto_possible_instcodes {
10230:     my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
10231:     unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') && 
10232:             (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
10233:         return;
10234:     }
10235:     my (@homeservers,$uhome);
10236:     if (defined(&domain($domain,'primary'))) {
10237:         $uhome=&domain($domain,'primary');
10238:         push(@homeservers,&domain($domain,'primary'));
10239:     } else {
10240:         my %servers = &get_servers($domain,'library');
10241:         foreach my $tryserver (keys(%servers)) {
10242:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
10243:                 push(@homeservers,$tryserver);
10244:             }
10245:         }
10246:     }
10247:     my $response;
10248:     foreach my $server (@homeservers) {
10249:         $response=&reply('autopossibleinstcodes:'.$domain,$server);
10250:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
10251:         my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) = 
10252:             split(':',$response);
10253:         @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
10254:         @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
10255:         foreach my $item (split('&',$cat_title)) {   
10256:             my ($name,$value)=split('=',$item);
10257:             $cat_titles->{&unescape($name)}=&thaw_unescape($value);
10258:         }
10259:         foreach my $item (split('&',$cat_order)) {
10260:             my ($name,$value)=split('=',$item);
10261:             $cat_orders->{&unescape($name)}=&thaw_unescape($value);
10262:         }
10263:         return 'ok';
10264:     }
10265:     return $response;
10266: }
10267: 
10268: sub auto_courserequest_checks {
10269:     my ($dom) = @_;
10270:     my ($homeserver,%validations);
10271:     if ($dom =~ /^$match_domain$/) {
10272:         $homeserver = &domain($dom,'primary');
10273:     }
10274:     unless ($homeserver eq 'no_host') {
10275:         my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
10276:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
10277:             my @items = split(/&/,$response);
10278:             foreach my $item (@items) {
10279:                 my ($key,$value) = split('=',$item);
10280:                 $validations{&unescape($key)} = &thaw_unescape($value);
10281:             }
10282:         }
10283:     }
10284:     return %validations; 
10285: }
10286: 
10287: sub auto_courserequest_validation {
10288:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist,$custominfo) = @_;
10289:     my ($homeserver,$response);
10290:     if ($dom =~ /^$match_domain$/) {
10291:         $homeserver = &domain($dom,'primary');
10292:     }
10293:     unless ($homeserver eq 'no_host') {
10294:         my $customdata;
10295:         if (ref($custominfo) eq 'HASH') {
10296:             $customdata = &freeze_escape($custominfo);
10297:         }
10298:         $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
10299:                                     ':'.&escape($crstype).':'.&escape($inststatuslist).
10300:                                     ':'.&escape($instcode).':'.&escape($instseclist).':'.
10301:                                     $customdata,$homeserver));
10302:     }
10303:     return $response;
10304: }
10305: 
10306: sub auto_validate_class_sec {
10307:     my ($cdom,$cnum,$owners,$inst_class) = @_;
10308:     my $homeserver = &homeserver($cnum,$cdom);
10309:     my $ownerlist;
10310:     if (ref($owners) eq 'ARRAY') {
10311:         $ownerlist = join(',',@{$owners});
10312:     } else {
10313:         $ownerlist = $owners;
10314:     }
10315:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
10316:                         &escape($ownerlist).':'.$cdom,$homeserver);
10317:     return $response;
10318: }
10319: 
10320: sub auto_instsec_reformat {
10321:     my ($cdom,$action,$instsecref) = @_;
10322:     return unless(($action eq 'clutter') || ($action eq 'declutter'));
10323:     my @homeservers;
10324:     if (defined(&domain($cdom,'primary'))) {
10325:         push(@homeservers,&domain($cdom,'primary'));
10326:     } else {
10327:         my %servers = &get_servers($cdom,'library');
10328:         foreach my $tryserver (keys(%servers)) {
10329:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
10330:                 push(@homeservers,$tryserver);
10331:             }
10332:         }
10333:     }
10334:     my $response;
10335:     my %reformatted = %{$instsecref};
10336:     foreach my $server (@homeservers) {
10337:         if (ref($instsecref) eq 'HASH') {
10338:             my $info = &freeze_escape($instsecref);
10339:             my $response=&reply('autoinstsecreformat:'.$cdom.':'.
10340:                                 $action.':'.$info,$server);
10341:             next if ($response =~ /(con_lost|error|no_such_host|refused|unknown_command)/);
10342:             my @items = split(/&/,$response);
10343:             foreach my $item (@items) {
10344:                 my ($key,$value) = split(/=/,$item);
10345:                 $reformatted{&unescape($key)} = &thaw_unescape($value);
10346:             }
10347:         }
10348:     }
10349:     return %reformatted;
10350: }
10351: 
10352: sub auto_validate_instclasses {
10353:     my ($cdom,$cnum,$owners,$classesref) = @_;
10354:     my ($homeserver,%validations);
10355:     $homeserver = &homeserver($cnum,$cdom);
10356:     unless ($homeserver eq 'no_host') {
10357:         my $ownerlist;
10358:         if (ref($owners) eq 'ARRAY') {
10359:             $ownerlist = join(',',@{$owners});
10360:         } else {
10361:             $ownerlist = $owners;
10362:         }
10363:         if (ref($classesref) eq 'HASH') {
10364:             my $classes = &freeze_escape($classesref);
10365:             my $response=&reply('autovalidateinstclasses:'.&escape($ownerlist).
10366:                                 ':'.$cdom.':'.$classes,$homeserver);
10367:             unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
10368:                 my @items = split(/&/,$response);
10369:                 foreach my $item (@items) {
10370:                     my ($key,$value) = split('=',$item);
10371:                     $validations{&unescape($key)} = &thaw_unescape($value);
10372:                 }
10373:             }
10374:         }
10375:     }
10376:     return %validations;
10377: }
10378: 
10379: sub auto_crsreq_update {
10380:     my ($cdom,$cnum,$crstype,$action,$ownername,$ownerdomain,$fullname,$title,
10381:         $code,$accessstart,$accessend,$inbound) = @_;
10382:     my ($homeserver,%crsreqresponse);
10383:     if ($cdom =~ /^$match_domain$/) {
10384:         $homeserver = &domain($cdom,'primary');
10385:     }
10386:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
10387:         my $info;
10388:         if (ref($inbound) eq 'HASH') {
10389:             $info = &freeze_escape($inbound);
10390:         }
10391:         my $response=&reply('autocrsrequpdate:'.$cdom.':'.$cnum.':'.&escape($crstype).
10392:                             ':'.&escape($action).':'.&escape($ownername).':'.
10393:                             &escape($ownerdomain).':'.&escape($fullname).':'.
10394:                             &escape($title).':'.&escape($code).':'.
10395:                             &escape($accessstart).':'.&escape($accessend).':'.$info,
10396:                             $homeserver);
10397:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
10398:             my @items = split(/&/,$response);
10399:             foreach my $item (@items) {
10400:                 my ($key,$value) = split('=',$item);
10401:                 $crsreqresponse{&unescape($key)} = &thaw_unescape($value);
10402:             }
10403:         }
10404:     }
10405:     return \%crsreqresponse;
10406: }
10407: 
10408: sub auto_export_grades {
10409:     my ($cdom,$cnum,$inforef,$gradesref) = @_;
10410:     my ($homeserver,%exportresponse);
10411:     if ($cdom =~ /^$match_domain$/) {
10412:         $homeserver = &domain($cdom,'primary');
10413:     }
10414:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
10415:         my $info;
10416:         if (ref($inforef) eq 'HASH') {
10417:             $info = &freeze_escape($inforef);
10418:         }
10419:         if (ref($gradesref) eq 'HASH') {
10420:             my $grades = &freeze_escape($gradesref);
10421:             my $response=&reply('encrypt:autoexportgrades:'.$cdom.':'.$cnum.':'.
10422:                                 $info.':'.$grades,$homeserver);
10423:             unless ($response =~ /(con_lost|error|no_such_host|refused|unknown_command)/) {
10424:                 my @items = split(/&/,$response);
10425:                 foreach my $item (@items) {
10426:                     my ($key,$value) = split('=',$item);
10427:                     $exportresponse{&unescape($key)} = &thaw_unescape($value);
10428:                 }
10429:             }
10430:         }
10431:     }
10432:     return \%exportresponse;
10433: }
10434: 
10435: sub check_instcode_cloning {
10436:     my ($codedefaults,$code_order,$cloner,$clonefromcode,$clonetocode) = @_;
10437:     unless ((ref($codedefaults) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
10438:         return;
10439:     }
10440:     my $canclone;
10441:     if (@{$code_order} > 0) {
10442:         my $instcoderegexp ='^';
10443:         my @clonecodes = split(/\&/,$cloner);
10444:         foreach my $item (@{$code_order}) {
10445:             if (grep(/^\Q$item\E=/,@clonecodes)) {
10446:                 foreach my $pair (@clonecodes) {
10447:                     my ($key,$val) = split(/\=/,$pair,2);
10448:                     $val = &unescape($val);
10449:                     if ($key eq $item) {
10450:                         $instcoderegexp .= '('.$val.')';
10451:                         last;
10452:                     }
10453:                 }
10454:             } else {
10455:                 $instcoderegexp .= $codedefaults->{$item};
10456:             }
10457:         }
10458:         $instcoderegexp .= '$';
10459:         my (@from,@to);
10460:         eval {
10461:                (@from) = ($clonefromcode =~ /$instcoderegexp/);
10462:                (@to) = ($clonetocode =~ /$instcoderegexp/);
10463:         };
10464:         if ((@from > 0) && (@to > 0)) {
10465:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
10466:             if (!@diffs) {
10467:                 $canclone = 1;
10468:             }
10469:         }
10470:     }
10471:     return $canclone;
10472: }
10473: 
10474: sub default_instcode_cloning {
10475:     my ($clonedom,$domdefclone,$clonefromcode,$clonetocode,$codedefaultsref,$codeorderref) = @_;
10476:     my (%codedefaults,@code_order,$canclone);
10477:     if ((ref($codedefaultsref) eq 'HASH') && (ref($codeorderref) eq 'ARRAY')) {
10478:         %codedefaults = %{$codedefaultsref};
10479:         @code_order = @{$codeorderref};
10480:     } elsif ($clonedom) {
10481:         &auto_instcode_defaults($clonedom,\%codedefaults,\@code_order);
10482:     }
10483:     if (($domdefclone) && (@code_order)) {
10484:         my @clonecodes = split(/\+/,$domdefclone);
10485:         my $instcoderegexp ='^';
10486:         foreach my $item (@code_order) {
10487:             if (grep(/^\Q$item\E$/,@clonecodes)) {
10488:                 $instcoderegexp .= '('.$codedefaults{$item}.')';
10489:             } else {
10490:                 $instcoderegexp .= $codedefaults{$item};
10491:             }
10492:         }
10493:         $instcoderegexp .= '$';
10494:         my (@from,@to);
10495:         eval {
10496:             (@from) = ($clonefromcode =~ /$instcoderegexp/);
10497:             (@to) = ($clonetocode =~ /$instcoderegexp/);
10498:         };
10499:         if ((@from > 0) && (@to > 0)) {
10500:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
10501:             if (!@diffs) {
10502:                 $canclone = 1;
10503:             }
10504:         }
10505:     }
10506:     return $canclone;
10507: }
10508: 
10509: # ------------------------------------------------------- Course Group routines
10510: 
10511: sub get_coursegroups {
10512:     my ($cdom,$cnum,$group,$namespace) = @_;
10513:     return(&dump($namespace,$cdom,$cnum,$group));
10514: }
10515: 
10516: sub modify_coursegroup {
10517:     my ($cdom,$cnum,$groupsettings) = @_;
10518:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
10519: }
10520: 
10521: sub toggle_coursegroup_status {
10522:     my ($cdom,$cnum,$group,$action) = @_;
10523:     my ($from_namespace,$to_namespace);
10524:     if ($action eq 'delete') {
10525:         $from_namespace = 'coursegroups';
10526:         $to_namespace = 'deleted_groups';
10527:     } else {
10528:         $from_namespace = 'deleted_groups';
10529:         $to_namespace = 'coursegroups';
10530:     }
10531:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
10532:     if (my $tmp = &error(%curr_group)) {
10533:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
10534:         return ('read error',$tmp);
10535:     } else {
10536:         my %savedsettings = %curr_group; 
10537:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
10538:         my $deloutcome;
10539:         if ($result eq 'ok') {
10540:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
10541:         } else {
10542:             return ('write error',$result);
10543:         }
10544:         if ($deloutcome eq 'ok') {
10545:             return 'ok';
10546:         } else {
10547:             return ('delete error',$deloutcome);
10548:         }
10549:     }
10550: }
10551: 
10552: sub modify_group_roles {
10553:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context,
10554:         $othdomby,$requester) = @_;
10555:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
10556:     my $role = 'gr/'.&escape($userprivs);
10557:     my ($uname,$udom) = split(/:/,$user);
10558:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context,
10559:                              $othdomby,$requester);
10560:     if ($result eq 'ok') {
10561:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
10562:     }
10563:     return $result;
10564: }
10565: 
10566: sub modify_coursegroup_membership {
10567:     my ($cdom,$cnum,$membership) = @_;
10568:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
10569:     return $result;
10570: }
10571: 
10572: sub get_active_groups {
10573:     my ($udom,$uname,$cdom,$cnum) = @_;
10574:     my $now = time;
10575:     my %groups = ();
10576:     foreach my $key (keys(%env)) {
10577:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
10578:             my ($start,$end) = split(/\./,$env{$key});
10579:             if (($end!=0) && ($end<$now)) { next; }
10580:             if (($start!=0) && ($start>$now)) { next; }
10581:             if ($1 eq $cdom && $2 eq $cnum) {
10582:                 $groups{$3} = $env{$key} ;
10583:             }
10584:         }
10585:     }
10586:     return %groups;
10587: }
10588: 
10589: sub get_group_membership {
10590:     my ($cdom,$cnum,$group) = @_;
10591:     return(&dump('groupmembership',$cdom,$cnum,$group));
10592: }
10593: 
10594: sub get_users_groups {
10595:     my ($udom,$uname,$courseid) = @_;
10596:     my @usersgroups;
10597:     my $cachetime=1800;
10598: 
10599:     my $hashid="$udom:$uname:$courseid";
10600:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
10601:     if (defined($cached)) {
10602:         @usersgroups = split(/:/,$grouplist);
10603:     } else {  
10604:         $grouplist = '';
10605:         my $courseurl = &courseid_to_courseurl($courseid);
10606:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
10607:         my $access_end = $env{'course.'.$courseid.
10608:                               '.default_enrollment_end_date'};
10609:         my $now = time;
10610:         foreach my $key (keys(%roleshash)) {
10611:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
10612:                 my $group = $1;
10613:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
10614:                     my $start = $2;
10615:                     my $end = $1;
10616:                     if ($start == -1) { next; } # deleted from group
10617:                     if (($start!=0) && ($start>$now)) { next; }
10618:                     if (($end!=0) && ($end<$now)) {
10619:                         if ($access_end && $access_end < $now) {
10620:                             if ($access_end - $end < 86400) {
10621:                                 push(@usersgroups,$group);
10622:                             }
10623:                         }
10624:                         next;
10625:                     }
10626:                     push(@usersgroups,$group);
10627:                 }
10628:             }
10629:         }
10630:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
10631:         $grouplist = join(':',@usersgroups);
10632:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
10633:     }
10634:     return @usersgroups;
10635: }
10636: 
10637: sub devalidate_getgroups_cache {
10638:     my ($udom,$uname,$cdom,$cnum)=@_;
10639:     my $courseid = $cdom.'_'.$cnum;
10640: 
10641:     my $hashid="$udom:$uname:$courseid";
10642:     &devalidate_cache_new('getgroups',$hashid);
10643: }
10644: 
10645: # ------------------------------------------------------------------ Plain Text
10646: 
10647: sub plaintext {
10648:     my ($short,$type,$cid,$forcedefault) = @_;
10649:     if ($short =~ m{^cr/}) {
10650: 	return (split('/',$short))[-1];
10651:     }
10652:     if (!defined($cid)) {
10653:         $cid = $env{'request.course.id'};
10654:     }
10655:     my %rolenames = (
10656:                       Course    => 'std',
10657:                       Community => 'alt1',
10658:                       Placement => 'std',
10659:                     );
10660:     if ($cid ne '') {
10661:         if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
10662:             unless ($forcedefault) {
10663:                 my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
10664:                 &Apache::lonlocal::mt_escape(\$roletext);
10665:                 return &Apache::lonlocal::mt($roletext);
10666:             }
10667:         }
10668:     }
10669:     if ((defined($type)) && (defined($rolenames{$type})) &&
10670:         (defined($rolenames{$type})) && 
10671:         (defined($prp{$short}{$rolenames{$type}}))) {
10672:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
10673:     } elsif ($cid ne '') {
10674:         my $crstype = $env{'course.'.$cid.'.type'};
10675:         if (($crstype ne '') && (defined($rolenames{$crstype})) &&
10676:             (defined($prp{$short}{$rolenames{$crstype}}))) {
10677:             return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
10678:         }
10679:     }
10680:     return &Apache::lonlocal::mt($prp{$short}{'std'});
10681: }
10682: 
10683: # ----------------------------------------------------------------- Assign Role
10684: 
10685: sub assignrole {
10686:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
10687:         $context,$othdomby,$requester,$reqsec,$reqrole)=@_;
10688:     my ($mrole,$rolelogcontext);
10689:     if ($role =~ /^cr\//) {
10690:         my $cwosec=$url;
10691:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
10692:         if ((!&allowed('ccr',$cwosec)) && (!&allowed('ccr',$udom))) {
10693:             my $refused = 1;
10694:             if ($context eq 'requestcourses') {
10695:                 if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
10696:                     if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
10697:                         if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
10698:                             my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
10699:                             my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
10700:                             if ($crsenv{'internal.courseowner'} eq
10701:                                 $env{'user.name'}.':'.$env{'user.domain'}) {
10702:                                 $refused = '';
10703:                             }
10704:                         }
10705:                     }
10706:                 }
10707:             } elsif (($context eq 'course') && ($othdomby eq 'othdombyuser')) {
10708:                 my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
10709:                 my ($sec) = ($url =~ m{^/\Q$cwosec\E/(.*)$});
10710:                 my $key = "$uname:$udom:$role:$sec";
10711:                 my %queuedrolereq = &Apache::lonnet::get('nohist_othdomqueued',[$key],$cdom,$cnum);
10712:                 if ((exists($queuedrolereq{$key})) && (ref($queuedrolereq{$key}) eq 'HASH')) {
10713:                     if (($queuedrolereq{$key}{'adj'} eq 'user') && ($queuedrolereq{$key}{'requester'} eq $requester)) {
10714:                         $refused = '';
10715:                     }
10716:                 }
10717:             }
10718:             if ($refused) {
10719:                 &logthis('Refused custom assignrole: '.
10720:                          $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
10721:                          ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
10722:                 return 'refused';
10723:             }
10724:         }
10725:         $mrole='cr';
10726:     } elsif ($role =~ /^gr\//) {
10727:         my $cwogrp=$url;
10728:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
10729:         if (!&allowed('mdg',$cwogrp)) {
10730:             my $refused = 1;
10731:             if (($refused) && ($othdomby eq 'othdombyuser') && ($requester ne '') && ($reqrole ne '')) {
10732:                 my ($cdom,$cnum) = ($cwogrp =~ m{^/?($match_domain)/($match_courseid)$});
10733:                 my $key = "$uname:$udom:$reqrole:$reqsec";
10734:                 my %queuedrolereq = &Apache::lonnet::get('nohist_othdomqueued',[$key],$cdom,$cnum);
10735:                 if ((exists($queuedrolereq{$key})) && (ref($queuedrolereq{$key}) eq 'HASH')) {
10736:                     if (($queuedrolereq{$key}{'adj'} eq 'user') && ($queuedrolereq{$key}{'requester'} eq $requester)) {
10737:                         $refused = '';
10738:                     }
10739:                 }
10740:             }
10741:             if ($refused) {
10742:                 &logthis('Refused group assignrole: '.
10743:                          $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
10744:                          $env{'user.name'}.' at '.$env{'user.domain'});
10745:                 return 'refused';
10746:             }
10747:         }
10748:         $mrole='gr';
10749:     } else {
10750:         my $cwosec=$url;
10751:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
10752:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
10753:             my $refused;
10754:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
10755:                 if (!(&allowed('c'.$role,$url))) {
10756:                     $refused = 1;
10757:                 }
10758:             } else {
10759:                 $refused = 1;
10760:             }
10761:             if ($refused) {
10762:                 my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
10763:                 if (!$selfenroll && ($othdomby ne 'othdombyuser') &&
10764:                    (($context eq 'course') || ($context eq 'ltienroll' && $env{'request.lti.login'}))) {
10765:                     my %crsenv;
10766:                     if ($role eq 'cc' || $role eq 'co') {
10767:                         %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
10768:                         if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
10769:                             if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
10770:                                 if ($crsenv{'internal.courseowner'} eq 
10771:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
10772:                                     $refused = '';
10773:                                 }
10774:                             }
10775:                         } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) { 
10776:                             if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
10777:                                 if ($crsenv{'internal.courseowner'} eq 
10778:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
10779:                                     $refused = '';
10780:                                 }
10781:                             }
10782:                         }
10783:                     }
10784:                 } elsif (($selfenroll == 1) && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
10785:                     if ($role eq 'st') {
10786:                         $refused = '';
10787:                     } elsif (($context eq 'ltienroll') && ($env{'request.lti.login'})) {
10788:                         $refused = '';
10789:                     }
10790:                 } elsif ($othdomby eq 'othdombyuser') {
10791:                     my ($key,%queuedrolereq);
10792:                     if ($context eq 'course') {
10793:                         my ($sec) = ($url =~ m{^/\Q$cwosec\E/(.*)$});
10794:                         $key = "$uname:$udom:$role:$sec";
10795:                         %queuedrolereq = &Apache::lonnet::get('nohist_othdomqueued',[$key],$cdom,$cnum);
10796:                         if ((exists($queuedrolereq{$key})) && (ref($queuedrolereq{$key}) eq 'HASH')) {
10797:                             if (($queuedrolereq{$key}{'adj'} eq 'user') && ($queuedrolereq{$key}{'requester'} eq $requester)) {
10798:                                 if ((($role eq 'cc') && ($cnum !~ /^$match_community$/)) || 
10799:                                     (($role eq 'co') && ($cnum =~ /^$match_community$/))) {
10800:                                     my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
10801:                                     if ($crsenv{'internal.courseowner'} eq $requester) {
10802:                                         $refused = '';
10803:                                     }
10804:                                 } elsif ($role =~ /^(?:in|ta|ep|st)$/) {
10805:                                     $refused = '';
10806:                                 }
10807:                             }
10808:                         }
10809:                     } elsif (($context eq 'author') && ($role =~ /^ca|aa$/)) {
10810:                         my $key = "$uname:$udom:$role"; 
10811:                         my ($audom,$auname) = ($url =~ m{^/($match_domain)/($match_username)$});
10812:                         if (($audom ne '') && ($auname ne '')) {
10813:                             my %queuedrolereq = &Apache::lonnet::get('nohist_othdomqueued',[$key],$audom,$auname);
10814:                             if ((exists($queuedrolereq{$key})) && (ref($queuedrolereq{$key}) eq 'HASH')) {
10815:                                 if (($queuedrolereq{$key}{'adj'} eq 'user') && ($queuedrolereq{$key}{'requester'} eq $requester)) {
10816:                                     $refused = '';
10817:                                 }
10818:                             }
10819:                         }
10820:                     } elsif (($context eq 'domain') && ($role ne 'dc') && ($role ne 'su')) {
10821:                         my $key = "$uname:$udom:$role";
10822:                         my ($roledom) = ($url =~ m{^/($match_domain)/\Q$role\E$});
10823:                         if ($roledom ne '') {
10824:                             my $confname = $roledom.'-domainconfig';
10825:                             my %queuedrolereq = &Apache::lonnet::get('nohist_othdomqueued',[$key],$roledom,$confname);
10826:                             if ((exists($queuedrolereq{$key})) && (ref($queuedrolereq{$key}) eq 'HASH')) {
10827:                                 if (($queuedrolereq{$key}{'adj'} eq 'user') && ($queuedrolereq{$key}{'requester'} eq $requester)) {
10828:                                     $refused = '';
10829:                                 }
10830:                             }
10831:                         }
10832:                     }
10833:                 } elsif ($context eq 'requestcourses') {
10834:                     my @possroles = ('st','ta','ep','in','cc','co');
10835:                     if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
10836:                         my $wrongcc;
10837:                         if ($cnum =~ /^$match_community$/) {
10838:                             $wrongcc = 1 if ($role eq 'cc');
10839:                         } else {
10840:                             $wrongcc = 1 if ($role eq 'co');
10841:                         }
10842:                         unless ($wrongcc) {
10843:                             my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
10844:                             if ($crsenv{'internal.courseowner'} eq 
10845:                                  $env{'user.name'}.':'.$env{'user.domain'}) {
10846:                                 $refused = '';
10847:                             }
10848:                         }
10849:                     }
10850:                 } elsif ($context eq 'requestauthor') {
10851:                     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) && 
10852:                         ($url eq '/'.$udom.'/') && ($role eq 'au')) {
10853:                         if ($env{'environment.requestauthor'} eq 'automatic') {
10854:                             $refused = '';
10855:                         } else {
10856:                             my %domdefaults = &get_domain_defaults($udom);
10857:                             if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
10858:                                 my $checkbystatus;
10859:                                 if ($env{'user.adv'}) { 
10860:                                     my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
10861:                                     if ($disposition eq 'automatic') {
10862:                                         $refused = '';
10863:                                     } elsif ($disposition eq '') {
10864:                                         $checkbystatus = 1;
10865:                                     } 
10866:                                 } else {
10867:                                     $checkbystatus = 1;
10868:                                 }
10869:                                 if ($checkbystatus) {
10870:                                     if ($env{'environment.inststatus'}) {
10871:                                         my @inststatuses = split(/,/,$env{'environment.inststatus'});
10872:                                         foreach my $type (@inststatuses) {
10873:                                             if (($type ne '') &&
10874:                                                 ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
10875:                                                 $refused = '';
10876:                                             }
10877:                                         }
10878:                                     } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
10879:                                         $refused = '';
10880:                                     }
10881:                                 }
10882:                             }
10883:                         }
10884:                     }
10885:                 } elsif (($context eq 'author') && (($role eq 'ca' || $role eq 'aa'))) {
10886:                     if ($url =~ m{^/($match_domain)/($match_username)$}) {
10887:                         my ($audom,$auname) = ($1,$2);
10888:                         if ((&Apache::lonnet::allowed('v'.$role,"$audom/$auname")) &&
10889:                             ($env{"environment.internal.manager.$url"})) {
10890:                             $refused = '';
10891:                             $rolelogcontext = 'coauthor';
10892:                         }
10893:                     }
10894:                 }
10895:                 if ($refused) {
10896:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
10897:                              ' '.$role.' '.$end.' '.$start.' by '.
10898: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
10899:                     return 'refused';
10900:                 }
10901:             }
10902:         } elsif ($role eq 'au') {
10903:             if ($url ne '/'.$udom.'/') {
10904:                 &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
10905:                          ' to assign author role for '.$uname.':'.$udom.
10906:                          ' in domain: '.$url.' refused (wrong domain).');
10907:                 return 'refused';
10908:             }
10909:         }
10910:         $mrole=$role;
10911:     }
10912:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
10913:                 "$udom:$uname:$url".'_'."$mrole=$role";
10914:     if ($end) { $command.='_'.$end; }
10915:     if ($start) {
10916: 	if ($end) { 
10917:            $command.='_'.$start; 
10918:         } else {
10919:            $command.='_0_'.$start;
10920:         }
10921:     }
10922:     my $origstart = $start;
10923:     my $origend = $end;
10924:     my $delflag;
10925: # actually delete
10926:     if ($deleteflag) {
10927: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
10928: # modify command to delete the role
10929:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
10930:                 "$udom:$uname:$url".'_'."$mrole";
10931: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
10932: # set start and finish to negative values for userrolelog
10933:            $start=-1;
10934:            $end=-1;
10935:            $delflag = 1;
10936:         }
10937:     }
10938: # send command
10939:     my $answer=&reply($command,&homeserver($uname,$udom));
10940: # log new user role if status is ok
10941:     if ($answer eq 'ok') {
10942: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
10943:         if (($role eq 'cc') || ($role eq 'in') ||
10944:             ($role eq 'ep') || ($role eq 'ad') ||
10945:             ($role eq 'ta') || ($role eq 'st') ||
10946:             ($role=~/^cr/) || ($role eq 'gr') ||
10947:             ($role eq 'co')) {
10948: # for course roles, perform group memberships changes triggered by role change.
10949:             unless ($role =~ /^gr/) {
10950:                 &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
10951:                                                  $origstart,$selfenroll,$context);
10952:             }
10953:             &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
10954:                            $selfenroll,$context,$othdomby,$requester);
10955:         } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
10956:                  ($role eq 'au') || ($role eq 'dc') || ($role eq 'dh') ||
10957:                  ($role eq 'da')) {
10958:             &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
10959:                            $context,$othdomby,$requester);
10960:         } elsif (($role eq 'ca') || ($role eq 'aa')) {
10961:             if ($rolelogcontext eq '') {
10962:                 $rolelogcontext = $context;
10963:             }
10964:             &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
10965:                              $rolelogcontext,$othdomby,$requester); 
10966:         }
10967:         if ($role eq 'cc') {
10968:             &autoupdate_coowners($url,$end,$start,$uname,$udom);
10969:         }
10970:     }
10971:     return $answer;
10972: }
10973: 
10974: sub autoupdate_coowners {
10975:     my ($url,$end,$start,$uname,$udom) = @_;
10976:     my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
10977:     if (($cdom ne '') && ($cnum ne '')) {
10978:         my $now = time;
10979:         my %domdesign = &Apache::loncommon::get_domainconf($cdom);
10980:         if ($domdesign{$cdom.'.autoassign.co-owners'}) {
10981:             my %coursehash = &coursedescription($cdom.'_'.$cnum);
10982:             my $instcode = $coursehash{'internal.coursecode'};
10983:             my $xlists = $coursehash{'internal.crosslistings'};
10984:             if ($instcode ne '') {
10985:                 if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
10986:                     unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
10987:                         my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
10988:                         my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
10989:                         unless ($result eq 'valid') {
10990:                             if ($xlists ne '') {
10991:                                 foreach my $xlist (split(',',$xlists)) {
10992:                                     my ($inst_crosslist,$lcsec) = split(':',$xlist);
10993:                                     $result =
10994:                                         &auto_validate_inst_crosslist($cnum,$cdom,$instcode,
10995:                                                                       $inst_crosslist,$uname.':'.$udom);
10996:                                     last if ($result eq 'valid');
10997:                                 }
10998:                             }
10999:                         }
11000:                         if ($result eq 'valid') {
11001:                             if ($coursehash{'internal.co-owners'}) {
11002:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
11003:                                     push(@newcoowners,$coowner);
11004:                                 }
11005:                                 unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
11006:                                     push(@newcoowners,$uname.':'.$udom);
11007:                                 }
11008:                                 @newcoowners = sort(@newcoowners);
11009:                             } else {
11010:                                 push(@newcoowners,$uname.':'.$udom);
11011:                             }
11012:                         } elsif ($coursehash{'internal.co-owners'}) {
11013:                             foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
11014:                                 unless ($coowner eq $uname.':'.$udom) {
11015:                                     push(@newcoowners,$coowner);
11016:                                 }
11017:                             }
11018:                             unless (@newcoowners > 0) {
11019:                                 $delcoowners = 1;
11020:                                 $coowners = '';
11021:                             }
11022:                         }
11023:                         if (@newcoowners || $delcoowners) {
11024:                             &store_coowners($cdom,$cnum,$coursehash{'home'},
11025:                                             $delcoowners,@newcoowners);
11026:                         }
11027:                     }
11028:                 }
11029:             }
11030:         }
11031:     }
11032: }
11033: 
11034: sub store_coowners {
11035:     my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
11036:     my $cid = $cdom.'_'.$cnum;
11037:     my ($coowners,$delresult,$putresult);
11038:     if (@newcoowners) {
11039:         $coowners = join(',',@newcoowners);
11040:         my %coownershash = (
11041:                             'internal.co-owners' => $coowners,
11042:                            );
11043:         $putresult = &put('environment',\%coownershash,$cdom,$cnum);
11044:         if ($putresult eq 'ok') {
11045:             if ($env{'course.'.$cid.'.num'} eq $cnum) {
11046:                 &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
11047:             }
11048:         }
11049:     }
11050:     if ($delcoowners) {
11051:         $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
11052:         if ($delresult eq 'ok') {
11053:             if ($env{'course.'.$cid.'.internal.co-owners'}) {
11054:                 &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
11055:             }
11056:         }
11057:     }
11058:     if (($putresult eq 'ok') || ($delresult eq 'ok')) {
11059:         my %crsinfo =
11060:             &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
11061:         if (ref($crsinfo{$cid}) eq 'HASH') {
11062:             $crsinfo{$cid}{'co-owners'} = \@newcoowners;
11063:             my $cidput = &courseidput($cdom,\%crsinfo,$chome,'notime');
11064:         }
11065:     }
11066: }
11067: 
11068: # -------------------------------------------------- Modify user authentication
11069: # Overrides without validation
11070: 
11071: sub modifyuserauth {
11072:     my ($udom,$uname,$umode,$upass)=@_;
11073:     my $uhome=&homeserver($uname,$udom);
11074:     my $allowed;
11075:     if (&allowed('mau',$udom)) {
11076:         $allowed = 1;
11077:     } elsif (($umode eq 'internal') && ($udom eq $env{'user.domain'}) &&
11078:              ($env{'request.course.id'}) && (&allowed('mip',$env{'request.course.id'})) &&
11079:              (!$env{'course.'.$env{'request.course.id'}.'.internal.nopasswdchg'})) {
11080:         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
11081:         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
11082:         if (($cdom ne '') && ($cnum ne '')) {
11083:             my $is_owner = &is_course_owner($cdom,$cnum);
11084:             if ($is_owner) {
11085:                 $allowed = 1;
11086:             }
11087:         }
11088:     }
11089:     unless ($allowed) { return 'refused'; }
11090:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
11091:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
11092:              ' in domain '.$env{'request.role.domain'});  
11093:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
11094: 		     &escape($upass),$uhome);
11095:     my $ip = &get_requestor_ip();
11096:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
11097:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
11098:          '(Remote '.$ip.'): '.$reply);
11099:     &log($udom,,$uname,$uhome,
11100:         'Authentication changed by '.$env{'user.domain'}.', '.
11101:                                      $env{'user.name'}.', '.$umode.
11102:          '(Remote '.$ip.'): '.$reply);
11103:     unless ($reply eq 'ok') {
11104:         &logthis('Authentication mode error: '.$reply);
11105: 	return 'error: '.$reply;
11106:     }   
11107:     return 'ok';
11108: }
11109: 
11110: # --------------------------------------------------------------- Modify a user
11111: 
11112: sub modifyuser {
11113:     my ($udom,    $uname, $uid,
11114:         $umode,   $upass, $first,
11115:         $middle,  $last,  $gene,
11116:         $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
11117:     $udom= &LONCAPA::clean_domain($udom);
11118:     $uname=&LONCAPA::clean_username($uname);
11119:     my $showcandelete = 'none';
11120:     if (ref($candelete) eq 'ARRAY') {
11121:         if (@{$candelete} > 0) {
11122:             $showcandelete = join(', ',@{$candelete});
11123:         }
11124:     }
11125:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
11126:              $umode.', '.$first.', '.$middle.', '.
11127: 	     $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
11128:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
11129:                                      ' desiredhome not specified'). 
11130:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
11131:              ' in domain '.$env{'request.role.domain'});
11132:     my $uhome=&homeserver($uname,$udom,'true');
11133:     my $newuser;
11134:     if ($uhome eq 'no_host') {
11135:         $newuser = 1;
11136:         unless (($umode && ($upass ne '')) || ($umode eq 'localauth') ||
11137:                 ($umode eq 'lti')) {
11138:             return 'error: more information needed to create new user';
11139:         }
11140:     }
11141: # ----------------------------------------------------------------- Create User
11142:     if (($uhome eq 'no_host') && 
11143: 	(($umode && $upass) || ($umode eq 'localauth') || ($umode eq 'lti'))) {
11144:         my $unhome='';
11145:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
11146:             $unhome = $desiredhome;
11147: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
11148: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
11149:         } else { # load balancing routine for determining $unhome
11150:             my $loadm=10000000;
11151: 	    my %servers = &get_servers($udom,'library');
11152: 	    foreach my $tryserver (keys(%servers)) {
11153: 		my $answer=reply('load',$tryserver);
11154: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
11155: 		    $loadm=$answer;
11156: 		    $unhome=$tryserver;
11157: 		}
11158: 	    }
11159:         }
11160:         if (($unhome eq '') || ($unhome eq 'no_host')) {
11161: 	    return 'error: unable to find a home server for '.$uname.
11162:                    ' in domain '.$udom;
11163:         }
11164:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
11165:                          &escape($upass),$unhome);
11166: 	unless ($reply eq 'ok') {
11167:             return 'error: '.$reply;
11168:         }   
11169:         $uhome=&homeserver($uname,$udom,'true');
11170:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
11171: 	    return 'error: unable verify users home machine.';
11172:         }
11173:     }   # End of creation of new user
11174: # ---------------------------------------------------------------------- Add ID
11175:     if ($uid) {
11176:        $uid=~tr/A-Z/a-z/;
11177:        my %uidhash=&idrget($udom,$uname);
11178:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
11179:          && (!$forceid)) {
11180: 	  unless ($uid eq $uidhash{$uname}) {
11181: 	      return 'error: user id "'.$uid.'" does not match '.
11182:                   'current user id "'.$uidhash{$uname}.'".';
11183:           }
11184:        } else {
11185: 	  &idput($udom,{$uname => $uid},$uhome,'ids');
11186:        }
11187:     }
11188: # -------------------------------------------------------------- Add names, etc
11189:     my @tmp=&get('environment',
11190: 		   ['firstname','middlename','lastname','generation','id',
11191:                     'permanentemail','inststatus'],
11192: 		   $udom,$uname);
11193:     my (%names,%oldnames);
11194:     if ($tmp[0] =~ m/^error:.*/) { 
11195:         %names=(); 
11196:     } else {
11197:         %names = @tmp;
11198:         %oldnames = %names;
11199:     }
11200: #
11201: # If name, email and/or uid are blank (e.g., because an uploaded file
11202: # of users did not contain them), do not overwrite existing values
11203: # unless field is in $candelete array ref.  
11204: #
11205: 
11206:     my @fields = ('firstname','middlename','lastname','generation',
11207:                   'permanentemail','id');
11208:     my %newvalues;
11209:     if (ref($candelete) eq 'ARRAY') {
11210:         foreach my $field (@fields) {
11211:             if (grep(/^\Q$field\E$/,@{$candelete})) {
11212:                 if ($field eq 'firstname') {
11213:                     $names{$field} = $first;
11214:                 } elsif ($field eq 'middlename') {
11215:                     $names{$field} = $middle;
11216:                 } elsif ($field eq 'lastname') {
11217:                     $names{$field} = $last;
11218:                 } elsif ($field eq 'generation') { 
11219:                     $names{$field} = $gene;
11220:                 } elsif ($field eq 'permanentemail') {
11221:                     $names{$field} = $email;
11222:                 } elsif ($field eq 'id') {
11223:                     $names{$field}  = $uid;
11224:                 }
11225:             }
11226:         }
11227:     }
11228:     if ($first)  { $names{'firstname'}  = $first; }
11229:     if (defined($middle)) { $names{'middlename'} = $middle; }
11230:     if ($last)   { $names{'lastname'}   = $last; }
11231:     if (defined($gene))   { $names{'generation'} = $gene; }
11232:     if ($email) {
11233:        $email=~s/[^\w\@\.\-\,]//gs;
11234:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
11235:     }
11236:     if ($uid) { $names{'id'}  = $uid; }
11237:     if (defined($inststatus)) {
11238:         $names{'inststatus'} = '';
11239:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
11240:         if (ref($usertypes) eq 'HASH') {
11241:             my @okstatuses; 
11242:             foreach my $item (split(/:/,$inststatus)) {
11243:                 if (defined($usertypes->{$item})) {
11244:                     push(@okstatuses,$item);  
11245:                 }
11246:             }
11247:             if (@okstatuses) {
11248:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
11249:             }
11250:         }
11251:     }
11252:     my $logmsg = $udom.', '.$uname.', '.$uid.', '.
11253:                  $umode.', '.$first.', '.$middle.', '.
11254:                  $last.', '.$gene.', '.$email.', '.$inststatus;
11255:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
11256:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
11257:     } else {
11258:         $logmsg .= ' during self creation';
11259:     }
11260:     my $changed;
11261:     if ($newuser) {
11262:         $changed = 1;
11263:     } else {
11264:         foreach my $field (@fields) {
11265:             if ($names{$field} ne $oldnames{$field}) {
11266:                 $changed = 1;
11267:                 last;
11268:             }
11269:         }
11270:     }
11271:     unless ($changed) {
11272:         $logmsg = 'No changes in user information needed for: '.$logmsg;
11273:         &logthis($logmsg);
11274:         return 'ok';
11275:     }
11276:     my $reply = &put('environment', \%names, $udom,$uname);
11277:     if ($reply ne 'ok') { 
11278:         return 'error: '.$reply;
11279:     }
11280:     if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
11281:         &devalidate_cache_new('emailscache',$uname.':'.$udom);
11282:     }
11283:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
11284:     &devalidate_cache_new('namescache',$uname.':'.$udom);
11285:     $logmsg = 'Success modifying user '.$logmsg;
11286:     &logthis($logmsg);
11287:     return 'ok';
11288: }
11289: 
11290: # -------------------------------------------------------------- Modify student
11291: 
11292: sub modifystudent {
11293:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
11294:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
11295:         $selfenroll,$context,$inststatus,$credits,$instsec)=@_;
11296:     if (!$cid) {
11297: 	unless ($cid=$env{'request.course.id'}) {
11298: 	    return 'not_in_class';
11299: 	}
11300:     }
11301: # --------------------------------------------------------------- Make the user
11302:     my $reply=&modifyuser
11303: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
11304:          $desiredhome,$email,$inststatus);
11305:     unless ($reply eq 'ok') { return $reply; }
11306:     # This will cause &modify_student_enrollment to get the uid from the
11307:     # student's environment
11308:     $uid = undef if (!$forceid);
11309:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
11310:                                         $gene,$usec,$end,$start,$type,$locktype,
11311:                                         $cid,$selfenroll,$context,$credits,$instsec);
11312:     return $reply;
11313: }
11314: 
11315: sub modify_student_enrollment {
11316:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,
11317:         $locktype,$cid,$selfenroll,$context,$credits,$instsec,$othdomby,$requester) = @_;
11318:     my ($cdom,$cnum,$chome);
11319:     if (!$cid) {
11320: 	unless ($cid=$env{'request.course.id'}) {
11321: 	    return 'not_in_class';
11322: 	}
11323: 	$cdom=$env{'course.'.$cid.'.domain'};
11324: 	$cnum=$env{'course.'.$cid.'.num'};
11325:     } else {
11326: 	($cdom,$cnum)=split(/_/,$cid);
11327:     }
11328:     $chome=$env{'course.'.$cid.'.home'};
11329:     if (!$chome) {
11330: 	$chome=&homeserver($cnum,$cdom);
11331:     }
11332:     if (!$chome) { return 'unknown_course'; }
11333:     # Make sure the user exists
11334:     my $uhome=&homeserver($uname,$udom);
11335:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
11336: 	return 'error: no such user';
11337:     }
11338:     # Get student data if we were not given enough information
11339:     if (!defined($first)  || $first  eq '' || 
11340:         !defined($last)   || $last   eq '' || 
11341:         !defined($uid)    || $uid    eq '' || 
11342:         !defined($middle) || $middle eq '' || 
11343:         !defined($gene)   || $gene   eq '') {
11344:         # They did not supply us with enough data to enroll the student, so
11345:         # we need to pick up more information.
11346:         my %tmp = &get('environment',
11347:                        ['firstname','middlename','lastname', 'generation','id']
11348:                        ,$udom,$uname);
11349: 
11350:         #foreach my $key (keys(%tmp)) {
11351:         #    &logthis("key $key = ".$tmp{$key});
11352:         #}
11353:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
11354:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
11355:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
11356:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
11357:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
11358:     }
11359:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
11360:     my $user = "$uname:$udom";
11361:     my %old_entry = &get('classlist',[$user],$cdom,$cnum);
11362:     my $reply=cput('classlist',
11363: 		   {$user => 
11364: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits,$instsec) },
11365: 		   $cdom,$cnum);
11366:     if (($reply eq 'ok') || ($reply eq 'delayed')) {
11367:         &devalidate_getsection_cache($udom,$uname,$cid);
11368:     } else { 
11369: 	return 'error: '.$reply;
11370:     }
11371:     # Add student role to user
11372:     my $uurl='/'.$cid;
11373:     $uurl=~s/\_/\//g;
11374:     if ($usec) {
11375: 	$uurl.='/'.$usec;
11376:     }
11377:     my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
11378:                              $selfenroll,$context,$othdomby,$requester);
11379:     if ($result ne 'ok') {
11380:         if ($old_entry{$user} ne '') {
11381:             $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
11382:         } else {
11383:             $reply = &del('classlist',[$user],$cdom,$cnum);
11384:         }
11385:     }
11386:     return $result; 
11387: }
11388: 
11389: sub format_name {
11390:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
11391:     my $name;
11392:     if ($first ne 'lastname') {
11393: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
11394:     } else {
11395: 	if ($lastname=~/\S/) {
11396: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
11397: 	    $name=~s/\s+,/,/;
11398: 	} else {
11399: 	    $name.= $firstname.' '.$middlename.' '.$generation;
11400: 	}
11401:     }
11402:     $name=~s/^\s+//;
11403:     $name=~s/\s+$//;
11404:     $name=~s/\s+/ /g;
11405:     return $name;
11406: }
11407: 
11408: # ------------------------------------------------- Write to course preferences
11409: 
11410: sub writecoursepref {
11411:     my ($courseid,%prefs)=@_;
11412:     $courseid=~s/^\///;
11413:     $courseid=~s/\_/\//g;
11414:     my ($cdomain,$cnum)=split(/\//,$courseid);
11415:     my $chome=homeserver($cnum,$cdomain);
11416:     if (($chome eq '') || ($chome eq 'no_host')) { 
11417: 	return 'error: no such course';
11418:     }
11419:     my $cstring='';
11420:     foreach my $pref (keys(%prefs)) {
11421: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
11422:     }
11423:     $cstring=~s/\&$//;
11424:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
11425: }
11426: 
11427: # ---------------------------------------------------------- Make/modify course
11428: 
11429: sub createcourse {
11430:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
11431:         $course_owner,$crstype,$cnum,$context,$category,$callercontext)=@_;
11432:     $url=&declutter($url);
11433:     my $cid='';
11434:     if ($context eq 'requestcourses') {
11435:         my $can_create = 0;
11436:         my ($ownername,$ownerdom) = split(':',$course_owner);
11437:         if ($udom eq $ownerdom) {
11438:             my $reload;
11439:             if (($callercontext eq 'auto') &&
11440:                ($ownerdom eq $env{'user.domain'}) && ($ownername eq $env{'user.name'})) {
11441:                 $reload = 'reload';
11442:             }
11443:             if (&usertools_access($ownername,$ownerdom,$category,$reload,
11444:                                   $context)) {
11445:                 $can_create = 1;
11446:             }
11447:         } else {
11448:             my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
11449:                                            $category);
11450:             if ($userenv{'reqcrsotherdom.'.$category} ne '') {
11451:                 my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
11452:                 if (@curr > 0) {
11453:                     my @options = qw(approval validate autolimit);
11454:                     my $optregex = join('|',@options);
11455:                     if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
11456:                         $can_create = 1;
11457:                     }
11458:                 }
11459:             }
11460:         }
11461:         if ($can_create) {
11462:             unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
11463:                 unless (&allowed('ccc',$udom)) {
11464:                     return 'refused'; 
11465:                 }
11466:             }
11467:         } else {
11468:             return 'refused';
11469:         }
11470:     } elsif (!&allowed('ccc',$udom)) {
11471:         return 'refused';
11472:     }
11473: # --------------------------------------------------------------- Get Unique ID
11474:     my $uname;
11475:     if ($cnum =~ /^$match_courseid$/) {
11476:         my $chome=&homeserver($cnum,$udom,'true');
11477:         if (($chome eq '') || ($chome eq 'no_host')) {
11478:             $uname = $cnum;
11479:         } else {
11480:             $uname = &generate_coursenum($udom,$crstype);
11481:         }
11482:     } else {
11483:         $uname = &generate_coursenum($udom,$crstype);
11484:     }
11485:     return $uname if ($uname =~ /^error/);
11486: # -------------------------------------------------- Check supplied server name
11487:     if (!defined($course_server)) {
11488:         if (defined(&domain($udom,'primary'))) {
11489:             $course_server = &domain($udom,'primary');
11490:         } else {
11491:             $course_server = $env{'user.home'}; 
11492:         }
11493:     }
11494:     my %host_servers =
11495:         &get_servers($udom,'library');
11496:     unless ($host_servers{$course_server}) {
11497:         return 'error: invalid home server for course: '.$course_server;
11498:     }
11499: # ------------------------------------------------------------- Make the course
11500:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
11501:                       $course_server);
11502:     unless ($reply eq 'ok') { return 'error: '.$reply; }
11503:     my $uhome=&homeserver($uname,$udom,'true');
11504:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
11505: 	return 'error: no such course';
11506:     }
11507: # ----------------------------------------------------------------- Course made
11508: # log existence
11509:     my $now = time;
11510:     my $newcourse = {
11511:                     $udom.'_'.$uname => {
11512:                                      description => $description,
11513:                                      inst_code   => $inst_code,
11514:                                      owner       => $course_owner,
11515:                                      type        => $crstype,
11516:                                      creator     => $env{'user.name'}.':'.
11517:                                                     $env{'user.domain'},
11518:                                      created     => $now,
11519:                                      context     => $context,
11520:                                                 },
11521:                     };
11522:     &courseidput($udom,$newcourse,$uhome,'notime');
11523: # set toplevel url
11524:     my $topurl=$url;
11525:     unless ($nonstandard) {
11526: # ------------------------------------------ For standard courses, make top url
11527:         my $mapurl=&clutter($url);
11528:         if ($mapurl eq '/res/') { $mapurl=''; }
11529:         $env{'form.initmap'}=(<<ENDINITMAP);
11530: <map>
11531: <resource id="1" type="start"></resource>
11532: <resource id="2" src="$mapurl"></resource>
11533: <resource id="3" type="finish"></resource>
11534: <link index="1" from="1" to="2"></link>
11535: <link index="2" from="2" to="3"></link>
11536: </map>
11537: ENDINITMAP
11538:         $topurl=&declutter(
11539:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
11540:                           );
11541:     }
11542: # ----------------------------------------------------------- Write preferences
11543:     &writecoursepref($udom.'_'.$uname,
11544:                      ('description'              => $description,
11545:                       'url'                      => $topurl,
11546:                       'internal.creator'         => $env{'user.name'}.':'.
11547:                                                     $env{'user.domain'},
11548:                       'internal.created'         => $now,
11549:                       'internal.creationcontext' => $context)
11550:                     );
11551:     return '/'.$udom.'/'.$uname;
11552: }
11553: 
11554: # ------------------------------------------------------------------- Create ID
11555: sub generate_coursenum {
11556:     my ($udom,$crstype) = @_;
11557:     my $domdesc = &domain($udom);
11558:     return 'error: invalid domain' if ($domdesc eq '');
11559:     my $first;
11560:     if ($crstype eq 'Community') {
11561:         $first = '0';
11562:     } else {
11563:         $first = int(1+rand(9)); 
11564:     } 
11565:     my $uname=$first.
11566:         ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
11567:         substr($$.time,0,5).unpack("H8",pack("I32",time)).
11568:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
11569: # ----------------------------------------------- Make sure that does not exist
11570:     my $uhome=&homeserver($uname,$udom,'true');
11571:     unless (($uhome eq '') || ($uhome eq 'no_host')) {
11572:         if ($crstype eq 'Community') {
11573:             $first = '0';
11574:         } else {
11575:             $first = int(1+rand(9));
11576:         }
11577:         $uname=$first.
11578:                ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
11579:                substr($$.time,0,5).unpack("H8",pack("I32",time)).
11580:                unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
11581:         $uhome=&homeserver($uname,$udom,'true');
11582:         unless (($uhome eq '') || ($uhome eq 'no_host')) {
11583:             return 'error: unable to generate unique course-ID';
11584:         }
11585:     }
11586:     return $uname;
11587: }
11588: 
11589: sub is_course {
11590:     my ($cdom, $cnum) = scalar(@_) == 1 ? 
11591:          ($_[0] =~ /^($match_domain)_($match_courseid)$/)  :  @_;
11592: 
11593:     return unless (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/));
11594:     my $uhome=&homeserver($cnum,$cdom);
11595:     my $iscourse;
11596:     if (grep { $_ eq $uhome } current_machine_ids()) {
11597:         $iscourse = &LONCAPA::Lond::is_course($cdom,$cnum);
11598:     } else {
11599:         my $hashid = $cdom.':'.$cnum;
11600:         ($iscourse,my $cached) = &is_cached_new('iscourse',$hashid);
11601:         unless (defined($cached)) {
11602:             my %courses = &courseiddump($cdom, '.', 1, '.', '.',
11603:                                         $cnum,undef,undef,'.');
11604:             $iscourse = 0;
11605:             if (exists($courses{$cdom.'_'.$cnum})) {
11606:                 $iscourse = 1;
11607:             }
11608:             &do_cache_new('iscourse',$hashid,$iscourse,3600);
11609:         }
11610:     }
11611:     return unless ($iscourse);
11612:     return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
11613: }
11614: 
11615: sub store_userdata {
11616:     my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
11617:     my $result;
11618:     if ($datakey ne '') {
11619:         if (ref($storehash) eq 'HASH') {
11620:             if ($udom eq '' || $uname eq '') {
11621:                 $udom = $env{'user.domain'};
11622:                 $uname = $env{'user.name'};
11623:             }
11624:             my $uhome=&homeserver($uname,$udom);
11625:             if (($uhome eq '') || ($uhome eq 'no_host')) {
11626:                 $result = 'error: no_host';
11627:             } else {
11628:                 $storehash->{'ip'} = &get_requestor_ip();
11629:                 $storehash->{'host'} = $perlvar{'lonHostID'};
11630: 
11631:                 my $namevalue='';
11632:                 foreach my $key (keys(%{$storehash})) {
11633:                     $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
11634:                 }
11635:                 $namevalue=~s/\&$//;
11636:                 unless ($namespace eq 'courserequests') {
11637:                     $datakey = &escape($datakey);
11638:                 }
11639:                 $result =  &reply("store:$udom:$uname:$namespace:$datakey:".
11640:                                   $namevalue,$uhome);
11641:             }
11642:         } else {
11643:             $result = 'error: data to store was not a hash reference'; 
11644:         }
11645:     } else {
11646:         $result= 'error: invalid requestkey'; 
11647:     }
11648:     return $result;
11649: }
11650: 
11651: # ---------------------------------------------------------- Assign Custom Role
11652: 
11653: sub assigncustomrole {
11654:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,
11655:         $selfenroll,$context,$othdomby,$requester)=@_;
11656:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
11657:                        $end,$start,$deleteflag,$selfenroll,$context,$othdomby,
11658:                        $requester);
11659: }
11660: 
11661: # ----------------------------------------------------------------- Revoke Role
11662: 
11663: sub revokerole {
11664:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
11665:     my $now=time;
11666:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
11667: }
11668: 
11669: # ---------------------------------------------------------- Revoke Custom Role
11670: 
11671: sub revokecustomrole {
11672:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
11673:     my $now=time;
11674:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
11675:            $deleteflag,$selfenroll,$context);
11676: }
11677: 
11678: # ------------------------------------------------------------ Disk usage
11679: sub diskusage {
11680:     my ($udom,$uname,$directorypath,$getpropath)=@_;
11681:     $directorypath =~ s/\/$//;
11682:     my $listing=&reply('du2:'.&escape($directorypath).':'
11683:                        .&escape($getpropath).':'.&escape($uname).':'
11684:                        .&escape($udom),homeserver($uname,$udom));
11685:     if ($listing eq 'unknown_cmd') {
11686:         if ($getpropath) {
11687:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
11688:         }
11689:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
11690:     }
11691:     return $listing;
11692: }
11693: 
11694: sub is_locked {
11695:     my ($file_name, $domain, $user, $which) = @_;
11696:     my @check;
11697:     my $is_locked;
11698:     push (@check,$file_name);
11699:     my %locked = &get('file_permissions',\@check,
11700: 		      $env{'user.domain'},$env{'user.name'});
11701:     my ($tmp)=keys(%locked);
11702:     if ($tmp=~/^error:/) { undef(%locked); }
11703:     
11704:     if (ref($locked{$file_name}) eq 'ARRAY') {
11705:         $is_locked = 'false';
11706:         foreach my $entry (@{$locked{$file_name}}) {
11707:            if (ref($entry) eq 'ARRAY') {
11708:                $is_locked = 'true';
11709:                if (ref($which) eq 'ARRAY') {
11710:                    push(@{$which},$entry);
11711:                } else {
11712:                    last;
11713:                }
11714:            }
11715:        }
11716:     } else {
11717:         $is_locked = 'false';
11718:     }
11719:     return $is_locked;
11720: }
11721: 
11722: sub declutter_portfile {
11723:     my ($file) = @_;
11724:     $file =~ s{^(/portfolio/|portfolio/)}{/};
11725:     return $file;
11726: }
11727: 
11728: # ------------------------------------------------------------- Mark as Read Only
11729: 
11730: sub mark_as_readonly {
11731:     my ($domain,$user,$files,$what) = @_;
11732:     my %current_permissions = &dump('file_permissions',$domain,$user);
11733:     my ($tmp)=keys(%current_permissions);
11734:     if ($tmp=~/^error:/) { undef(%current_permissions); }
11735:     foreach my $file (@{$files}) {
11736: 	$file = &declutter_portfile($file);
11737:         push(@{$current_permissions{$file}},$what);
11738:     }
11739:     &put('file_permissions',\%current_permissions,$domain,$user);
11740:     return;
11741: }
11742: 
11743: # ------------------------------------------------------------Save Selected Files
11744: 
11745: sub save_selected_files {
11746:     my ($user, $path, @files) = @_;
11747:     my $filename = $user."savedfiles";
11748:     my @other_files = &files_not_in_path($user, $path);
11749:     open (OUT,'>',LONCAPA::tempdir().$filename);
11750:     foreach my $file (@files) {
11751:         print (OUT $env{'form.currentpath'}.$file."\n");
11752:     }
11753:     foreach my $file (@other_files) {
11754:         print (OUT $file."\n");
11755:     }
11756:     close (OUT);
11757:     return 'ok';
11758: }
11759: 
11760: sub clear_selected_files {
11761:     my ($user) = @_;
11762:     my $filename = $user."savedfiles";
11763:     open (OUT,'>',LONCAPA::tempdir().$filename);
11764:     print (OUT undef);
11765:     close (OUT);
11766:     return ("ok");    
11767: }
11768: 
11769: sub files_in_path {
11770:     my ($user, $path) = @_;
11771:     my $filename = $user."savedfiles";
11772:     my %return_files;
11773:     open (IN,'<',LONCAPA::tempdir().$filename);
11774:     while (my $line_in = <IN>) {
11775:         chomp ($line_in);
11776:         my @paths_and_file = split (m!/!, $line_in);
11777:         my $file_part = pop (@paths_and_file);
11778:         my $path_part = join ('/', @paths_and_file);
11779:         $path_part.='/';
11780:         my $path_and_file = $path_part.$file_part;
11781:         if ($path_part eq $path) {
11782:             $return_files{$file_part}= 'selected';
11783:         }
11784:     }
11785:     close (IN);
11786:     return (\%return_files);
11787: }
11788: 
11789: # called in portfolio select mode, to show files selected NOT in current directory
11790: sub files_not_in_path {
11791:     my ($user, $path) = @_;
11792:     my $filename = $user."savedfiles";
11793:     my @return_files;
11794:     my $path_part;
11795:     open(IN, '<',LONCAPA::tempdir().$filename);
11796:     while (my $line = <IN>) {
11797:         #ok, I know it's clunky, but I want it to work
11798:         my @paths_and_file = split(m|/|, $line);
11799:         my $file_part = pop(@paths_and_file);
11800:         chomp($file_part);
11801:         my $path_part = join('/', @paths_and_file);
11802:         $path_part .= '/';
11803:         my $path_and_file = $path_part.$file_part;
11804:         if ($path_part ne $path) {
11805:             push(@return_files, ($path_and_file));
11806:         }
11807:     }
11808:     close(OUT);
11809:     return (@return_files);
11810: }
11811: 
11812: #------------------------------Submitted/Handedback Portfolio Files Versioning
11813:  
11814: sub portfiles_versioning {
11815:     my ($symb,$domain,$stu_name,$portfiles,$versioned_portfiles) = @_;
11816:     my $portfolio_root = '/userfiles/portfolio';
11817:     return unless ((ref($portfiles) eq 'ARRAY') && (ref($versioned_portfiles) eq 'ARRAY'));
11818:     foreach my $file (@{$portfiles}) {
11819:         &unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
11820:         my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
11821:         my ($answer_name,$answer_ver,$answer_ext) = &file_name_version_ext($answer_file);
11822:         my $getpropath = 1;
11823:         my ($dir_list,$listerror) = &dirlist($portfolio_root.$directory,$domain,
11824:                                              $stu_name,$getpropath);
11825:         my $version = &get_next_version($answer_name,$answer_ext,$dir_list);
11826:         my $new_answer = 
11827:             &version_selected_portfile($domain,$stu_name,$directory,$answer_file,$version);
11828:         if ($new_answer ne 'problem getting file') {
11829:             push(@{$versioned_portfiles}, $directory.$new_answer);
11830:             &mark_as_readonly($domain,$stu_name,[$directory.$new_answer],
11831:                               [$symb,$env{'request.course.id'},'graded']);
11832:         }
11833:     }
11834: }
11835: 
11836: sub get_next_version {
11837:     my ($answer_name, $answer_ext, $dir_list) = @_;
11838:     my $version;
11839:     if (ref($dir_list) eq 'ARRAY') {
11840:         foreach my $row (@{$dir_list}) {
11841:             my ($file) = split(/\&/,$row,2);
11842:             my ($file_name,$file_version,$file_ext) =
11843:                 &file_name_version_ext($file);
11844:             if (($file_name eq $answer_name) &&
11845:                 ($file_ext eq $answer_ext)) {
11846:                      # gets here if filename and extension match,
11847:                      # regardless of version
11848:                 if ($file_version ne '') {
11849:                     # a versioned file is found  so save it for later
11850:                     if ($file_version > $version) {
11851:                         $version = $file_version;
11852:                     }
11853:                 }
11854:             }
11855:         }
11856:     }
11857:     $version ++;
11858:     return($version);
11859: }
11860: 
11861: sub version_selected_portfile {
11862:     my ($domain,$stu_name,$directory,$file_name,$version) = @_;
11863:     my ($answer_name,$answer_ver,$answer_ext) =
11864:         &file_name_version_ext($file_name);
11865:     my $new_answer;
11866:     $env{'form.copy'} =
11867:         &getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
11868:     if($env{'form.copy'} eq '-1') {
11869:         $new_answer = 'problem getting file';
11870:     } else {
11871:         $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
11872:         my $copy_result = 
11873:             &finishuserfileupload($stu_name,$domain,'copy',
11874:                                   '/portfolio'.$directory.$new_answer);
11875:     }
11876:     undef($env{'form.copy'});
11877:     return ($new_answer);
11878: }
11879: 
11880: sub file_name_version_ext {
11881:     my ($file)=@_;
11882:     my @file_parts = split(/\./, $file);
11883:     my ($name,$version,$ext);
11884:     if (@file_parts > 1) {
11885:         $ext=pop(@file_parts);
11886:         if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
11887:             $version=pop(@file_parts);
11888:         }
11889:         $name=join('.',@file_parts);
11890:     } else {
11891:         $name=join('.',@file_parts);
11892:     }
11893:     return($name,$version,$ext);
11894: }
11895: 
11896: #----------------------------------------------Get portfolio file permissions
11897: 
11898: sub get_portfile_permissions {
11899:     my ($domain,$user) = @_;
11900:     my %current_permissions = &dump('file_permissions',$domain,$user);
11901:     my ($tmp)=keys(%current_permissions);
11902:     if ($tmp=~/^error:/) { undef(%current_permissions); }
11903:     return \%current_permissions;
11904: }
11905: 
11906: #---------------------------------------------Get portfolio file access controls
11907: 
11908: sub get_access_controls {
11909:     my ($current_permissions,$group,$file) = @_;
11910:     my %access;
11911:     my $real_file = $file;
11912:     $file =~ s/\.meta$//;
11913:     if (defined($file)) {
11914:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
11915:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
11916:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
11917:             }
11918:         }
11919:     } else {
11920:         foreach my $key (keys(%{$current_permissions})) {
11921:             if ($key =~ /\0accesscontrol$/) {
11922:                 if (defined($group)) {
11923:                     if ($key !~ m-^\Q$group\E/-) {
11924:                         next;
11925:                     }
11926:                 }
11927:                 my ($fullpath) = split(/\0/,$key);
11928:                 if (ref($$current_permissions{$key}) eq 'HASH') {
11929:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
11930:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
11931:                     }
11932:                 }
11933:             }
11934:         }
11935:     }
11936:     return %access;
11937: }
11938: 
11939: sub modify_access_controls {
11940:     my ($file_name,$changes,$domain,$user)=@_;
11941:     my ($outcome,$deloutcome);
11942:     my %store_permissions;
11943:     my %new_values;
11944:     my %new_control;
11945:     my %translation;
11946:     my @deletions = ();
11947:     my $now = time;
11948:     if (exists($$changes{'activate'})) {
11949:         if (ref($$changes{'activate'}) eq 'HASH') {
11950:             my @newitems = sort(keys(%{$$changes{'activate'}}));
11951:             my $numnew = scalar(@newitems);
11952:             for (my $i=0; $i<$numnew; $i++) {
11953:                 my $newkey = $newitems[$i];
11954:                 my $newid = &Apache::loncommon::get_cgi_id();
11955:                 if ($newkey =~ /^\d+:/) { 
11956:                     $newkey =~ s/^(\d+)/$newid/;
11957:                     $translation{$1} = $newid;
11958:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
11959:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
11960:                     $translation{$1} = $newid;
11961:                 }
11962:                 $new_values{$file_name."\0".$newkey} = 
11963:                                           $$changes{'activate'}{$newitems[$i]};
11964:                 $new_control{$newkey} = $now;
11965:             }
11966:         }
11967:     }
11968:     my %todelete;
11969:     my %changed_items;
11970:     foreach my $action ('delete','update') {
11971:         if (exists($$changes{$action})) {
11972:             if (ref($$changes{$action}) eq 'HASH') {
11973:                 foreach my $key (keys(%{$$changes{$action}})) {
11974:                     my ($itemnum) = ($key =~ /^([^:]+):/);
11975:                     if ($action eq 'delete') { 
11976:                         $todelete{$itemnum} = 1;
11977:                     } else {
11978:                         $changed_items{$itemnum} = $key;
11979:                     }
11980:                 }
11981:             }
11982:         }
11983:     }
11984:     # get lock on access controls for file.
11985:     my $lockhash = {
11986:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
11987:                                                        ':'.$env{'user.domain'},
11988:                    }; 
11989:     my $tries = 0;
11990:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
11991:    
11992:     while (($gotlock ne 'ok') && $tries < 10) {
11993:         $tries ++;
11994:         sleep(0.1);
11995:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
11996:     }
11997:     if ($gotlock eq 'ok') {
11998:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
11999:         my ($tmp)=keys(%curr_permissions);
12000:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
12001:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
12002:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
12003:             if (ref($curr_controls) eq 'HASH') {
12004:                 foreach my $control_item (keys(%{$curr_controls})) {
12005:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
12006:                     if (defined($todelete{$itemnum})) {
12007:                         push(@deletions,$file_name."\0".$control_item);
12008:                     } else {
12009:                         if (defined($changed_items{$itemnum})) {
12010:                             $new_control{$changed_items{$itemnum}} = $now;
12011:                             push(@deletions,$file_name."\0".$control_item);
12012:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
12013:                         } else {
12014:                             $new_control{$control_item} = $$curr_controls{$control_item};
12015:                         }
12016:                     }
12017:                 }
12018:             }
12019:         }
12020:         my ($group);
12021:         if (&is_course($domain,$user)) {
12022:             ($group,my $file) = split(/\//,$file_name,2);
12023:         }
12024:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
12025:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
12026:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
12027:         #  remove lock
12028:         my @del_lock = ($file_name."\0".'locked_access_records');
12029:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
12030:         my $sqlresult =
12031:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
12032:                                     $group);
12033:     } else {
12034:         $outcome = "error: could not obtain lockfile\n";  
12035:     }
12036:     return ($outcome,$deloutcome,\%new_values,\%translation);
12037: }
12038: 
12039: sub make_public_indefinitely {
12040:     my (@requrl) = @_;
12041:     return &automated_portfile_access('public',\@requrl);
12042: }
12043: 
12044: sub automated_portfile_access {
12045:     my ($accesstype,$addsref,$delsref,$info) = @_;
12046:     unless (($accesstype eq 'public') || ($accesstype eq 'ip')) {
12047:         return 'invalid';
12048:     }
12049:     my %urls;
12050:     if (ref($addsref) eq 'ARRAY') {
12051:         foreach my $requrl (@{$addsref}) {
12052:             if (&is_portfolio_url($requrl)) {
12053:                 unless (exists($urls{$requrl})) {
12054:                     $urls{$requrl} = 'add';
12055:                 }
12056:             }
12057:         }
12058:     }
12059:     if (ref($delsref) eq 'ARRAY') {
12060:         foreach my $requrl (@{$delsref}) { 
12061:             if (&is_portfolio_url($requrl)) {
12062:                 unless (exists($urls{$requrl})) {
12063:                     $urls{$requrl} = 'delete'; 
12064:                 }
12065:             }
12066:         }
12067:     }
12068:     unless (keys(%urls)) {
12069:         return 'invalid';
12070:     }
12071:     my $ip;
12072:     if ($accesstype eq 'ip') {
12073:         if (ref($info) eq 'HASH') {
12074:             if ($info->{'ip'} ne '') {
12075:                 $ip = $info->{'ip'};
12076:             }
12077:         }
12078:         if ($ip eq '') {
12079:             return 'invalid';
12080:         }
12081:     }
12082:     my $errors;
12083:     my $now = time;
12084:     my %current_perms;
12085:     foreach my $requrl (sort(keys(%urls))) {
12086:         my $action;
12087:         if ($urls{$requrl} eq 'add') {
12088:             $action = 'activate';
12089:         } else {
12090:             $action = 'none';
12091:         }
12092:         my $aclnum = 0;
12093:         my (undef,$udom,$unum,$file_name,$group) =
12094:             &parse_portfolio_url($requrl);
12095:         unless (exists($current_perms{$unum.':'.$udom})) {
12096:             $current_perms{$unum.':'.$udom} = &get_portfile_permissions($udom,$unum);
12097:         }
12098:         my %access_controls = &get_access_controls($current_perms{$unum.':'.$udom},
12099:                                                    $group,$file_name);
12100:         foreach my $key (keys(%{$access_controls{$file_name}})) {
12101:             my ($num,$scope,$end,$start) = 
12102:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
12103:             if ($scope eq $accesstype) {
12104:                 if (($start <= $now) && ($end == 0)) {
12105:                     if ($accesstype eq 'ip') {
12106:                         if (ref($access_controls{$file_name}{$key}) eq 'HASH') {
12107:                             if (ref($access_controls{$file_name}{$key}{'ip'}) eq 'ARRAY') {
12108:                                 if (grep(/^\Q$ip\E$/,@{$access_controls{$file_name}{$key}{'ip'}})) {
12109:                                     if ($urls{$requrl} eq 'add') {
12110:                                         $action = 'none';
12111:                                         last;
12112:                                     } else {
12113:                                         $action = 'delete';
12114:                                         $aclnum = $num;
12115:                                         last;
12116:                                     }
12117:                                 }
12118:                             }
12119:                         }
12120:                     } elsif ($accesstype eq 'public') {
12121:                         if ($urls{$requrl} eq 'add') {
12122:                             $action = 'none';
12123:                             last;
12124:                         } else {
12125:                             $action = 'delete';
12126:                             $aclnum = $num;
12127:                             last;
12128:                         }
12129:                     }
12130:                 } elsif ($accesstype eq 'public') {
12131:                     $action = 'update';
12132:                     $aclnum = $num;
12133:                     last;
12134:                 }
12135:             }
12136:         }
12137:         if ($action eq 'none') {
12138:             next;
12139:         } else {
12140:             my %changes;
12141:             my $newend = 0;
12142:             my $newstart = $now;
12143:             my $newkey = $aclnum.':'.$accesstype.'_'.$newend.'_'.$newstart;
12144:             $changes{$action}{$newkey} = {
12145:                 type => $accesstype,
12146:                 time => {
12147:                     start => $newstart,
12148:                     end   => $newend,
12149:                 },
12150:             };
12151:             if ($accesstype eq 'ip') {
12152:                 $changes{$action}{$newkey}{'ip'} = [$ip];
12153:             }
12154:             my ($outcome,$deloutcome,$new_values,$translation) =
12155:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
12156:             unless ($outcome eq 'ok') {
12157:                 $errors .= $outcome.' ';
12158:             }
12159:         }
12160:     }
12161:     if ($errors) {
12162:         $errors =~ s/\s$//;
12163:         return $errors;
12164:     } else {
12165:         return 'ok';
12166:     }
12167: }
12168: 
12169: #------------------------------------------------------Get Marked as Read Only
12170: 
12171: sub get_marked_as_readonly {
12172:     my ($domain,$user,$what,$group) = @_;
12173:     my $current_permissions = &get_portfile_permissions($domain,$user);
12174:     my @readonly_files;
12175:     my $cmp1=$what;
12176:     if (ref($what)) { $cmp1=join('',@{$what}) };
12177:     while (my ($file_name,$value) = each(%{$current_permissions})) {
12178:         if (defined($group)) {
12179:             if ($file_name !~ m-^\Q$group\E/-) {
12180:                 next;
12181:             }
12182:         }
12183:         if (ref($value) eq "ARRAY"){
12184:             foreach my $stored_what (@{$value}) {
12185:                 my $cmp2=$stored_what;
12186:                 if (ref($stored_what) eq 'ARRAY') {
12187:                     $cmp2=join('',@{$stored_what});
12188:                 }
12189:                 if ($cmp1 eq $cmp2) {
12190:                     push(@readonly_files, $file_name);
12191:                     last;
12192:                 } elsif (!defined($what)) {
12193:                     push(@readonly_files, $file_name);
12194:                     last;
12195:                 }
12196:             }
12197:         }
12198:     }
12199:     return @readonly_files;
12200: }
12201: #-----------------------------------------------------------Get Marked as Read Only Hash
12202: 
12203: sub get_marked_as_readonly_hash {
12204:     my ($current_permissions,$group,$what) = @_;
12205:     my %readonly_files;
12206:     while (my ($file_name,$value) = each(%{$current_permissions})) {
12207:         if (defined($group)) {
12208:             if ($file_name !~ m-^\Q$group\E/-) {
12209:                 next;
12210:             }
12211:         }
12212:         if (ref($value) eq "ARRAY"){
12213:             foreach my $stored_what (@{$value}) {
12214:                 if (ref($stored_what) eq 'ARRAY') {
12215:                     foreach my $lock_descriptor(@{$stored_what}) {
12216:                         if ($lock_descriptor eq 'graded') {
12217:                             $readonly_files{$file_name} = 'graded';
12218:                         } elsif ($lock_descriptor eq 'handback') {
12219:                             $readonly_files{$file_name} = 'handback';
12220:                         } else {
12221:                             if (!exists($readonly_files{$file_name})) {
12222:                                 $readonly_files{$file_name} = 'locked';
12223:                             }
12224:                         }
12225:                     }
12226:                 } 
12227:             }
12228:         } 
12229:     }
12230:     return %readonly_files;
12231: }
12232: # ------------------------------------------------------------ Unmark as Read Only
12233: 
12234: sub unmark_as_readonly {
12235:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
12236:     # for portfolio submissions, $what contains [$symb,$crsid] 
12237:     my ($domain,$user,$what,$file_name,$group) = @_;
12238:     $file_name = &declutter_portfile($file_name);
12239:     my $symb_crs = $what;
12240:     if (ref($what)) { $symb_crs=join('',@$what); }
12241:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
12242:     my ($tmp)=keys(%current_permissions);
12243:     if ($tmp=~/^error:/) { undef(%current_permissions); }
12244:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
12245:     foreach my $file (@readonly_files) {
12246: 	my $clean_file = &declutter_portfile($file);
12247: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
12248: 	my $current_locks = $current_permissions{$file};
12249:         my @new_locks;
12250:         my @del_keys;
12251:         if (ref($current_locks) eq "ARRAY"){
12252:             foreach my $locker (@{$current_locks}) {
12253:                 my $compare=$locker;
12254:                 if (ref($locker) eq 'ARRAY') {
12255:                     $compare=join('',@{$locker});
12256:                     if ($compare ne $symb_crs) {
12257:                         push(@new_locks, $locker);
12258:                     }
12259:                 }
12260:             }
12261:             if (scalar(@new_locks) > 0) {
12262:                 $current_permissions{$file} = \@new_locks;
12263:             } else {
12264:                 push(@del_keys, $file);
12265:                 &del('file_permissions',\@del_keys, $domain, $user);
12266:                 delete($current_permissions{$file});
12267:             }
12268:         }
12269:     }
12270:     &put('file_permissions',\%current_permissions,$domain,$user);
12271:     return;
12272: }
12273: 
12274: # ------------------------------------------------------------ Directory lister
12275: 
12276: sub dirlist {
12277:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
12278:     $uri=~s/^\///;
12279:     $uri=~s/\/$//;
12280:     my ($udom, $uname);
12281:     if ($getuserdir) {
12282:         $udom = $userdomain;
12283:         $uname = $username;
12284:     } else {
12285:         (undef,$udom,$uname)=split(/\//,$uri);
12286:         if(defined($userdomain)) {
12287:             $udom = $userdomain;
12288:         }
12289:         if(defined($username)) {
12290:             $uname = $username;
12291:         }
12292:     }
12293:     my ($dirRoot,$listing,@listing_results);
12294: 
12295:     $dirRoot = $perlvar{'lonDocRoot'};
12296:     if (defined($getpropath)) {
12297:         $dirRoot = &propath($udom,$uname);
12298:         $dirRoot =~ s/\/$//;
12299:     } elsif (defined($getuserdir)) {
12300:         my $subdir=$uname.'__';
12301:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
12302:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
12303:                    ."/$udom/$subdir/$uname";
12304:     } elsif (defined($alternateRoot)) {
12305:         $dirRoot = $alternateRoot;
12306:     }
12307: 
12308:     if($udom) {
12309:         if($uname) {
12310:             my $uhome = &homeserver($uname,$udom);
12311:             if ($uhome eq 'no_host') {
12312:                 return ([],'no_host');
12313:             }
12314:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
12315:                               .$getuserdir.':'.&escape($dirRoot)
12316:                               .':'.&escape($uname).':'.&escape($udom),$uhome);
12317:             if ($listing eq 'unknown_cmd') {
12318:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
12319:             } else {
12320:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
12321:             }
12322:             if ($listing eq 'unknown_cmd') {
12323:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
12324:                 @listing_results = split(/:/,$listing);
12325:             } else {
12326:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
12327:             }
12328:             if (($listing eq 'no_such_host') || ($listing eq 'con_lost') || 
12329:                 ($listing eq 'rejected') || ($listing eq 'refused') ||
12330:                 ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
12331:                 return ([],$listing);
12332:             } else {
12333:                 return (\@listing_results);
12334:             }
12335:         } elsif(!$alternateRoot) {
12336:             my (%allusers,%listerror);
12337: 	    my %servers = &get_servers($udom,'library');
12338:  	    foreach my $tryserver (keys(%servers)) {
12339:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
12340:                                   &escape($udom),$tryserver);
12341:                 if ($listing eq 'unknown_cmd') {
12342: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
12343: 				      $udom, $tryserver);
12344:                 } else {
12345:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
12346:                 }
12347: 		if ($listing eq 'unknown_cmd') {
12348: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
12349: 				      $udom, $tryserver);
12350: 		    @listing_results = split(/:/,$listing);
12351: 		} else {
12352: 		    @listing_results =
12353: 			map { &unescape($_); } split(/:/,$listing);
12354: 		}
12355:                 if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
12356:                     ($listing eq 'rejected') || ($listing eq 'refused') ||
12357:                     ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
12358:                     $listerror{$tryserver} = $listing;
12359:                 } else {
12360: 		    foreach my $line (@listing_results) {
12361: 			my ($entry) = split(/&/,$line,2);
12362: 			$allusers{$entry} = 1;
12363: 		    }
12364: 		}
12365:             }
12366:             my @alluserslist=();
12367:             foreach my $user (sort(keys(%allusers))) {
12368:                 push(@alluserslist,$user.'&user');
12369:             }
12370: 
12371:             if (!%listerror) {
12372:                 # no errors
12373:                 return (\@alluserslist);
12374:             } elsif (scalar(keys(%servers)) == 1) {
12375:                 # one library server, one error 
12376:                 my ($key) = keys(%listerror);
12377:                 return (\@alluserslist, $listerror{$key});
12378:             } elsif ( grep { $_ eq 'con_lost' } values(%listerror) ) {
12379:                 # con_lost indicates that we might miss data from at least one
12380:                 # library server
12381:                 return (\@alluserslist, 'con_lost');
12382:             } else {
12383:                 # multiple library servers and no con_lost -> data should be
12384:                 # complete. 
12385:                 return (\@alluserslist);
12386:             }
12387: 
12388:         } else {
12389:             return ([],'missing username');
12390:         }
12391:     } elsif(!defined($getpropath)) {
12392:         my $path = $perlvar{'lonDocRoot'}.'/res/'; 
12393:         my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
12394:         return (\@all_domains);
12395:     } else {
12396:         return ([],'missing domain');
12397:     }
12398: }
12399: 
12400: # --------------------------------------------- GetFileTimestamp
12401: # This function utilizes dirlist and returns the date stamp for
12402: # when it was last modified.  It will also return an error of -1
12403: # if an error occurs
12404: 
12405: sub GetFileTimestamp {
12406:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
12407:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
12408:     $studentName   = &LONCAPA::clean_username($studentName);
12409:     my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
12410:                                     undef,$getuserdir);
12411:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
12412:         return -1;
12413:     }
12414:     if (ref($fileref) eq 'ARRAY') {
12415:         my @stats = split('&',$fileref->[0]);
12416:         # @stats contains first the filename, then the stat output
12417:         return $stats[10]; # so this is 10 instead of 9.
12418:     } else {
12419:         return -1;
12420:     }
12421: }
12422: 
12423: sub stat_file {
12424:     my ($uri) = @_;
12425:     $uri = &clutter_with_no_wrapper($uri);
12426: 
12427:     my ($udom,$uname,$file);
12428:     if ($uri =~ m-^/(uploaded|editupload)/-) {
12429: 	($udom,$uname,$file) =
12430: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
12431: 	$file = 'userfiles/'.$file;
12432:     }
12433:     if ($uri =~ m-^/res/-) {
12434: 	($udom,$uname) = 
12435: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
12436: 	$file = $uri;
12437:     }
12438: 
12439:     if (!$udom || !$uname || !$file) {
12440: 	# unable to handle the uri
12441: 	return ();
12442:     }
12443:     my $getpropath;
12444:     if ($file =~ /^userfiles\//) {
12445:         $getpropath = 1;
12446:     }
12447:     my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
12448:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
12449:         return ();
12450:     } else {
12451:         if (ref($listref) eq 'ARRAY') {
12452:             my @stats = split('&',$listref->[0]);
12453: 	    shift(@stats); #filename is first
12454: 	    return @stats;
12455:         }
12456:     }
12457:     return ();
12458: }
12459: 
12460: # --------------------------------------------------------- recursedirs
12461: # Recursive function to traverse either a specific user's Authoring Space
12462: # or corresponding Published Resource Space, and populate the hash ref:
12463: # $dirhashref with URLs of all directories, and if $filehashref hash
12464: # ref arg is provided, the URLs of any files, excluding versioned, .meta,
12465: # or .rights files in resource space, and .meta, .save, .log, .bak and
12466: # .rights files in Authoring Space.
12467: #
12468: # Inputs:
12469: #
12470: # $is_home - true if current server is home server for user's space
12471: # $recurse - if true will also traverse subdirectories recursively
12472: # $include - reference to hash containing allowed file extensions.  If provided,
12473: #             files which do not have a matching extension will be ignored.
12474: # $exclude - reference to hash containing excluded file extensions.  If provided,
12475: #             files which have a matching extension will be ignored.
12476: # $nonemptydir - if true, will only populate $fileshashref hash entry for a particular
12477: #             directory with first file found (with acceptable extension).
12478: # $addtopdir - if true, set $dirhashref->{'/'} = 1 
12479: # $toppath - Top level directory (i.e., /res/$dom/$uname or /priv/$dom/$uname
12480: # $relpath - Current path (relative to top level).
12481: # $dirhashref - reference to hash to populate with URLs of directories (Required)
12482: # $filehashref - reference to hash to populate with URLs of files (Optional)
12483: #
12484: # Returns: nothing
12485: #
12486: # Side Effects: populates $dirhashref, and $filehashref (if provided).
12487: #
12488: # Currently used by interface/londocs.pm to create linked select boxes for
12489: # directory and filename to import a Course "Author" resource into a course, and
12490: # also to create linked select boxes for Authoring Space and Directory to choose
12491: # save location for creation of a new "standard" problem from the Course Editor.
12492: #
12493: 
12494: sub recursedirs {
12495:     my ($is_home,$recurse,$include,$exclude,$nonemptydir,$addtopdir,$toppath,$relpath,$dirhashref,$filehashref) = @_;
12496:     return unless (ref($dirhashref) eq 'HASH');
12497:     my $docroot = $perlvar{'lonDocRoot'};
12498:     my $currpath = $docroot.$toppath;
12499:     if ($relpath ne '') {
12500:         $currpath .= "/$relpath";
12501:     }
12502:     my ($savefile,$checkinc,$checkexc);
12503:     if (ref($filehashref)) {
12504:         $savefile = 1;
12505:     }
12506:     if (ref($include) eq 'HASH') {
12507:         $checkinc = 1;
12508:     }
12509:     if (ref($exclude) eq 'HASH') {
12510:         $checkexc = 1;
12511:     }
12512:     if ($is_home) {
12513:         if ((-e $currpath) && (opendir(my $dirh,$currpath))) {
12514:             my $filecount = 0;
12515:             foreach my $item (sort { lc($a) cmp lc($b) } grep(!/^\.+$/,readdir($dirh))) {
12516:                 next if ($item eq '');
12517:                 if (-d "$currpath/$item") {
12518:                     my $newpath;
12519:                     if ($relpath ne '') {
12520:                         $newpath = "$relpath/$item";
12521:                     } else {
12522:                         $newpath = $item;
12523:                     }
12524:                     $dirhashref->{&Apache::lonlocal::js_escape($newpath)} = 1;
12525:                     if ($recurse) {
12526:                         &recursedirs($is_home,$recurse,$include,$exclude,$nonemptydir,$addtopdir,$toppath,$newpath,$dirhashref,$filehashref);
12527:                     }
12528:                 } elsif (($savefile) || ($relpath eq '')) {
12529:                     next if ($nonemptydir && $filecount);
12530:                     if ($checkinc || $checkexc) {
12531:                         my ($extension) = ($item =~ /\.(\w+)$/);
12532:                         if ($checkinc) {
12533:                             next unless ($extension && $include->{$extension});
12534:                         }
12535:                         if ($checkexc) {
12536:                             next if ($extension && $exclude->{$extension});
12537:                         }
12538:                     }
12539:                     if (($relpath eq '') && (!exists($dirhashref->{'/'}))) {
12540:                         $dirhashref->{'/'} = 1;
12541:                     }
12542:                     if ($savefile) {
12543:                         if ($relpath eq '') {
12544:                             $filehashref->{'/'}{$item} = 1;
12545:                         } else {
12546:                             $filehashref->{&Apache::lonlocal::js_escape($relpath)}{$item} = 1;
12547:                         }
12548:                     }
12549:                     $filecount ++;
12550:                 }
12551:             }
12552:             closedir($dirh);
12553:         }
12554:     } else {
12555:         my ($dirlistref,$listerror) =
12556:             &dirlist($toppath.$relpath);
12557:         my @dir_lines;
12558:         my $dirptr=16384;
12559:         if (ref($dirlistref) eq 'ARRAY') {
12560:             my $filecount = 0;
12561:             foreach my $dir_line (sort
12562:                               {
12563:                                   my ($afile)=split('&',$a,2);
12564:                                   my ($bfile)=split('&',$b,2);
12565:                                   return (lc($afile) cmp lc($bfile));
12566:                               } (@{$dirlistref})) {
12567:                 my ($item,$dom,undef,$testdir,undef,undef,undef,undef,$size,undef,$mtime,undef,undef,undef,$obs,undef) =
12568:                     split(/\&/,$dir_line,16);
12569:                 $item =~ s/\s+$//;
12570:                 next if (($item =~ /^\.\.?$/) || ($obs));
12571:                 if ($dirptr&$testdir) {
12572:                     my $newpath;
12573:                     if ($relpath) {
12574:                         $newpath = "$relpath/$item";
12575:                     } else {
12576:                         $newpath = $item;
12577:                     }
12578:                     $dirhashref->{&Apache::lonlocal::js_escape($newpath)} = 1;
12579:                     if ($recurse) {
12580:                         &recursedirs($is_home,$recurse,$include,$exclude,$nonemptydir,$addtopdir,$toppath,$newpath,$dirhashref,$filehashref);
12581:                     }
12582:                 } elsif (($savefile) || ($relpath eq '')) {
12583:                     next if ($nonemptydir && $filecount);
12584:                     if ($checkinc || $checkexc) {
12585:                         my $extension;
12586:                         if ($checkinc) {
12587:                             next unless ($extension && $include->{$extension});
12588:                         }
12589:                         if ($checkexc) {
12590:                             next if ($extension && $exclude->{$extension});
12591:                         }
12592:                     }
12593:                     if (($relpath eq '') && (!exists($dirhashref->{'/'}))) {
12594:                         $dirhashref->{'/'} = 1;
12595:                     }
12596:                     if ($savefile) {
12597:                         if ($relpath eq '') {
12598:                             $filehashref->{'/'}{$item} = 1;
12599:                         } else {
12600:                             $filehashref->{&Apache::lonlocal::js_escape($relpath)}{$item} = 1;
12601:                         }
12602:                     }
12603:                     $filecount ++; 
12604:                 }
12605:             }
12606:         }
12607:     }
12608:     if ($addtopdir) {
12609:         if (($relpath eq '') && (!exists($dirhashref->{'/'}))) {
12610:             $dirhashref->{'/'} = 1;
12611:         }
12612:     }
12613:     return;
12614: }
12615: 
12616: sub priv_exclude {
12617:     return {
12618:              meta => 1,
12619:              save => 1,
12620:              log => 1,
12621:              bak => 1,
12622:              rights => 1,
12623:              DS_Store => 1,
12624:            };
12625: }
12626: 
12627: # -------------------------------------------------------- Value of a Condition
12628: 
12629: # gets the value of a specific preevaluated condition
12630: #    stored in the string  $env{user.state.<cid>}
12631: # or looks up a condition reference in the bighash and if if hasn't
12632: # already been evaluated recurses into docondval to get the value of
12633: # the condition, then memoizing it to 
12634: #   $env{user.state.<cid>.<condition>}
12635: sub directcondval {
12636:     my $number=shift;
12637:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
12638: 	&Apache::lonuserstate::evalstate();
12639:     }
12640:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
12641: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
12642:     } elsif ($number =~ /^_/) {
12643: 	my $sub_condition;
12644: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
12645: 		&GDBM_READER(),0640)) {
12646: 	    $sub_condition=$bighash{'conditions'.$number};
12647: 	    untie(%bighash);
12648: 	}
12649: 	my $value = &docondval($sub_condition);
12650: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
12651: 	return $value;
12652:     }
12653:     if ($env{'user.state.'.$env{'request.course.id'}}) {
12654:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
12655:     } else {
12656:        return 2;
12657:     }
12658: }
12659: 
12660: # get the collection of conditions for this resource
12661: sub condval {
12662:     my $condidx=shift;
12663:     my $allpathcond='';
12664:     foreach my $cond (split(/\|/,$condidx)) {
12665: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
12666: 	    $allpathcond.=
12667: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
12668: 	}
12669:     }
12670:     $allpathcond=~s/\|$//;
12671:     return &docondval($allpathcond);
12672: }
12673: 
12674: #evaluates an expression of conditions
12675: sub docondval {
12676:     my ($allpathcond) = @_;
12677:     my $result=0;
12678:     if ($env{'request.course.id'}
12679: 	&& defined($allpathcond)) {
12680: 	my $operand='|';
12681: 	my @stack;
12682: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
12683: 	    if ($chunk eq '(') {
12684: 		push @stack,($operand,$result);
12685: 	    } elsif ($chunk eq ')') {
12686: 		my $before=pop @stack;
12687: 		if (pop @stack eq '&') {
12688: 		    $result=$result>$before?$before:$result;
12689: 		} else {
12690: 		    $result=$result>$before?$result:$before;
12691: 		}
12692: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
12693: 		$operand=$chunk;
12694: 	    } else {
12695: 		my $new=directcondval($chunk);
12696: 		if ($operand eq '&') {
12697: 		    $result=$result>$new?$new:$result;
12698: 		} else {
12699: 		    $result=$result>$new?$result:$new;
12700: 		}
12701: 	    }
12702: 	}
12703:     }
12704:     return $result;
12705: }
12706: 
12707: # ---------------------------------------------------- Devalidate courseresdata
12708: 
12709: sub devalidatecourseresdata {
12710:     my ($coursenum,$coursedomain)=@_;
12711:     my $hashid=$coursenum.':'.$coursedomain;
12712:     &devalidate_cache_new('courseres',$hashid);
12713: }
12714: 
12715: 
12716: # --------------------------------------------------- Course Resourcedata Query
12717: #
12718: #  Parameters:
12719: #      $coursenum    - Number of the course.
12720: #      $coursedomain - Domain at which the course was created.
12721: #  Returns:
12722: #     A hash of the course parameters along (I think) with timestamps
12723: #     and version info.
12724: 
12725: sub get_courseresdata {
12726:     my ($coursenum,$coursedomain)=@_;
12727:     my $coursehom=&homeserver($coursenum,$coursedomain);
12728:     my $hashid=$coursenum.':'.$coursedomain;
12729:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
12730:     my %dumpreply;
12731:     unless (defined($cached)) {
12732: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
12733: 	$result=\%dumpreply;
12734: 	my ($tmp) = keys(%dumpreply);
12735: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
12736: 	    &do_cache_new('courseres',$hashid,$result,600);
12737: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
12738: 	    return $tmp;
12739: 	} elsif ($tmp =~ /^(error)/) {
12740: 	    $result=undef;
12741: 	    &do_cache_new('courseres',$hashid,$result,600);
12742: 	}
12743:     }
12744:     return $result;
12745: }
12746: 
12747: sub devalidateuserresdata {
12748:     my ($uname,$udom)=@_;
12749:     my $hashid="$udom:$uname";
12750:     &devalidate_cache_new('userres',$hashid);
12751: }
12752: 
12753: sub get_userresdata {
12754:     my ($uname,$udom)=@_;
12755:     #most student don\'t have any data set, check if there is some data
12756:     if (&EXT_cache_status($udom,$uname)) { return undef; }
12757: 
12758:     my $hashid="$udom:$uname";
12759:     my ($result,$cached)=&is_cached_new('userres',$hashid);
12760:     if (!defined($cached)) {
12761: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
12762: 	$result=\%resourcedata;
12763: 	&do_cache_new('userres',$hashid,$result,600);
12764:     }
12765:     my ($tmp)=keys(%$result);
12766:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
12767: 	return $result;
12768:     }
12769:     #error 2 occurs when the .db doesn't exist
12770:     if ($tmp!~/error: 2 /) {
12771:         if ((!defined($cached)) || ($tmp ne 'con_lost')) {
12772: 	    &logthis("<font color=\"blue\">WARNING:".
12773: 		     " Trying to get resource data for ".
12774: 		     $uname." at ".$udom.": ".
12775: 		     $tmp."</font>");
12776:         }
12777:     } elsif ($tmp=~/error: 2 /) {
12778: 	#&EXT_cache_set($udom,$uname);
12779: 	&do_cache_new('userres',$hashid,undef,600);
12780: 	undef($tmp); # not really an error so don't send it back
12781:     }
12782:     return $tmp;
12783: }
12784: #----------------------------------------------- resdata - return resource data
12785: #  Purpose:
12786: #    Return resource data for either users or for a course.
12787: #  Parameters:
12788: #     $name      - Course/user name.
12789: #     $domain    - Name of the domain the user/course is registered on.
12790: #     $type      - Type of thing $name is (must be 'course' or 'user')
12791: #     $mapp      - decluttered URL of enclosing map  
12792: #     $recursed  - Ref to scalar -- set to 1, if nested maps have been recursed.
12793: #     $recurseup - Ref to array of map URLs, starting with map containing
12794: #                  $mapp up through hierarchy of nested maps to top level map.  
12795: #     $courseid  - CourseID (first part of param identifier).
12796: #     $modifier  - Middle part of param identifier.
12797: #     $what      - Last part of param identifier.
12798: #     @which     - Array of names of resources desired.
12799: #  Returns:
12800: #     The value of the first reasource in @which that is found in the
12801: #     resource hash.
12802: #  Exceptional Conditions:
12803: #     If the $type passed in is not valid (not the string 'course' or 
12804: #     'user', an undefined  reference is returned.
12805: #     If none of the resources are found, an undef is returned
12806: sub resdata {
12807:     my ($name,$domain,$type,$mapp,$recursed,$recurseup,$courseid,
12808:         $modifier,$what,@which)=@_;
12809:     my $result;
12810:     if ($type eq 'course') {
12811: 	$result=&get_courseresdata($name,$domain);
12812:     } elsif ($type eq 'user') {
12813: 	$result=&get_userresdata($name,$domain);
12814:     }
12815:     if (!ref($result)) { return $result; }    
12816:     foreach my $item (@which) {
12817:         if ($item->[1] eq 'course') {
12818:             if ((ref($recurseup) eq 'ARRAY') && (ref($recursed) eq 'SCALAR')) {
12819:                 unless ($$recursed) {
12820:                     @{$recurseup} = &get_map_hierarchy($mapp,$courseid);
12821:                     $$recursed = 1;
12822:                 }
12823:                 foreach my $item (@${recurseup}) {
12824:                     my $norecursechk=$courseid.$modifier.$item.'___(all).'.$what;
12825:                     last if (defined($result->{$norecursechk}));
12826:                     my $recursechk=$courseid.$modifier.$item.'___(rec).'.$what;
12827:                     if (defined($result->{$recursechk})) { return [$result->{$recursechk},'map']; }
12828:                 }
12829:             }
12830:         }
12831:         if (defined($result->{$item->[0]})) {
12832: 	    return [$result->{$item->[0]},$item->[1]];
12833: 	}
12834:     }
12835:     return undef;
12836: }
12837: 
12838: sub get_domain_lti {
12839:     my ($cdom,$context) = @_;
12840:     my ($name,$cachename,%lti);
12841:     if ($context eq 'consumer') {
12842:         $name = 'ltitools';
12843:     } elsif ($context eq 'provider') {
12844:         $name = 'lti';
12845:     } elsif ($context eq 'linkprot') {
12846:         $name = 'ltisec';
12847:     } else {
12848:         return %lti;
12849:     }
12850:     if ($context eq 'linkprot') {
12851:         $cachename = $context;
12852:     } else {
12853:         $cachename = $name;
12854:     }
12855:     my ($result,$cached)=&is_cached_new($cachename,$cdom);
12856:     if (defined($cached)) {
12857:         if (ref($result) eq 'HASH') {
12858:             %lti = %{$result};
12859:         }
12860:     } else {
12861:         my %domconfig = &get_dom('configuration',[$name],$cdom);
12862:         if (ref($domconfig{$name}) eq 'HASH') {
12863:             if ($context eq 'linkprot') {
12864:                 if (ref($domconfig{$name}{'linkprot'}) eq 'HASH') {
12865:                     %lti = %{$domconfig{$name}{'linkprot'}};
12866:                 }
12867:             } else {
12868:                 %lti = %{$domconfig{$name}};
12869:             }
12870:         }
12871:         my $cachetime = 24*60*60;
12872:         &do_cache_new($cachename,$cdom,\%lti,$cachetime);
12873:     }
12874:     return %lti;
12875: }
12876: 
12877: sub get_course_lti {
12878:     my ($cnum,$cdom,$context) = @_;
12879:     my ($name,$cachename,%lti);
12880:     if ($context eq 'consumer') {
12881:         $name = 'ltitools';
12882:         $cachename = 'courseltitools';
12883:     } elsif ($context eq 'provider') {
12884:         $name = 'lti';
12885:         $cachename = 'courselti';
12886:     } else {
12887:         return %lti;
12888:     }
12889:     my $hashid=$cdom.'_'.$cnum;
12890:     my ($result,$cached)=&is_cached_new($cachename,$hashid);
12891:     if (defined($cached)) {
12892:         if (ref($result) eq 'HASH') {
12893:             %lti = %{$result};
12894:         }
12895:     } else {
12896:         %lti = &dump($name,$cdom,$cnum,undef,undef,undef,1);
12897:         my $cachetime = 24*60*60;
12898:         &do_cache_new($cachename,$hashid,\%lti,$cachetime);
12899:     }
12900:     return %lti;
12901: }
12902: 
12903: sub courselti_itemid {
12904:     my ($cnum,$cdom,$url,$method,$params,$context) = @_;
12905:     my ($chome,$itemid);
12906:     $chome = &homeserver($cnum,$cdom);
12907:     return if ($chome eq 'no_host');
12908:     if (ref($params) eq 'HASH') {
12909:         my $rep;
12910:         if (grep { $_ eq $chome } current_machine_ids()) {
12911:             $rep = LONCAPA::Lond::crslti_itemid($cdom,$cnum,$url,$method,$params,$perlvar{'lonVersion'});
12912:         } else {
12913:             my $escurl = &escape($url);
12914:             my $escmethod = &escape($method);
12915:             my $items = &freeze_escape($params);
12916:             $rep = &reply("encrypt:lti:$cdom:$cnum:$context:$escurl:$escmethod:$items",$chome);
12917:         }
12918:         unless (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
12919:                 ($rep eq 'unknown_cmd')) {
12920:             $itemid = $rep;
12921:         }
12922:     }
12923:     return $itemid;
12924: }
12925: 
12926: sub domainlti_itemid {
12927:     my ($cdom,$url,$method,$params,$context) = @_;
12928:     my ($primary_id,$itemid);
12929:     $primary_id = &domain($cdom,'primary');
12930:     return if ($primary_id eq '');
12931:     if (ref($params) eq 'HASH') {
12932:         my $rep;
12933:         if (grep { $_ eq $primary_id } current_machine_ids()) {
12934:             $rep = LONCAPA::Lond::domlti_itemid($cdom,$context,$url,$method,$params,$perlvar{'lonVersion'});
12935:         } else {
12936:             my $cnum = '';
12937:             my $escurl = &escape($url);
12938:             my $escmethod = &escape($method);
12939:             my $items = &freeze_escape($params);
12940:             $rep = &reply("encrypt:lti:$cdom:$cnum:$context:$escurl:$escmethod:$items",$primary_id);
12941:         }
12942:         unless (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
12943:                 ($rep eq 'unknown_cmd')) {
12944:             $itemid = $rep;
12945:         }
12946:     }
12947:     return $itemid;
12948: }
12949: 
12950: sub get_ltitools_id {
12951:     my ($context,$cdom,$cnum,$title) = @_;
12952:     my ($lockhash,$tries,$gotlock,$id,$error);
12953: 
12954:     # get lock on ltitools db
12955:     $lockhash = {
12956:                    lock => $env{'user.name'}.
12957:                            ':'.$env{'user.domain'},
12958:                 };
12959:     $tries = 0;
12960:     if ($context eq 'domain') {
12961:         $gotlock = &newput_dom('ltitools',$lockhash,$cdom);
12962:     } else {
12963:         $gotlock = &newput('ltitools',$lockhash,$cdom,$cnum);
12964:     }
12965:     while (($gotlock ne 'ok') && ($tries<10)) {
12966:         $tries ++;
12967:         sleep (0.1);
12968:         if ($context eq 'domain') {
12969:             $gotlock = &newput_dom('ltitools',$lockhash,$cdom);
12970:         } else {
12971:             $gotlock = &newput('ltitools',$lockhash,$cdom,$cnum);
12972:         }
12973:     }
12974:     if ($gotlock eq 'ok') {
12975:         my %currids;
12976:         if ($context eq 'domain') {
12977:             %currids = &dump_dom('ltitools',$cdom);
12978:         } else {
12979:             %currids = &dump('ltitools',$cdom,$cnum);
12980:         }
12981:         if ($currids{'lock'}) {
12982:             delete($currids{'lock'});
12983:             if (keys(%currids)) {
12984:                 my @curr = sort { $a <=> $b } keys(%currids);
12985:                 if ($curr[-1] =~ /^\d+$/) {
12986:                     $id = 1 + $curr[-1];
12987:                 }
12988:             } else {
12989:                 $id = 1;
12990:             }
12991:             if ($id) {
12992:                 if ($context eq 'domain') {
12993:                     unless (&newput_dom('ltitools',{ $id => $title },$cdom) eq 'ok') {
12994:                         $error = 'nostore';
12995:                     }
12996:                 } else {
12997:                     unless (&newput('ltitools',{ $id => $title },$cdom,$cnum) eq 'ok') {
12998:                         $error = 'nostore';
12999:                     }
13000:                 }
13001:             } else {
13002:                 $error = 'nonumber';
13003:             }
13004:         }
13005:         my $dellockoutcome;
13006:         if ($context eq 'domain') {
13007:             $dellockoutcome = &del_dom('ltitools',['lock'],$cdom);
13008:         } else {
13009:             $dellockoutcome = &del('ltitools',['lock'],$cdom,$cnum);
13010:         }
13011:     } else {
13012:         $error = 'nolock';
13013:     }
13014:     return ($id,$error);
13015: }
13016: 
13017: sub count_supptools {
13018:     my ($cnum,$cdom,$ignorecache,$reload)=@_;
13019:     my $hashid=$cnum.':'.$cdom;
13020:     my ($numexttools,$cached);
13021:     unless ($ignorecache) {
13022:         ($numexttools,$cached) = &is_cached_new('supptools',$hashid);
13023:     }
13024:     unless (defined($cached)) {
13025:         my $chome=&homeserver($cnum,$cdom);
13026:         $numexttools = 0;
13027:         unless ($chome eq 'no_host') {
13028:             my ($supplemental) = &Apache::loncommon::get_supplemental($cnum,$cdom,$reload);
13029:             if (ref($supplemental) eq 'HASH') {
13030:                 if ((ref($supplemental->{'ids'}) eq 'HASH') && (ref($supplemental->{'hidden'}) eq 'HASH')) {
13031:                     foreach my $key (keys(%{$supplemental->{'ids'}})) {
13032:                         if ($key =~ m{^/adm/$cdom/$cnum/\d+/ext\.tool$}) {
13033:                             $numexttools ++;
13034:                         }
13035:                     }
13036:                 }
13037:             }
13038:         }
13039:         &do_cache_new('supptools',$hashid,$numexttools,600);
13040:     }
13041:     return $numexttools;
13042: }
13043: 
13044: sub has_unhidden_suppfiles {
13045:     my ($cnum,$cdom,$ignorecache,$possdel)=@_;
13046:     my $hashid=$cnum.':'.$cdom;
13047:     my ($showsupp,$cached);
13048:     unless ($ignorecache) {
13049:         ($showsupp,$cached) = &is_cached_new('showsupp',$hashid);
13050:     }
13051:     unless (defined($cached)) {
13052:         my $chome=&homeserver($cnum,$cdom);
13053:         unless ($chome eq 'no_host') {
13054:             my ($supplemental) = &Apache::loncommon::get_supplemental($cnum,$cdom,$ignorecache,$possdel);
13055:             if (ref($supplemental) eq 'HASH') {
13056:                 if ((ref($supplemental->{'ids'}) eq 'HASH') && (ref($supplemental->{'hidden'}) eq 'HASH')) {
13057:                     foreach my $key (keys(%{$supplemental->{'ids'}})) {
13058:                         next if ($key =~ /\.sequence$/);
13059:                         if (ref($supplemental->{'ids'}->{$key}) eq 'ARRAY') {
13060:                             foreach my $id (@{$supplemental->{'ids'}->{$key}}) {
13061:                                 unless ($supplemental->{'hidden'}->{$id}) {
13062:                                     $showsupp = 1;
13063:                                     last;
13064:                                 }
13065:                             }
13066:                         }
13067:                         last if ($showsupp);
13068:                     }
13069:                 }
13070:             }
13071:         }
13072:         &do_cache_new('showsupp',$hashid,$showsupp,600);
13073:     }
13074:     return $showsupp;
13075: }
13076: 
13077: #
13078: # EXT resource caching routines
13079: #
13080: 
13081: {
13082: # Cache (5 seconds) of map hierarchy for speedup of navmaps display
13083: #
13084: # The course for which we cache
13085: my $cachedmapkey='';
13086: # The cached recursive maps for this course
13087: my %cachedmaps=();
13088: # When this was last done
13089: my $cachedmaptime='';
13090: 
13091: sub clear_EXT_cache_status {
13092:     &delenv('cache.EXT.');
13093: }
13094: 
13095: sub EXT_cache_status {
13096:     my ($target_domain,$target_user) = @_;
13097:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
13098:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
13099:         # We know already the user has no data
13100:         return 1;
13101:     } else {
13102:         return 0;
13103:     }
13104: }
13105: 
13106: sub EXT_cache_set {
13107:     my ($target_domain,$target_user) = @_;
13108:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
13109:     #&appenv({$cachename => time});
13110: }
13111: 
13112: # --------------------------------------------------------- Value of a Variable
13113: sub EXT {
13114: 
13115:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse,$cid,$recurseupref)=@_;
13116:     unless ($varname) { return ''; }
13117:     #get real user name/domain, courseid and symb
13118:     my $courseid;
13119:     my $publicuser;
13120:     if ($symbparm) {
13121: 	$symbparm=&get_symb_from_alias($symbparm);
13122:     }
13123:     if (!($uname && $udom)) {
13124:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
13125:       if (!$symbparm) {	$symbparm=$cursymb; }
13126:     } else {
13127: 	$courseid=$env{'request.course.id'};
13128:     }
13129:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
13130:     my $rest;
13131:     if (defined($therest[0])) {
13132:        $rest=join('.',@therest);
13133:     } else {
13134:        $rest='';
13135:     }
13136: 
13137:     my $qualifierrest=$qualifier;
13138:     if ($rest) { $qualifierrest.='.'.$rest; }
13139:     my $spacequalifierrest=$space;
13140:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
13141:     if ($realm eq 'user') {
13142: # --------------------------------------------------------------- user.resource
13143: 	if ($space eq 'resource') {
13144: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
13145: 		  || defined($Apache::lonhomework::parsing_a_task))
13146: 		 &&
13147: 		 ($symbparm eq &symbread()) ) {
13148: 		# if we are in the middle of processing the resource the
13149: 		# get the value we are planning on committing
13150:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
13151:                     return $Apache::lonhomework::results{$qualifierrest};
13152:                 } else {
13153:                     return $Apache::lonhomework::history{$qualifierrest};
13154:                 }
13155: 	    } else {
13156: 		my %restored;
13157: 		if ($publicuser || $env{'request.state'} eq 'construct') {
13158: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
13159: 		} else {
13160: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
13161: 		}
13162: 		return $restored{$qualifierrest};
13163: 	    }
13164: # ----------------------------------------------------------------- user.access
13165:         } elsif ($space eq 'access') {
13166: 	    # FIXME - not supporting calls for a specific user
13167:             return &allowed($qualifier,$rest);
13168: # ------------------------------------------ user.preferences, user.environment
13169:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
13170: 	    if (($uname eq $env{'user.name'}) &&
13171: 		($udom eq $env{'user.domain'})) {
13172: 		return $env{join('.',('environment',$qualifierrest))};
13173: 	    } else {
13174: 		my %returnhash;
13175: 		if (!$publicuser) {
13176: 		    %returnhash=&userenvironment($udom,$uname,
13177: 						 $qualifierrest);
13178: 		}
13179: 		return $returnhash{$qualifierrest};
13180: 	    }
13181: # ----------------------------------------------------------------- user.course
13182:         } elsif ($space eq 'course') {
13183: 	    # FIXME - not supporting calls for a specific user
13184:             return $env{join('.',('request.course',$qualifier))};
13185: # ------------------------------------------------------------------- user.role
13186:         } elsif ($space eq 'role') {
13187: 	    # FIXME - not supporting calls for a specific user
13188:             my ($role,$where)=split(/\./,$env{'request.role'});
13189:             if ($qualifier eq 'value') {
13190: 		return $role;
13191:             } elsif ($qualifier eq 'extent') {
13192:                 return $where;
13193:             }
13194: # ----------------------------------------------------------------- user.domain
13195:         } elsif ($space eq 'domain') {
13196:             return $udom;
13197: # ------------------------------------------------------------------- user.name
13198:         } elsif ($space eq 'name') {
13199:             return $uname;
13200: # ---------------------------------------------------- Any other user namespace
13201:         } else {
13202: 	    my %reply;
13203: 	    if (!$publicuser) {
13204: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
13205: 	    }
13206: 	    return $reply{$qualifierrest};
13207:         }
13208:     } elsif ($realm eq 'query') {
13209: # ---------------------------------------------- pull stuff out of query string
13210:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
13211: 						[$spacequalifierrest]);
13212: 	return $env{'form.'.$spacequalifierrest}; 
13213:    } elsif ($realm eq 'request') {
13214: # ------------------------------------------------------------- request.browser
13215:         if ($space eq 'browser') {
13216:             return $env{'browser.'.$qualifier};
13217: # ------------------------------------------------------------ request.filename
13218:         } else {
13219:             return $env{'request.'.$spacequalifierrest};
13220:         }
13221:     } elsif ($realm eq 'course') {
13222: # ---------------------------------------------------------- course.description
13223:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
13224:     } elsif ($realm eq 'resource') {
13225: 
13226: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
13227: 	    if (!$symbparm) { $symbparm=&symbread(); }
13228: 	}
13229: 
13230:         if ($qualifier eq '') {
13231: 	    if ($space eq 'title') {
13232: 	        if (!$symbparm) { $symbparm = $env{'request.filename'}; }
13233: 	        return &gettitle($symbparm);
13234: 	    }
13235: 	
13236: 	    if ($space eq 'map') {
13237: 	        my ($map) = &decode_symb($symbparm);
13238: 	        return &symbread($map);
13239: 	    }
13240:             if ($space eq 'maptitle') {
13241:                 my ($map) = &decode_symb($symbparm);
13242:                 return &gettitle($map);
13243:             }
13244: 	    if ($space eq 'filename') {
13245: 	        if ($symbparm) {
13246: 		    return &clutter((&decode_symb($symbparm))[2]);
13247: 	        }
13248: 	        return &hreflocation('',$env{'request.filename'});
13249: 	    }
13250: 
13251:             if ((defined($courseid)) && ($courseid eq $env{'request.course.id'}) && $symbparm) {
13252:                 if ($space eq 'visibleparts') {
13253:                     my $navmap = Apache::lonnavmaps::navmap->new();
13254:                     my $item;
13255:                     if (ref($navmap)) {
13256:                         my $res = $navmap->getBySymb($symbparm);
13257:                         my $parts = $res->parts();
13258:                         if (ref($parts) eq 'ARRAY') {
13259:                             $item = join(',',@{$parts});
13260:                         }
13261:                         undef($navmap);
13262:                     }
13263:                     return $item;
13264:                 }
13265:             }
13266:         }
13267: 
13268: 	my ($section, $group, @groups, @recurseup, $recursed);
13269:         if (ref($recurseupref) eq 'ARRAY') {
13270:             @recurseup = @{$recurseupref};
13271:             $recursed = 1;
13272:         }
13273: 	my ($courselevelm,$courseleveli,$courselevel,$mapp);
13274:         if (($courseid eq '') && ($cid)) {
13275:             $courseid = $cid;
13276:         }
13277: 	if (($symbparm && $courseid) && 
13278: 	    (($courseid eq $env{'request.course.id'}) || ($courseid eq $cid)))  {
13279: 
13280: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
13281: 
13282: # ----------------------------------------------------- Cascading lookup scheme
13283: 	    my $symbp=$symbparm;
13284: 	    $mapp=&deversion((&decode_symb($symbp))[0]);
13285: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
13286:             my $recurseparm=$mapp.'___(rec).'.$spacequalifierrest;
13287: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
13288: 	    if (($env{'user.name'} eq $uname) &&
13289: 		($env{'user.domain'} eq $udom)) {
13290: 		$section=$env{'request.course.sec'};
13291:                 @groups = split(/:/,$env{'request.course.groups'});  
13292:                 @groups=&sort_course_groups($courseid,@groups); 
13293: 	    } else {
13294: 		if (! defined($usection)) {
13295: 		    $section=&getsection($udom,$uname,$courseid);
13296: 		} else {
13297: 		    $section = $usection;
13298: 		}
13299:                 @groups = &get_users_groups($udom,$uname,$courseid);
13300: 	    }
13301: 
13302: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
13303: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
13304:             my $secleveli=$courseid.'.['.$section.'].'.$recurseparm;
13305: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
13306: 
13307: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
13308: 	    my $courselevelr=$courseid.'.'.$symbparm;
13309:             $courseleveli=$courseid.'.'.$recurseparm;
13310: 	    $courselevelm=$courseid.'.'.$mapparm;
13311: 
13312: # ----------------------------------------------------------- first, check user
13313: 
13314: 	    my $userreply=&resdata($uname,$udom,'user',$mapp,\$recursed,
13315:                                    \@recurseup,$courseid,'.',$spacequalifierrest, 
13316: 				       ([$courselevelr,'resource'],
13317: 					[$courselevelm,'map'     ],
13318:                                         [$courseleveli,'map'     ],
13319: 					[$courselevel, 'course'  ]));
13320: 	    if (defined($userreply)) { return &get_reply($userreply); }
13321: 
13322: # ------------------------------------------------ second, check some of course
13323:             my $coursereply;
13324:             if (@groups > 0) {
13325:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
13326:                                        $recurseparm,$mapparm,$spacequalifierrest,
13327:                                        $mapp,\$recursed,\@recurseup);
13328:                 if (defined($coursereply)) { return &get_reply($coursereply); } 
13329:             }
13330: 
13331: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
13332: 				  $env{'course.'.$courseid.'.domain'},
13333: 				  'course',$mapp,\$recursed,\@recurseup,
13334:                                   $courseid,'.['.$section.'].',$spacequalifierrest,
13335: 				  ([$seclevelr,   'resource'],
13336: 				   [$seclevelm,   'map'     ],
13337:                                    [$secleveli,   'map'     ],
13338: 				   [$seclevel,    'course'  ],
13339: 				   [$courselevelr,'resource']));
13340: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
13341: 
13342: # ------------------------------------------------------ third, check map parms
13343: 	    my %parmhash=();
13344: 	    my $thisparm='';
13345: 	    if (tie(%parmhash,'GDBM_File',
13346: 		    $env{'request.course.fn'}.'_parms.db',
13347: 		    &GDBM_READER(),0640)) {
13348: 		$thisparm=$parmhash{$symbparm};
13349: 		untie(%parmhash);
13350: 	    }
13351: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
13352: 	}
13353: # ------------------------------------------ fourth, look in resource metadata
13354:  
13355:         my $what = $spacequalifierrest;
13356: 	$what=~s/\./\_/;
13357: 	my $filename;
13358: 	if (!$symbparm) { $symbparm=&symbread(); }
13359: 	if ($symbparm) {
13360: 	    $filename=(&decode_symb($symbparm))[2];
13361: 	} else {
13362: 	    $filename=$env{'request.filename'};
13363: 	}
13364:         my $toolsymb;
13365:         if (($filename =~ /ext\.tool$/) && ($what ne '0_gradable')) {
13366:             $toolsymb = $symbparm;
13367:         }
13368: 	my $metadata=&metadata($filename,$what,$toolsymb);
13369: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
13370: 	$metadata=&metadata($filename,'parameter_'.$what,$toolsymb);
13371: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
13372: 
13373: # ----------------------------------------------- fifth, look in rest of course
13374: 	if ($symbparm && defined($courseid) && 
13375: 	    $courseid eq $env{'request.course.id'}) {
13376: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
13377: 				     $env{'course.'.$courseid.'.domain'},
13378: 				     'course',$mapp,\$recursed,\@recurseup,
13379:                                      $courseid,'.',$spacequalifierrest,
13380: 				     ([$courselevelm,'map'   ],
13381:                                       [$courseleveli,'map'   ],
13382: 				      [$courselevel, 'course']));
13383: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
13384: 	}
13385: # ------------------------------------------------------------------ Cascade up
13386: 	unless ($space eq '0') {
13387: 	    my @parts=split(/_/,$space);
13388: 	    my $id=pop(@parts);
13389: 	    my $part=join('_',@parts);
13390: 	    if ($part eq '') { $part='0'; }
13391: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
13392: 				 $symbparm,$udom,$uname,$section,1);
13393: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
13394: 	}
13395: 	if ($recurse) { return undef; }
13396: 	my $pack_def=&packages_tab_default($filename,$varname,$toolsymb);
13397: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
13398: # ---------------------------------------------------- Any other user namespace
13399:     } elsif ($realm eq 'environment') {
13400: # ----------------------------------------------------------------- environment
13401: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
13402: 	    return $env{'environment.'.$spacequalifierrest};
13403: 	} else {
13404: 	    if ($uname eq 'anonymous' && $udom eq '') {
13405: 		return '';
13406: 	    }
13407: 	    my %returnhash=&userenvironment($udom,$uname,
13408: 					    $spacequalifierrest);
13409: 	    return $returnhash{$spacequalifierrest};
13410: 	}
13411:     } elsif ($realm eq 'system') {
13412: # ----------------------------------------------------------------- system.time
13413: 	if ($space eq 'time') {
13414: 	    return time;
13415:         }
13416:     } elsif ($realm eq 'server') {
13417: # ----------------------------------------------------------------- system.time
13418: 	if ($space eq 'name') {
13419: 	    return $ENV{'SERVER_NAME'};
13420:         }
13421:     } elsif ($realm eq 'client') {
13422:         if ($space eq 'remote_addr') {
13423:             return &get_requestor_ip();
13424:         }
13425:     }
13426:     return '';
13427: }
13428: 
13429: sub get_reply {
13430:     my ($reply_value) = @_;
13431:     if (ref($reply_value) eq 'ARRAY') {
13432:         if (wantarray) {
13433: 	    return @$reply_value;
13434:         }
13435:         return $reply_value->[0];
13436:     } else {
13437:         return $reply_value;
13438:     }
13439: }
13440: 
13441: sub check_group_parms {
13442:     my ($courseid,$groups,$symbparm,$recurseparm,$mapparm,$what,$mapp,
13443:         $recursed,$recurseupref) = @_;
13444:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$recurseparm,'map'],
13445:                   [$what,'course']);
13446:     my $coursereply;
13447:     foreach my $group (@{$groups}) {
13448:         my @groupitems = ();
13449:         foreach my $level (@levels) {
13450:              my $item = $courseid.'.['.$group.'].'.$level->[0];
13451:              push(@groupitems,[$item,$level->[1]]);
13452:         }
13453:         my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
13454:                                    $env{'course.'.$courseid.'.domain'},
13455:                                    'course',$mapp,$recursed,$recurseupref,
13456:                                    $courseid,'.['.$group.'].',$what,
13457:                                    @groupitems);
13458:         last if (defined($coursereply));
13459:     }
13460:     return $coursereply;
13461: }
13462: 
13463: sub get_map_hierarchy {
13464:     my ($mapname,$courseid) = @_;
13465:     my @recurseup = ();
13466:     if ($mapname) {
13467:         if (($cachedmapkey eq $courseid) &&
13468:             (abs($cachedmaptime-time)<5)) {
13469:             if (ref($cachedmaps{$mapname}) eq 'ARRAY') {
13470:                 return @{$cachedmaps{$mapname}};
13471:             }
13472:         }
13473:         my $navmap = Apache::lonnavmaps::navmap->new();
13474:         if (ref($navmap)) {
13475:             @recurseup = $navmap->recurseup_maps($mapname);
13476:             undef($navmap);
13477:             $cachedmaps{$mapname} = \@recurseup;
13478:             $cachedmaptime=time;
13479:             $cachedmapkey=$courseid;
13480:         }
13481:     }
13482:     return @recurseup;
13483: }
13484: 
13485: }
13486: 
13487: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
13488:     my ($courseid,@groups) = @_;
13489:     @groups = sort(@groups);
13490:     return @groups;
13491: }
13492: 
13493: sub packages_tab_default {
13494:     my ($uri,$varname,$toolsymb)=@_;
13495:     my (undef,$part,$name)=split(/\./,$varname);
13496: 
13497:     my (@extension,@specifics,$do_default);
13498:     foreach my $package (split(/,/,&metadata($uri,'packages',$toolsymb))) {
13499: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
13500: 	if ($pack_type eq 'default') {
13501: 	    $do_default=1;
13502: 	} elsif ($pack_type eq 'extension') {
13503: 	    push(@extension,[$package,$pack_type,$pack_part]);
13504: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
13505: 	    # only look at packages defaults for packages that this id is
13506: 	    push(@specifics,[$package,$pack_type,$pack_part]);
13507: 	}
13508:     }
13509:     # first look for a package that matches the requested part id
13510:     foreach my $package (@specifics) {
13511: 	my (undef,$pack_type,$pack_part)=@{$package};
13512: 	next if ($pack_part ne $part);
13513: 	if (defined($packagetab{"$pack_type&$name&default"})) {
13514: 	    return $packagetab{"$pack_type&$name&default"};
13515: 	}
13516:     }
13517:     # look for any possible matching non extension_ package
13518:     foreach my $package (@specifics) {
13519: 	my (undef,$pack_type,$pack_part)=@{$package};
13520: 	if (defined($packagetab{"$pack_type&$name&default"})) {
13521: 	    return $packagetab{"$pack_type&$name&default"};
13522: 	}
13523: 	if ($pack_type eq 'part') { $pack_part='0'; }
13524: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
13525: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
13526: 	}
13527:     }
13528:     # look for any posible extension_ match
13529:     foreach my $package (@extension) {
13530: 	my ($package,$pack_type)=@{$package};
13531: 	if (defined($packagetab{"$pack_type&$name&default"})) {
13532: 	    return $packagetab{"$pack_type&$name&default"};
13533: 	}
13534: 	if (defined($packagetab{$package."&$name&default"})) {
13535: 	    return $packagetab{$package."&$name&default"};
13536: 	}
13537:     }
13538:     # look for a global default setting
13539:     if ($do_default && defined($packagetab{"default&$name&default"})) {
13540: 	return $packagetab{"default&$name&default"};
13541:     }
13542:     return undef;
13543: }
13544: 
13545: sub add_prefix_and_part {
13546:     my ($prefix,$part)=@_;
13547:     my $keyroot;
13548:     if (defined($prefix) && $prefix !~ /^__/) {
13549: 	# prefix that has a part already
13550: 	$keyroot=$prefix;
13551:     } elsif (defined($prefix)) {
13552: 	# prefix that is missing a part
13553: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
13554:     } else {
13555: 	# no prefix at all
13556: 	if (defined($part)) { $keyroot='_'.$part; }
13557:     }
13558:     return $keyroot;
13559: }
13560: 
13561: # ---------------------------------------------------------------- Get metadata
13562: 
13563: my %metaentry;
13564: my %importedpartids;
13565: my %importedrespids;
13566: sub metadata {
13567:     my ($uri,$what,$toolsymb,$liburi,$prefix,$depthcount)=@_;
13568:     $uri=&declutter($uri);
13569:     # if it is a non metadata possible uri return quickly
13570:     if (($uri eq '') || 
13571: 	(($uri =~ m|^/*adm/|) && 
13572: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard|ext\.tool)$})) ||
13573:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
13574: 	return undef;
13575:     }
13576:     if (($uri =~ /^priv/ || $uri=~m{^home/httpd/html/priv}) 
13577: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
13578: 	return undef;
13579:     }
13580:     my $filename=$uri;
13581:     $uri=~s/\.meta$//;
13582: #
13583: # Is the metadata already cached?
13584: # Look at timestamp of caching
13585: # Everything is cached by the main uri, libraries are never directly cached
13586: #
13587:     if (!defined($liburi)) {
13588: 	my ($result,$cached)=&is_cached_new('meta',$uri);
13589: 	if (defined($cached)) { return $result->{':'.$what}; }
13590:     }
13591: 
13592: #
13593: # If the uri is for an external tool the file from
13594: # which metadata should be retrieved depends on whether
13595: # the tool had been configured to be gradable (set in the Course
13596: # Editor or Resource Editor).
13597: #
13598: # If a valid symb has been included as the third arg in the call
13599: # to &metadata() that can be used to retrieve the value of
13600: # parameter_0_gradable set for the resource, and included in the
13601: # uploaded map containing the tool. The value is retrieved via
13602: # &EXT(), if a valid symb is available.  Otherwise the value of
13603: # gradable in the exttool_$marker.db file for the tool instance
13604: # is retrieved via &get().
13605: #
13606: # When lonuserstate::traceroute() calls lonnet::EXT() for 
13607: # hiddenresource and encrypturl (during course initialization)
13608: # the map-level parameter for resource.0.gradable included in the 
13609: # uploaded map containing the tool will not yet have been stored
13610: # in the user_course_parms.db file for the user's session, so in 
13611: # this case fall back to retrieving gradable status from the
13612: # exttool_$marker.db file.
13613: #
13614: # In order to avoid an infinite loop, &metadata() will return
13615: # before a call to &EXT(), if the uri is for an external tool
13616: # and the $what for which metadata is being requested is
13617: # parameter_0_gradable or 0_gradable.
13618: #
13619: 
13620:     if ($uri =~ /ext\.tool$/) {
13621:         if (($what eq 'parameter_0_gradable') || ($what eq '0_gradable')) {
13622:             return;
13623:         } else {
13624:             my ($checked,$use_passback);
13625:             if ($toolsymb ne '') {
13626:                 (undef,undef,my $tooluri) = &decode_symb($toolsymb);
13627:                 if (($tooluri eq $uri) && (&EXT('resource.0.gradable',$toolsymb))) {
13628:                     $checked = 1;
13629:                     if (&EXT('resource.0.gradable',$toolsymb) =~ /^yes$/i) {
13630:                         $use_passback = 1;
13631:                     }
13632:                 }
13633:             }
13634:             unless ($checked) {
13635:                 my ($ignore,$cdom,$cnum,$marker) = split(m{/},$uri);
13636:                 $marker=~s/\D//g;
13637:                 if ($marker) {
13638:                     my %toolsettings=&get('exttool_'.$marker,['gradable'],$cdom,$cnum);
13639:                     $use_passback = $toolsettings{'gradable'};
13640:                 }
13641:             }
13642:             if ($use_passback) {
13643:                 $filename = '/home/httpd/html/res/lib/templates/LTIpassback.tool';
13644:             } else {
13645:                 $filename = '/home/httpd/html/res/lib/templates/LTIstandard.tool';
13646:             }
13647:         }
13648:     }
13649: 
13650:     {
13651: # Imported parts would go here
13652:         my @origfiletagids=();
13653:         my $importedparts=0;
13654: 
13655: # Imported responseids would go here
13656:         my $importedresponses=0;
13657: #
13658: # Is this a recursive call for a library?
13659: #
13660: #	if (! exists($metacache{$uri})) {
13661: #	    $metacache{$uri}={};
13662: #	}
13663: 	my $cachetime = 60*60;
13664:         if ($liburi) {
13665: 	    $liburi=&declutter($liburi);
13666:             $filename=$liburi;
13667:         } else {
13668: 	    &devalidate_cache_new('meta',$uri);
13669: 	    undef(%metaentry);
13670: 	}
13671:         my %metathesekeys=();
13672:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
13673: 	my $metastring;
13674: 	if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
13675: 	    my $which = &hreflocation('','/'.($liburi || $uri));
13676: 	    $metastring = 
13677: 		&Apache::lonnet::ssi_body($which,
13678: 					  ('grade_target' => 'meta'));
13679: 	    $cachetime = 1; # only want this cached in the child not long term
13680: 	} elsif (($uri !~ m -^(editupload)/-) && 
13681:                  ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
13682: 	    my $file=&filelocation('',&clutter($filename));
13683: 	    #push(@{$metaentry{$uri.'.file'}},$file);
13684: 	    $metastring=&getfile($file);
13685: 	}
13686:         my $parser=HTML::LCParser->new(\$metastring);
13687:         my $token;
13688:         undef %metathesekeys;
13689:         while ($token=$parser->get_token) {
13690: 	    if ($token->[0] eq 'S') {
13691: 		if (defined($token->[2]->{'package'})) {
13692: #
13693: # This is a package - get package info
13694: #
13695: 		    my $package=$token->[2]->{'package'};
13696: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
13697: 		    if (defined($token->[2]->{'id'})) { 
13698: 			$keyroot.='_'.$token->[2]->{'id'}; 
13699: 		    }
13700: 		    if ($metaentry{':packages'}) {
13701: 			$metaentry{':packages'}.=','.$package.$keyroot;
13702: 		    } else {
13703: 			$metaentry{':packages'}=$package.$keyroot;
13704: 		    }
13705: 		    foreach my $pack_entry (keys(%packagetab)) {
13706: 			my $part=$keyroot;
13707: 			$part=~s/^\_//;
13708: 			if ($pack_entry=~/^\Q$package\E\&/ || 
13709: 			    $pack_entry=~/^\Q$package\E_0\&/) {
13710: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
13711: 			    # ignore package.tab specified default values
13712:                             # here &package_tab_default() will fetch those
13713: 			    if ($subp eq 'default') { next; }
13714: 			    my $value=$packagetab{$pack_entry};
13715: 			    my $unikey;
13716: 			    if ($pack =~ /_0$/) {
13717: 				$unikey='parameter_0_'.$name;
13718: 				$part=0;
13719: 			    } else {
13720: 				$unikey='parameter'.$keyroot.'_'.$name;
13721: 			    }
13722: 			    if ($subp eq 'display') {
13723: 				$value.=' [Part: '.$part.']';
13724: 			    }
13725: 			    $metaentry{':'.$unikey.'.part'}=$part;
13726: 			    $metathesekeys{$unikey}=1;
13727: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
13728: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
13729: 			    }
13730: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
13731: 				$metaentry{':'.$unikey}=
13732: 				    $metaentry{':'.$unikey.'.default'};
13733: 			    }
13734: 			}
13735: 		    }
13736: 		} else {
13737: #
13738: # This is not a package - some other kind of start tag
13739: #
13740: 		    my $entry=$token->[1];
13741: 		    my $unikey='';
13742: 
13743: 		    if ($entry eq 'import') {
13744: #
13745: # Importing a library here
13746: #
13747:                         my $location=$parser->get_text('/import');
13748:                         my $dir=$filename;
13749:                         $dir=~s|[^/]*$||;
13750:                         $location=&filelocation($dir,$location);
13751: 
13752:                         my $importid=$token->[2]->{'id'};
13753:                         my $importmode=$token->[2]->{'importmode'};
13754: #
13755: # Check metadata for imported file to
13756: # see if it contained response items
13757: #
13758:                         my ($origfile,@libfilekeys);
13759:                         my %currmetaentry = %metaentry;
13760:                         @libfilekeys = split(/,/,&metadata($location,'keys',undef,undef,undef,
13761:                                                            $depthcount+1));
13762:                         if (grep(/^responseorder$/,@libfilekeys)) {
13763:                             my $libresponseorder = &metadata($location,'responseorder',undef,undef,
13764:                                                              undef,$depthcount+1);
13765:                             if ($libresponseorder ne '') {
13766:                                 if ($#origfiletagids<0) {
13767:                                     undef(%importedrespids);
13768:                                     undef(%importedpartids);
13769:                                 }
13770:                                 my @respids = split(/\s*,\s*/,$libresponseorder);
13771:                                 if (@respids) {
13772:                                     $importedrespids{$importid} = join(',',map { $importid.'_'.$_ } @respids);
13773:                                 }
13774:                                 if ($importedrespids{$importid} ne '') {
13775:                                     $importedresponses = 1;
13776: # We need to get the original file and the imported file to get the response order correct
13777: # Load and inspect original file
13778:                                     if ($#origfiletagids<0) {
13779:                                         my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
13780:                                         $origfile=&getfile($origfilelocation);
13781:                                         @origfiletagids=($origfile=~/<((?:\w+)response|import|part)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
13782:                                     }
13783:                                 }
13784:                             }
13785:                         }
13786: # Do not overwrite contents of %metaentry hash for resource itself with 
13787: # hash populated for imported library file
13788:                         %metaentry = %currmetaentry;
13789:                         undef(%currmetaentry);
13790:                         if ($importmode eq 'part') {
13791: # Import as part(s)
13792:                            $importedparts=1;
13793: # We need to get the original file and the imported file to get the part order correct
13794: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
13795: # Load and inspect original file if we didn't do that already
13796:                            if ($#origfiletagids<0) {
13797:                                undef(%importedrespids);
13798:                                undef(%importedpartids);
13799:                                if ($origfile eq '') {
13800:                                    my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
13801:                                    $origfile=&getfile($origfilelocation);
13802:                                    @origfiletagids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
13803:                                }
13804:                            }
13805:                            my @impfilepartids;
13806: # If <partorder> tag is included in metadata for the imported file
13807: # get the parts in the imported file from that.
13808:                            if (grep(/^partorder$/,@libfilekeys)) {
13809:                                %currmetaentry = %metaentry;
13810:                                my $libpartorder = &metadata($location,'partorder',undef,undef,undef,
13811:                                                             $depthcount+1);
13812:                                %metaentry = %currmetaentry;
13813:                                undef(%currmetaentry);
13814:                                if ($libpartorder ne '') {
13815:                                    @impfilepartids=split(/\s*,\s*/,$libpartorder);
13816:                                }
13817:                            } else {
13818: # If no <partorder> tag available, load and inspect imported file
13819:                                my $impfile=&getfile($location);
13820:                                @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
13821:                            }
13822:                            if ($#impfilepartids>=0) {
13823: # This problem had parts
13824:                                $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
13825:                            } else {
13826: # Importing by turning a single problem into a problem part
13827: # It gets the import-tags ID as part-ID
13828:                                $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
13829:                                $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
13830:                            }
13831:                         } else {
13832: # Import as problem or as normal import
13833:                             $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
13834:                             unless ($importmode eq 'problem') {
13835: # Normal import
13836:                                 if (defined($token->[2]->{'id'})) {
13837:                                     $unikey.='_'.$token->[2]->{'id'};
13838:                                 }
13839:                             }
13840: # Check metadata for imported file to
13841: # see if it contained parts
13842:                             if (grep(/^partorder$/,@libfilekeys)) {
13843:                                 %currmetaentry = %metaentry;
13844:                                 my $libpartorder = &metadata($location,'partorder',undef,undef,undef,
13845:                                                              $depthcount+1);
13846:                                 %metaentry = %currmetaentry;
13847:                                 undef(%currmetaentry);
13848:                                 if ($libpartorder ne '') {
13849:                                     $importedparts = 1;
13850:                                     $importedpartids{$token->[2]->{'id'}}=$libpartorder;
13851:                                 }
13852:                             }
13853:                         }
13854: 			if ($depthcount<20) {
13855: 			    my $metadata = 
13856: 				&metadata($uri,'keys',$toolsymb,$location,$unikey,
13857: 					  $depthcount+1);
13858: 			    foreach my $meta (split(',',$metadata)) {
13859: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
13860: 				$metathesekeys{$meta}=1;
13861: 			    }
13862:                         }
13863: 		    } else {
13864: #
13865: # Not importing, some other kind of non-package, non-library start tag
13866: # 
13867:                         $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
13868:                         if (defined($token->[2]->{'id'})) {
13869:                             $unikey.='_'.$token->[2]->{'id'};
13870:                         }
13871: 			if (defined($token->[2]->{'name'})) { 
13872: 			    $unikey.='_'.$token->[2]->{'name'}; 
13873: 			}
13874: 			$metathesekeys{$unikey}=1;
13875: 			foreach my $param (@{$token->[3]}) {
13876: 			    $metaentry{':'.$unikey.'.'.$param} =
13877: 				$token->[2]->{$param};
13878: 			}
13879: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
13880: 			my $default=$metaentry{':'.$unikey.'.default'};
13881: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
13882: 		 # only ws inside the tag, and not in default, so use default
13883: 		 # as value
13884: 			    $metaentry{':'.$unikey}=$default;
13885: 			} elsif ( $internaltext =~ /\S/ ) {
13886: 		  # something interesting inside the tag
13887: 			    $metaentry{':'.$unikey}=$internaltext;
13888: 			} else {
13889: 		  # no interesting values, don't set a default
13890: 			}
13891: # end of not-a-package not-a-library import
13892: 		    }
13893: # end of not-a-package start tag
13894: 		}
13895: # the next is the end of "start tag"
13896: 	    }
13897: 	}
13898: 	my ($extension) = ($uri =~ /\.(\w+)$/);
13899: 	$extension = lc($extension);
13900: 	if ($extension eq 'htm') { $extension='html'; }
13901: 
13902: 	foreach my $key (keys(%packagetab)) {
13903: 	    #no specific packages #how's our extension
13904: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
13905: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
13906: 					 \%metathesekeys);
13907: 	}
13908: 
13909: 	if (!exists($metaentry{':packages'})
13910: 	    || $packagetab{"import_defaults&extension_$extension"}) {
13911: 	    foreach my $key (keys(%packagetab)) {
13912: 		#no specific packages well let's get default then
13913: 		if ($key!~/^default&/) { next; }
13914: 		&metadata_create_package_def($uri,$key,'default',
13915: 					     \%metathesekeys);
13916: 	    }
13917: 	}
13918: # are there custom rights to evaluate
13919: 	if ($metaentry{':copyright'} eq 'custom') {
13920: 
13921:     #
13922:     # Importing a rights file here
13923:     #
13924: 	    unless ($depthcount) {
13925: 		my $location=$metaentry{':customdistributionfile'};
13926: 		my $dir=$filename;
13927: 		$dir=~s|[^/]*$||;
13928: 		$location=&filelocation($dir,$location);
13929: 		my $rights_metadata =
13930: 		    &metadata($uri,'keys',$toolsymb,$location,'_rights',
13931: 			      $depthcount+1);
13932: 		foreach my $rights (split(',',$rights_metadata)) {
13933: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
13934: 		    $metathesekeys{$rights}=1;
13935: 		}
13936: 	    }
13937: 	}
13938: 	# uniqifiy package listing
13939: 	my %seen;
13940: 	my @uniq_packages =
13941: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
13942: 	$metaentry{':packages'} = join(',',@uniq_packages);
13943: 
13944:         if (($importedresponses) || ($importedparts)) {
13945:             if ($importedparts) {
13946: # We had imported parts and need to rebuild partorder
13947:                 $metaentry{':partorder'}='';
13948:                 $metathesekeys{'partorder'}=1;
13949:             }
13950:             if ($importedresponses) {
13951: # We had imported responses and need to rebuil responseorder
13952:                 $metaentry{':responseorder'}='';
13953:                 $metathesekeys{'responseorder'}=1;
13954:             }
13955:             for (my $index=0;$index<$#origfiletagids;$index+=2) {
13956:                 my $origid = $origfiletagids[$index+1];
13957:                 if ($origfiletagids[$index] eq 'part') {
13958: # Original part, part of the problem
13959:                     if ($importedparts) {
13960:                         $metaentry{':partorder'}.=','.$origid;
13961:                     }
13962:                 } elsif ($origfiletagids[$index] eq 'import') {
13963:                     if ($importedparts) {
13964: # We have imported parts at this position
13965:                         if ($importedpartids{$origid} ne '') {
13966:                             $metaentry{':partorder'}.=','.$importedpartids{$origid};
13967:                         }
13968:                     }
13969:                     if ($importedresponses) {
13970: # We have imported responses at this position
13971:                         if ($importedrespids{$origid} ne '') {
13972:                             $metaentry{':responseorder'}.=','.$importedrespids{$origid};
13973:                         }
13974:                     }
13975:                 } else {
13976: # Original response item, part of the problem
13977:                     if ($importedresponses) {
13978:                         $metaentry{':responseorder'}.=','.$origid;
13979:                     }
13980:                 }
13981:             }
13982:             if ($importedparts) {
13983:                 $metaentry{':partorder'}=~s/^\,//;
13984:             }
13985:             if ($importedresponses) {
13986:                 $metaentry{':responseorder'}=~s/^\,//;
13987:             }
13988:         }
13989: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
13990: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
13991: 	$metaentry{':allpossiblekeys'}=join(',',keys(%metathesekeys));
13992:         unless ($liburi) {
13993: 	    &do_cache_new('meta',$uri,\%metaentry,$cachetime);
13994:         }
13995: # this is the end of "was not already recently cached
13996:     }
13997:     return $metaentry{':'.$what};
13998: }
13999: 
14000: sub metadata_create_package_def {
14001:     my ($uri,$key,$package,$metathesekeys)=@_;
14002:     my ($pack,$name,$subp)=split(/\&/,$key);
14003:     if ($subp eq 'default') { next; }
14004:     
14005:     if (defined($metaentry{':packages'})) {
14006: 	$metaentry{':packages'}.=','.$package;
14007:     } else {
14008: 	$metaentry{':packages'}=$package;
14009:     }
14010:     my $value=$packagetab{$key};
14011:     my $unikey;
14012:     $unikey='parameter_0_'.$name;
14013:     $metaentry{':'.$unikey.'.part'}=0;
14014:     $$metathesekeys{$unikey}=1;
14015:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
14016: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
14017:     }
14018:     if (defined($metaentry{':'.$unikey.'.default'})) {
14019: 	$metaentry{':'.$unikey}=
14020: 	    $metaentry{':'.$unikey.'.default'};
14021:     }
14022: }
14023: 
14024: sub metadata_generate_part0 {
14025:     my ($metadata,$metacache,$uri) = @_;
14026:     my %allnames;
14027:     foreach my $metakey (keys(%$metadata)) {
14028: 	if ($metakey=~/^parameter\_(.*)/) {
14029: 	  my $part=$$metacache{':'.$metakey.'.part'};
14030: 	  my $name=$$metacache{':'.$metakey.'.name'};
14031: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
14032: 	    $allnames{$name}=$part;
14033: 	  }
14034: 	}
14035:     }
14036:     foreach my $name (keys(%allnames)) {
14037:       $$metadata{"parameter_0_$name"}=1;
14038:       my $key=":parameter_0_$name";
14039:       $$metacache{"$key.part"}='0';
14040:       $$metacache{"$key.name"}=$name;
14041:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
14042: 					   $allnames{$name}.'_'.$name.
14043: 					   '.type'};
14044:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
14045: 			     '.display'};
14046:       my $expr='[Part: '.$allnames{$name}.']';
14047:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
14048:       $$metacache{"$key.display"}=$olddis;
14049:     }
14050: }
14051: 
14052: # ------------------------------------------------------ Devalidate title cache
14053: 
14054: sub devalidate_title_cache {
14055:     my ($url)=@_;
14056:     if (!$env{'request.course.id'}) { return; }
14057:     my $symb=&symbread($url);
14058:     if (!$symb) { return; }
14059:     my $key=$env{'request.course.id'}."\0".$symb;
14060:     &devalidate_cache_new('title',$key);
14061: }
14062: 
14063: # ------------------------------------------------- Get the title of a course
14064: 
14065: sub current_course_title {
14066:     return $env{ 'course.' . $env{'request.course.id'} . '.description' };
14067: }
14068: # ------------------------------------------------- Get the title of a resource
14069: 
14070: sub gettitle {
14071:     my $urlsymb=shift;
14072:     my $symb=&symbread($urlsymb);
14073:     if ($symb) {
14074: 	my $key=$env{'request.course.id'}."\0".$symb;
14075: 	my ($result,$cached)=&is_cached_new('title',$key);
14076: 	if (defined($cached)) { 
14077: 	    return $result;
14078: 	}
14079: 	my ($map,$resid,$url)=&decode_symb($symb);
14080: 	my $title='';
14081: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
14082: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
14083: 	} else {
14084: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
14085: 		    &GDBM_READER(),0640)) {
14086: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
14087: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
14088: 		untie(%bighash);
14089: 	    }
14090: 	}
14091: 	$title=~s/\&colon\;/\:/gs;
14092: 	if ($title) {
14093: # Remember both $symb and $title for dynamic metadata
14094:             $accesshash{$symb.'___crstitle'}=$title;
14095:             $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
14096: # Cache this title and then return it
14097: 	    return &do_cache_new('title',$key,$title,600);
14098: 	}
14099: 	$urlsymb=$url;
14100:     }
14101:     my $title=&metadata($urlsymb,'title');
14102:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
14103:     return $title;
14104: }
14105: 
14106: sub get_slot {
14107:     my ($which,$cnum,$cdom)=@_;
14108:     if (!$cnum || !$cdom) {
14109: 	(undef,my $courseid)=&whichuser();
14110: 	$cdom=$env{'course.'.$courseid.'.domain'};
14111: 	$cnum=$env{'course.'.$courseid.'.num'};
14112:     }
14113:     my $key=join("\0",'slots',$cdom,$cnum,$which);
14114:     my %slotinfo;
14115:     if (exists($remembered{$key})) {
14116: 	$slotinfo{$which} = $remembered{$key};
14117:     } else {
14118: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
14119: 	&Apache::lonhomework::showhash(%slotinfo);
14120: 	my ($tmp)=keys(%slotinfo);
14121: 	if ($tmp=~/^error:/) { return (); }
14122: 	$remembered{$key} = $slotinfo{$which};
14123:     }
14124:     if (ref($slotinfo{$which}) eq 'HASH') {
14125: 	return %{$slotinfo{$which}};
14126:     }
14127:     return $slotinfo{$which};
14128: }
14129: 
14130: sub get_reservable_slots {
14131:     my ($cnum,$cdom,$uname,$udom) = @_;
14132:     my $now = time;
14133:     my $reservable_info;
14134:     my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
14135:     if (exists($remembered{$key})) {
14136:         $reservable_info = $remembered{$key};
14137:     } else {
14138:         my %resv;
14139:         ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
14140:         &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
14141:         $reservable_info = \%resv;
14142:         $remembered{$key} = $reservable_info;
14143:     }
14144:     return $reservable_info;
14145: }
14146: 
14147: sub get_course_slots {
14148:     my ($cnum,$cdom) = @_;
14149:     my $hashid=$cnum.':'.$cdom;
14150:     my ($result,$cached) = &is_cached_new('allslots',$hashid);
14151:     if (defined($cached)) {
14152:         if (ref($result) eq 'HASH') {
14153:             return %{$result};
14154:         }
14155:     } else {
14156:         my %slots=&dump('slots',$cdom,$cnum);
14157:         my ($tmp) = keys(%slots);
14158:         if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
14159:             &do_cache_new('allslots',$hashid,\%slots,600);
14160:             return %slots;
14161:         }
14162:     }
14163:     return;
14164: }
14165: 
14166: sub devalidate_slots_cache {
14167:     my ($cnum,$cdom)=@_;
14168:     my $hashid=$cnum.':'.$cdom;
14169:     &devalidate_cache_new('allslots',$hashid);
14170: }
14171: 
14172: sub get_coursechange {
14173:     my ($cdom,$cnum) = @_;
14174:     if ($cdom eq '' || $cnum eq '') {
14175:         return unless ($env{'request.course.id'});
14176:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
14177:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
14178:     }
14179:     my $hashid=$cdom.'_'.$cnum;
14180:     my ($change,$cached)=&is_cached_new('crschange',$hashid);
14181:     if ((defined($cached)) && ($change ne '')) {
14182:         return $change;
14183:     } else {
14184:         my %crshash;
14185:         %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
14186:         if ($crshash{'internal.contentchange'} eq '') {
14187:             $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
14188:             if ($change eq '') {
14189:                 %crshash = &get('environment',['internal.created'],$cdom,$cnum);
14190:                 $change = $crshash{'internal.created'};
14191:             }
14192:         } else {
14193:             $change = $crshash{'internal.contentchange'};
14194:         }
14195:         my $cachetime = 600;
14196:         &do_cache_new('crschange',$hashid,$change,$cachetime);
14197:     }
14198:     return $change;
14199: }
14200: 
14201: sub devalidate_coursechange_cache {
14202:     my ($cdom,$cnum)=@_;
14203:     my $hashid=$cdom.'_'.$cnum;
14204:     &devalidate_cache_new('crschange',$hashid);
14205: }
14206: 
14207: sub get_suppchange {
14208:     my ($cdom,$cnum) = @_;
14209:     if ($cdom eq '' || $cnum eq '') {
14210:         return unless ($env{'request.course.id'});
14211:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
14212:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
14213:     }
14214:     my $hashid=$cdom.'_'.$cnum;
14215:     my ($change,$cached)=&is_cached_new('suppchange',$hashid);
14216:     if ((defined($cached)) && ($change ne '')) {
14217:         return $change;
14218:     } else {
14219:         my %crshash = &get('environment',['internal.supplementalchange'],$cdom,$cnum);
14220:         if ($crshash{'internal.supplementalchange'} eq '') {
14221:             $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
14222:             if ($change eq '') {
14223:                 %crshash = &get('environment',['internal.created'],$cdom,$cnum);
14224:                 $change = $crshash{'internal.created'};
14225:             }
14226:         } else {
14227:             $change = $crshash{'internal.supplementalchange'};
14228:         }
14229:         my $cachetime = 600;
14230:         &do_cache_new('suppchange',$hashid,$change,$cachetime);
14231:     }
14232:     return $change;
14233: }
14234: 
14235: sub devalidate_suppchange_cache {
14236:     my ($cdom,$cnum)=@_;
14237:     my $hashid=$cdom.'_'.$cnum;
14238:     &devalidate_cache_new('suppchange',$hashid);
14239: }
14240: 
14241: sub update_supp_caches {
14242:     my ($cdom,$cnum) = @_;
14243:     my %servers = &internet_dom_servers($cdom);
14244:     my @ids=&current_machine_ids();
14245:     foreach my $server (keys(%servers)) {
14246:         next if (grep(/^\Q$server\E$/,@ids));
14247:         my $hashid=$cnum.':'.$cdom;
14248:         my $cachekey = &escape('showsupp').':'.&escape($hashid);
14249:         &remote_devalidate_cache($server,[$cachekey]);
14250:     }
14251:     &has_unhidden_suppfiles($cnum,$cdom,1,1);
14252:     &count_supptools($cnum,$cdom,1);
14253:     my $now = time;
14254:     if ($env{'request.course.id'} eq $cdom.'_'.$cnum) {
14255:         &Apache::lonnet::appenv({'request.course.suppupdated' => $now});
14256:     }
14257:     &put('environment',{'internal.supplementalchange' => $now},
14258:          $cdom,$cnum);
14259:     &Apache::lonnet::appenv(
14260:         {'course.'.$cdom.'_'.$cnum.'.internal.supplementalchange' => $now});
14261:     &do_cache_new('suppchange',$cdom.'_'.$cnum,$now,600);
14262: }
14263: 
14264: # ------------------------------------------------- Update symbolic store links
14265: 
14266: sub symblist {
14267:     my ($mapname,%newhash)=@_;
14268:     $mapname=&deversion(&declutter($mapname));
14269:     my %hash;
14270:     if (($env{'request.course.fn'}) && (%newhash)) {
14271:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
14272:                       &GDBM_WRCREAT(),0640)) {
14273: 	    foreach my $url (keys(%newhash)) {
14274: 		next if ($url eq 'last_known'
14275: 			 && $env{'form.no_update_last_known'});
14276: 		$hash{declutter($url)}=&encode_symb($mapname,
14277: 						    $newhash{$url}->[1],
14278: 						    $newhash{$url}->[0]);
14279:             }
14280:             if (untie(%hash)) {
14281: 		return 'ok';
14282:             }
14283:         }
14284:     }
14285:     return 'error';
14286: }
14287: 
14288: # --------------------------------------------------------------- Verify a symb
14289: 
14290: sub symbverify {
14291:     my ($symb,$thisurl,$encstate)=@_;
14292:     my $thisfn=$thisurl;
14293:     $thisfn=&declutter($thisfn);
14294: # direct jump to resource in page or to a sequence - will construct own symbs
14295:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
14296: # check URL part
14297:     my ($map,$resid,$url)=&decode_symb($symb);
14298: 
14299:     unless ($url eq $thisfn) { return 0; }
14300: 
14301:     $symb=&symbclean($symb);
14302:     $thisurl=&deversion($thisurl);
14303:     $thisfn=&deversion($thisfn);
14304: 
14305:     my %bighash;
14306:     my $okay=0;
14307: 
14308:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
14309:                             &GDBM_READER(),0640)) {
14310:         if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
14311:             $thisurl =~ s/\?.+$//;
14312:             if ($map =~ m{^uploaded/.+\.page$}) {
14313:                 $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
14314:                 $thisurl =~ s{^\Qhttp://https://\E}{https://};
14315:             }
14316:         }
14317:         my $ids;
14318:         if ($map =~ m{^uploaded/.+\.page$}) {
14319:             $ids=$bighash{'ids_'.&clutter_with_no_wrapper($thisurl)};
14320:         } else {
14321:             $ids=$bighash{'ids_'.&clutter($thisurl)};
14322:         }
14323:         unless ($ids) {
14324:             my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;  
14325:             $ids=$bighash{$idkey};
14326:         }
14327:         if ($ids) {
14328: # ------------------------------------------------------------------- Has ID(s)
14329:             if ($thisfn =~ m{^/adm/wrapper/ext/}) {
14330:                 $symb =~ s/\?.+$//;
14331:             }
14332: 	    foreach my $id (split(/\,/,$ids)) {
14333: 	       my ($mapid,$resid)=split(/\./,$id);
14334:                if (
14335:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
14336:    eq $symb) {
14337:                    if (ref($encstate)) {
14338:                        $$encstate = $bighash{'encrypted_'.$id};
14339:                    }
14340: 		   if (($env{'request.role.adv'}) ||
14341: 		       ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
14342:                        ($thisurl eq '/adm/navmaps')) {
14343: 		       $okay=1;
14344:                        last;
14345: 		   }
14346: 	       }
14347: 	   }
14348:         }
14349: 	untie(%bighash);
14350:     }
14351:     return $okay;
14352: }
14353: 
14354: # --------------------------------------------------------------- Clean-up symb
14355: 
14356: sub symbclean {
14357:     my $symb=shift;
14358:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
14359: # remove version from map
14360:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
14361: 
14362: # remove version from URL
14363:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
14364: 
14365: # remove wrapper
14366: 
14367:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
14368:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
14369:     return $symb;
14370: }
14371: 
14372: # ---------------------------------------------- Split symb to find map and url
14373: 
14374: sub encode_symb {
14375:     my ($map,$resid,$url)=@_;
14376:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
14377: }
14378: 
14379: sub decode_symb {
14380:     my $symb=shift;
14381:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
14382:     my ($map,$resid,$url)=split(/___/,$symb);
14383:     return (&fixversion($map),$resid,&fixversion($url));
14384: }
14385: 
14386: sub fixversion {
14387:     my $fn=shift;
14388:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
14389:     my %bighash;
14390:     my $uri=&clutter($fn);
14391:     my $key=$env{'request.course.id'}.'_'.$uri;
14392: # is this cached?
14393:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
14394:     if (defined($cached)) { return $result; }
14395: # unfortunately not cached, or expired
14396:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
14397: 	    &GDBM_READER(),0640)) {
14398:  	if ($bighash{'version_'.$uri}) {
14399:  	    my $version=$bighash{'version_'.$uri};
14400:  	    unless (($version eq 'mostrecent') || 
14401: 		    ($version==&getversion($uri))) {
14402:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
14403:  	    }
14404:  	}
14405:  	untie %bighash;
14406:     }
14407:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
14408: }
14409: 
14410: sub deversion {
14411:     my $url=shift;
14412:     $url=~s/\.\d+\.(\w+)$/\.$1/;
14413:     return $url;
14414: }
14415: 
14416: # ------------------------------------------------------ Return symb list entry
14417: 
14418: sub symbread {
14419:     my ($thisfn,$donotrecurse,$ignorecachednull,$checkforblock,$possibles,
14420:         $ignoresymbdb,$noenccheck)=@_;
14421:     my $cache_str='request.symbread.cached.'.$thisfn;
14422:     if (defined($env{$cache_str})) {
14423:         unless (ref($possibles) eq 'HASH') {
14424:             if ($ignorecachednull) {
14425:                 return $env{$cache_str} unless ($env{$cache_str} eq '');
14426:             } else {
14427:                 return $env{$cache_str};
14428:             }
14429:         }
14430:     }
14431: # no filename provided? try from environment
14432:     unless ($thisfn) {
14433:         if ($env{'request.symb'}) {
14434:             return $env{$cache_str}=&symbclean($env{'request.symb'});
14435: 	}
14436: 	$thisfn=$env{'request.filename'};
14437:     }
14438:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
14439: # is that filename actually a symb? Verify, clean, and return
14440:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
14441: 	if (&symbverify($thisfn,$1)) {
14442: 	    return $env{$cache_str}=&symbclean($thisfn);
14443: 	}
14444:     }
14445:     $thisfn=declutter($thisfn);
14446:     my %hash;
14447:     my %bighash;
14448:     my $syval='';
14449:     if (($env{'request.course.fn'}) && ($thisfn)) {
14450:         unless ($ignoresymbdb) {
14451:             if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
14452:                           &GDBM_READER(),0640)) {
14453: 	        $syval=$hash{$thisfn};
14454:                 untie(%hash);
14455:             }
14456:             if ($syval && $checkforblock) {
14457:                 my @blockers = &has_comm_blocking('bre',$syval,$thisfn,$ignoresymbdb,$noenccheck);
14458:                 if (@blockers) {
14459:                     $syval='';
14460:                 }
14461:             }
14462:         }
14463: # ---------------------------------------------------------- There was an entry
14464:         if ($syval) {
14465: 	    #unless ($syval=~/\_\d+$/) {
14466: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
14467: 		    #&appenv({'request.ambiguous' => $thisfn});
14468: 		    #return $env{$cache_str}='';
14469: 		#}    
14470: 		#$syval.=$1;
14471: 	    #}
14472:         } else {
14473: # ------------------------------------------------------- Was not in symb table
14474:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
14475:                             &GDBM_READER(),0640)) {
14476: # ---------------------------------------------- Get ID(s) for current resource
14477:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
14478:               unless ($ids) { 
14479:                  $ids=$bighash{'ids_/'.$thisfn};
14480:               }
14481:               unless ($ids) {
14482: # alias?
14483: 		  $ids=$bighash{'mapalias_'.$thisfn};
14484:               }
14485:               if ($ids) {
14486: # ------------------------------------------------------------------- Has ID(s)
14487:                  my @possibilities=split(/\,/,$ids);
14488:                  if ($#possibilities==0) {
14489: # ----------------------------------------------- There is only one possibility
14490: 		     my ($mapid,$resid)=split(/\./,$ids);
14491: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
14492: 						    $resid,$thisfn);
14493:                      if (ref($possibles) eq 'HASH') {
14494:                          unless ($bighash{'randomout_'.$ids} || $env{'request.role.adv'}) {
14495:                              $possibles->{$syval} = 1;
14496:                          }
14497:                      }
14498:                      if ($checkforblock) {
14499:                          unless ($bighash{'randomout_'.$ids} || $env{'request.role.adv'}) {
14500:                              my @blockers = &has_comm_blocking('bre',$syval,$bighash{'src_'.$ids},'',$noenccheck);
14501:                              if (@blockers) {
14502:                                  $syval = '';
14503:                                  untie(%bighash);
14504:                                  return $env{$cache_str}='';
14505:                              }
14506:                          }
14507:                      }
14508:                  } elsif ((!$donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) { 
14509: # ------------------------------------------ There is more than one possibility
14510:                      my $realpossible=0;
14511:                      foreach my $id (@possibilities) {
14512: 			 my $file=$bighash{'src_'.$id};
14513:                          my $canaccess;
14514:                          if (($donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
14515:                              $canaccess = 1;
14516:                          } else { 
14517:                              $canaccess = &allowed('bre',$file);
14518:                          }
14519:                          if ($canaccess) {
14520:          		     my ($mapid,$resid)=split(/\./,$id);
14521:                              if ($bighash{'map_type_'.$mapid} ne 'page') {
14522:                                  my $poss_syval=&encode_symb($bighash{'map_id_'.$mapid},
14523: 						             $resid,$thisfn);
14524:                                  next if ($bighash{'randomout_'.$id} && !$env{'request.role.adv'});
14525:                                  next unless (($noenccheck) || ($bighash{'encrypted_'.$id} eq $env{'request.enc'}));
14526:                                  if ($checkforblock) {
14527:                                      my @blockers = &has_comm_blocking('bre',$poss_syval,$file,'',$noenccheck);
14528:                                      if (@blockers > 0) {
14529:                                          $syval = '';
14530:                                      } else {
14531:                                          $syval = $poss_syval;
14532:                                          $realpossible++;
14533:                                      }
14534:                                  } else {
14535:                                      $syval = $poss_syval;
14536:                                      $realpossible++;
14537:                                  }
14538:                                  if ($syval) {
14539:                                      if (ref($possibles) eq 'HASH') {
14540:                                          $possibles->{$syval} = 1;
14541:                                      }
14542:                                  }
14543:                              }
14544: 			 }
14545:                      }
14546: 		     if ($realpossible!=1) { $syval=''; }
14547:                  } else {
14548:                      $syval='';
14549:                  }
14550: 	      }
14551:               untie(%bighash);
14552:            }
14553:         }
14554:         if ($syval) {
14555: 	    return $env{$cache_str}=$syval;
14556:         }
14557:     }
14558:     &appenv({'request.ambiguous' => $thisfn});
14559:     return $env{$cache_str}='';
14560: }
14561: 
14562: # ---------------------------------------------------------- Return random seed
14563: 
14564: sub numval {
14565:     my $txt=shift;
14566:     $txt=~tr/A-J/0-9/;
14567:     $txt=~tr/a-j/0-9/;
14568:     $txt=~tr/K-T/0-9/;
14569:     $txt=~tr/k-t/0-9/;
14570:     $txt=~tr/U-Z/0-5/;
14571:     $txt=~tr/u-z/0-5/;
14572:     $txt=~s/\D//g;
14573:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
14574:     return int($txt);
14575: }
14576: 
14577: sub numval2 {
14578:     my $txt=shift;
14579:     $txt=~tr/A-J/0-9/;
14580:     $txt=~tr/a-j/0-9/;
14581:     $txt=~tr/K-T/0-9/;
14582:     $txt=~tr/k-t/0-9/;
14583:     $txt=~tr/U-Z/0-5/;
14584:     $txt=~tr/u-z/0-5/;
14585:     $txt=~s/\D//g;
14586:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
14587:     my $total;
14588:     foreach my $val (@txts) { $total+=$val; }
14589:     if ($_64bit) { if ($total > 2**32) { return -1; } }
14590:     return int($total);
14591: }
14592: 
14593: sub numval3 {
14594:     use integer;
14595:     my $txt=shift;
14596:     $txt=~tr/A-J/0-9/;
14597:     $txt=~tr/a-j/0-9/;
14598:     $txt=~tr/K-T/0-9/;
14599:     $txt=~tr/k-t/0-9/;
14600:     $txt=~tr/U-Z/0-5/;
14601:     $txt=~tr/u-z/0-5/;
14602:     $txt=~s/\D//g;
14603:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
14604:     my $total;
14605:     foreach my $val (@txts) { $total+=$val; }
14606:     if ($_64bit) { $total=(($total<<32)>>32); }
14607:     return $total;
14608: }
14609: 
14610: sub digest {
14611:     my ($data)=@_;
14612:     my $digest=&Digest::MD5::md5($data);
14613:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
14614:     my ($e,$f);
14615:     {
14616:         use integer;
14617:         $e=($a+$b);
14618:         $f=($c+$d);
14619:         if ($_64bit) {
14620:             $e=(($e<<32)>>32);
14621:             $f=(($f<<32)>>32);
14622:         }
14623:     }
14624:     if (wantarray) {
14625: 	return ($e,$f);
14626:     } else {
14627: 	my $g;
14628: 	{
14629: 	    use integer;
14630: 	    $g=($e+$f);
14631: 	    if ($_64bit) {
14632: 		$g=(($g<<32)>>32);
14633: 	    }
14634: 	}
14635: 	return $g;
14636:     }
14637: }
14638: 
14639: sub latest_rnd_algorithm_id {
14640:     return '64bit5';
14641: }
14642: 
14643: sub get_rand_alg {
14644:     my ($courseid)=@_;
14645:     if (!$courseid) { $courseid=(&whichuser())[1]; }
14646:     if ($courseid) {
14647: 	return $env{"course.$courseid.rndseed"};
14648:     }
14649:     return &latest_rnd_algorithm_id();
14650: }
14651: 
14652: sub validCODE {
14653:     my ($CODE)=@_;
14654:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
14655:     return 0;
14656: }
14657: 
14658: sub getCODE {
14659:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
14660:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
14661: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
14662: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
14663: 	return $Apache::lonhomework::history{'resource.CODE'};
14664:     }
14665:     return undef;
14666: }
14667: #
14668: #  Determines the random seed for a specific context:
14669: #
14670: # parameters:
14671: #   symb      - in course context the symb for the seed.
14672: #   course_id - The course id of the form domain_coursenum.
14673: #   domain    - Domain for the user.
14674: #   course    - Course for the user.
14675: #   cenv      - environment of the course.
14676: #
14677: # NOTE:
14678: #   All parameters are picked out of the environment if missing
14679: #   or not defined.
14680: #   If a symb cannot be determined the current time is used instead.
14681: #
14682: #  For a given well defined symb, courside, domain, username,
14683: #  and course environment, the seed is reproducible.
14684: #
14685: sub rndseed {
14686:     my ($symb,$courseid,$domain,$username, $cenv)=@_;
14687:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
14688:     if (!defined($symb)) {
14689: 	unless ($symb=$wsymb) { return time; }
14690:     }
14691:     if (!defined $courseid) { 
14692: 	$courseid=$wcourseid; 
14693:     }
14694:     if (!defined $domain) { $domain=$wdomain; }
14695:     if (!defined $username) { $username=$wusername }
14696: 
14697:     my $which;
14698:     if (defined($cenv->{'rndseed'})) {
14699: 	$which = $cenv->{'rndseed'};
14700:     } else {
14701: 	$which =&get_rand_alg($courseid);
14702:     }
14703:     if (defined(&getCODE())) {
14704: 
14705: 	if ($which eq '64bit5') {
14706: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
14707: 	} elsif ($which eq '64bit4') {
14708: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
14709: 	} else {
14710: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
14711: 	}
14712:     } elsif ($which eq '64bit5') {
14713: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
14714:     } elsif ($which eq '64bit4') {
14715: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
14716:     } elsif ($which eq '64bit3') {
14717: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
14718:     } elsif ($which eq '64bit2') {
14719: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
14720:     } elsif ($which eq '64bit') {
14721: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
14722:     }
14723:     return &rndseed_32bit($symb,$courseid,$domain,$username);
14724: }
14725: 
14726: sub rndseed_32bit {
14727:     my ($symb,$courseid,$domain,$username)=@_;
14728:     {
14729: 	use integer;
14730: 	my $symbchck=unpack("%32C*",$symb) << 27;
14731: 	my $symbseed=numval($symb) << 22;
14732: 	my $namechck=unpack("%32C*",$username) << 17;
14733: 	my $nameseed=numval($username) << 12;
14734: 	my $domainseed=unpack("%32C*",$domain) << 7;
14735: 	my $courseseed=unpack("%32C*",$courseid);
14736: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
14737: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
14738: 	#&logthis("rndseed :$num:$symb");
14739: 	if ($_64bit) { $num=(($num<<32)>>32); }
14740: 	return $num;
14741:     }
14742: }
14743: 
14744: sub rndseed_64bit {
14745:     my ($symb,$courseid,$domain,$username)=@_;
14746:     {
14747: 	use integer;
14748: 	my $symbchck=unpack("%32S*",$symb) << 21;
14749: 	my $symbseed=numval($symb) << 10;
14750: 	my $namechck=unpack("%32S*",$username);
14751: 	
14752: 	my $nameseed=numval($username) << 21;
14753: 	my $domainseed=unpack("%32S*",$domain) << 10;
14754: 	my $courseseed=unpack("%32S*",$courseid);
14755: 	
14756: 	my $num1=$symbchck+$symbseed+$namechck;
14757: 	my $num2=$nameseed+$domainseed+$courseseed;
14758: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
14759: 	#&logthis("rndseed :$num:$symb");
14760: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
14761: 	return "$num1,$num2";
14762:     }
14763: }
14764: 
14765: sub rndseed_64bit2 {
14766:     my ($symb,$courseid,$domain,$username)=@_;
14767:     {
14768: 	use integer;
14769: 	# strings need to be an even # of cahracters long, it it is odd the
14770:         # last characters gets thrown away
14771: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
14772: 	my $symbseed=numval($symb) << 10;
14773: 	my $namechck=unpack("%32S*",$username.' ');
14774: 	
14775: 	my $nameseed=numval($username) << 21;
14776: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
14777: 	my $courseseed=unpack("%32S*",$courseid.' ');
14778: 	
14779: 	my $num1=$symbchck+$symbseed+$namechck;
14780: 	my $num2=$nameseed+$domainseed+$courseseed;
14781: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
14782: 	#&logthis("rndseed :$num:$symb");
14783: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
14784: 	return "$num1,$num2";
14785:     }
14786: }
14787: 
14788: sub rndseed_64bit3 {
14789:     my ($symb,$courseid,$domain,$username)=@_;
14790:     {
14791: 	use integer;
14792: 	# strings need to be an even # of cahracters long, it it is odd the
14793:         # last characters gets thrown away
14794: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
14795: 	my $symbseed=numval2($symb) << 10;
14796: 	my $namechck=unpack("%32S*",$username.' ');
14797: 	
14798: 	my $nameseed=numval2($username) << 21;
14799: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
14800: 	my $courseseed=unpack("%32S*",$courseid.' ');
14801: 	
14802: 	my $num1=$symbchck+$symbseed+$namechck;
14803: 	my $num2=$nameseed+$domainseed+$courseseed;
14804: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
14805: 	#&logthis("rndseed :$num1:$num2:$_64bit");
14806: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
14807: 	
14808: 	return "$num1:$num2";
14809:     }
14810: }
14811: 
14812: sub rndseed_64bit4 {
14813:     my ($symb,$courseid,$domain,$username)=@_;
14814:     {
14815: 	use integer;
14816: 	# strings need to be an even # of cahracters long, it it is odd the
14817:         # last characters gets thrown away
14818: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
14819: 	my $symbseed=numval3($symb) << 10;
14820: 	my $namechck=unpack("%32S*",$username.' ');
14821: 	
14822: 	my $nameseed=numval3($username) << 21;
14823: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
14824: 	my $courseseed=unpack("%32S*",$courseid.' ');
14825: 	
14826: 	my $num1=$symbchck+$symbseed+$namechck;
14827: 	my $num2=$nameseed+$domainseed+$courseseed;
14828: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
14829: 	#&logthis("rndseed :$num1:$num2:$_64bit");
14830: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
14831: 	
14832: 	return "$num1:$num2";
14833:     }
14834: }
14835: 
14836: sub rndseed_64bit5 {
14837:     my ($symb,$courseid,$domain,$username)=@_;
14838:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
14839:     return "$num1:$num2";
14840: }
14841: 
14842: sub rndseed_CODE_64bit {
14843:     my ($symb,$courseid,$domain,$username)=@_;
14844:     {
14845: 	use integer;
14846: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
14847: 	my $symbseed=numval2($symb);
14848: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
14849: 	my $CODEseed=numval(&getCODE());
14850: 	my $courseseed=unpack("%32S*",$courseid.' ');
14851: 	my $num1=$symbseed+$CODEchck;
14852: 	my $num2=$CODEseed+$courseseed+$symbchck;
14853: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
14854: 	#&logthis("rndseed :$num1:$num2:$symb");
14855: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
14856: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
14857: 	return "$num1:$num2";
14858:     }
14859: }
14860: 
14861: sub rndseed_CODE_64bit4 {
14862:     my ($symb,$courseid,$domain,$username)=@_;
14863:     {
14864: 	use integer;
14865: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
14866: 	my $symbseed=numval3($symb);
14867: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
14868: 	my $CODEseed=numval3(&getCODE());
14869: 	my $courseseed=unpack("%32S*",$courseid.' ');
14870: 	my $num1=$symbseed+$CODEchck;
14871: 	my $num2=$CODEseed+$courseseed+$symbchck;
14872: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
14873: 	#&logthis("rndseed :$num1:$num2:$symb");
14874: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
14875: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
14876: 	return "$num1:$num2";
14877:     }
14878: }
14879: 
14880: sub rndseed_CODE_64bit5 {
14881:     my ($symb,$courseid,$domain,$username)=@_;
14882:     my $code = &getCODE();
14883:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
14884:     return "$num1:$num2";
14885: }
14886: 
14887: sub setup_random_from_rndseed {
14888:     my ($rndseed)=@_;
14889:     if ($rndseed =~/([,:])/) {
14890:         my ($num1,$num2) = map { abs($_); } (split(/[,:]/,$rndseed));
14891:         if ((!$num1) || (!$num2) || ($num1 > 2147483562) || ($num2 > 2147483398)) {
14892:             &Math::Random::random_set_seed_from_phrase($rndseed);
14893:         } else {
14894:             &Math::Random::random_set_seed($num1,$num2);
14895:         }
14896:     } else {
14897: 	&Math::Random::random_set_seed_from_phrase($rndseed);
14898:     }
14899: }
14900: 
14901: sub latest_receipt_algorithm_id {
14902:     return 'receipt3';
14903: }
14904: 
14905: sub recunique {
14906:     my $fucourseid=shift;
14907:     my $unique;
14908:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
14909: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
14910: 	$unique=$env{"course.$fucourseid.internal.encseed"};
14911:     } else {
14912: 	$unique=$perlvar{'lonReceipt'};
14913:     }
14914:     return unpack("%32C*",$unique);
14915: }
14916: 
14917: sub recprefix {
14918:     my $fucourseid=shift;
14919:     my $prefix;
14920:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
14921: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
14922: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
14923:     } else {
14924: 	$prefix=$perlvar{'lonHostID'};
14925:     }
14926:     return unpack("%32C*",$prefix);
14927: }
14928: 
14929: sub ireceipt {
14930:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
14931: 
14932:     my $return =&recprefix($fucourseid).'-';
14933: 
14934:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
14935: 	$env{'request.state'} eq 'construct') {
14936: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
14937: 	return $return;
14938:     }
14939: 
14940:     my $cuname=unpack("%32C*",$funame);
14941:     my $cudom=unpack("%32C*",$fudom);
14942:     my $cucourseid=unpack("%32C*",$fucourseid);
14943:     my $cusymb=unpack("%32C*",$fusymb);
14944:     my $cunique=&recunique($fucourseid);
14945:     my $cpart=unpack("%32S*",$part);
14946:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
14947: 
14948: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
14949: 			       
14950: 	$return.= ($cunique%$cuname+
14951: 		   $cunique%$cudom+
14952: 		   $cusymb%$cuname+
14953: 		   $cusymb%$cudom+
14954: 		   $cucourseid%$cuname+
14955: 		   $cucourseid%$cudom+
14956: 		   $cpart%$cuname+
14957: 		   $cpart%$cudom);
14958:     } else {
14959: 	$return.= ($cunique%$cuname+
14960: 		   $cunique%$cudom+
14961: 		   $cusymb%$cuname+
14962: 		   $cusymb%$cudom+
14963: 		   $cucourseid%$cuname+
14964: 		   $cucourseid%$cudom);
14965:     }
14966:     return $return;
14967: }
14968: 
14969: sub receipt {
14970:     my ($part)=@_;
14971:     my ($symb,$courseid,$domain,$name) = &whichuser();
14972:     return &ireceipt($name,$domain,$courseid,$symb,$part);
14973: }
14974: 
14975: sub whichuser {
14976:     my ($passedsymb)=@_;
14977:     my ($symb,$courseid,$domain,$name,$publicuser);
14978:     if (defined($env{'form.grade_symb'})) {
14979: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
14980: 	my $allowed=&allowed('vgr',$tmp_courseid);
14981: 	if (!$allowed &&
14982: 	    exists($env{'request.course.sec'}) &&
14983: 	    $env{'request.course.sec'} !~ /^\s*$/) {
14984: 	    $allowed=&allowed('vgr',$tmp_courseid.
14985: 			      '/'.$env{'request.course.sec'});
14986: 	}
14987: 	if ($allowed) {
14988: 	    ($symb)=&get_env_multiple('form.grade_symb');
14989: 	    $courseid=$tmp_courseid;
14990: 	    ($domain)=&get_env_multiple('form.grade_domain');
14991: 	    ($name)=&get_env_multiple('form.grade_username');
14992: 	    return ($symb,$courseid,$domain,$name,$publicuser);
14993: 	}
14994:     }
14995:     if (!$passedsymb) {
14996: 	$symb=&symbread();
14997:     } else {
14998: 	$symb=$passedsymb;
14999:     }
15000:     $courseid=$env{'request.course.id'};
15001:     $domain=$env{'user.domain'};
15002:     $name=$env{'user.name'};
15003:     if ($name eq 'public' && $domain eq 'public') {
15004: 	if (!defined($env{'form.username'})) {
15005: 	    $env{'form.username'}.=time.rand(10000000);
15006: 	}
15007: 	$name.=$env{'form.username'};
15008:     }
15009:     return ($symb,$courseid,$domain,$name,$publicuser);
15010: 
15011: }
15012: 
15013: # ------------------------------------------------------------ Serves up a file
15014: # returns either the contents of the file or 
15015: # -1 if the file doesn't exist
15016: #
15017: # if the target is a file that was uploaded via DOCS, 
15018: # a check will be made to see if a current copy exists on the local server,
15019: # if it does this will be served, otherwise a copy will be retrieved from
15020: # the home server for the course and stored in /home/httpd/html/userfiles on
15021: # the local server.   
15022: 
15023: sub getfile {
15024:     my ($file) = @_;
15025:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
15026:     &repcopy($file);
15027:     return &readfile($file);
15028: }
15029: 
15030: sub repcopy_userfile {
15031:     my ($file)=@_;
15032:     my $londocroot = $perlvar{'lonDocRoot'};
15033:     if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
15034:     if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
15035:     my ($cdom,$cnum,$filename) = 
15036: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
15037:     my $uri="/uploaded/$cdom/$cnum/$filename";
15038:     if (-e "$file") {
15039: # we already have a local copy, check it out
15040: 	my @fileinfo = stat($file);
15041: 	my $rtncode;
15042: 	my $info;
15043: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
15044: 	if ($lwpresp ne 'ok') {
15045: # there is no such file anymore, even though we had a local copy
15046: 	    if ($rtncode eq '404') {
15047: 		unlink($file);
15048: 	    }
15049: 	    return -1;
15050: 	}
15051: 	if ($info < $fileinfo[9]) {
15052: # nice, the file we have is up-to-date, just say okay
15053: 	    return 'ok';
15054: 	} else {
15055: # the file is outdated, get rid of it
15056: 	    unlink($file);
15057: 	}
15058:     }
15059: # one way or the other, at this point, we don't have the file
15060: # construct the correct path for the file
15061:     my @parts = ($cdom,$cnum); 
15062:     if ($filename =~ m|^(.+)/[^/]+$|) {
15063: 	push @parts, split(/\//,$1);
15064:     }
15065:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
15066:     foreach my $part (@parts) {
15067: 	$path .= '/'.$part;
15068: 	if (!-e $path) {
15069: 	    mkdir($path,0770);
15070: 	}
15071:     }
15072: # now the path exists for sure
15073: # get a user agent
15074:     my $transferfile=$file.'.in.transfer';
15075: # FIXME: this should flock
15076:     if (-e $transferfile) { return 'ok'; }
15077:     my $request;
15078:     $uri=~s/^\///;
15079:     my $homeserver = &homeserver($cnum,$cdom);
15080:     my $hostname = &hostname($homeserver);
15081:     my $protocol = $protocol{$homeserver};
15082:     $protocol = 'http' if ($protocol ne 'https');
15083:     $request=new HTTP::Request('GET',$protocol.'://'.$hostname.'/raw/'.$uri);
15084:     my $response = &LONCAPA::LWPReq::makerequest($homeserver,$request,$transferfile,\%perlvar,'',0,1);
15085: # did it work?
15086:     if ($response->is_error()) {
15087: 	unlink($transferfile);
15088: 	&logthis("Userfile repcopy failed for $uri");
15089: 	return -1;
15090:     }
15091: # worked, rename the transfer file
15092:     rename($transferfile,$file);
15093:     return 'ok';
15094: }
15095: 
15096: sub tokenwrapper {
15097:     my $uri=shift;
15098:     $uri=~s|^https?\://([^/]+)||;
15099:     $uri=~s|^/||;
15100:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
15101:     my $token=$1;
15102:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
15103:     if ($udom && $uname && $file) {
15104: 	$file=~s|(\?\.*)*$||;
15105:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
15106:         my $homeserver = &homeserver($uname,$udom);
15107:         my $hostname = &hostname($homeserver);
15108:         my $protocol = $protocol{$homeserver};
15109:         $protocol = 'http' if ($protocol ne 'https');
15110:         return $protocol.'://'.$hostname.'/'.$uri.
15111:                (($uri=~/\?/)?'&':'?').'token='.$token.
15112:                                '&tokenissued='.$perlvar{'lonHostID'};
15113:     } else {
15114:         return '/adm/notfound.html';
15115:     }
15116: }
15117: 
15118: # call with reqtype HEAD: get last modification time
15119: # call with reqtype GET: get the file contents
15120: # Do not call this with reqtype GET for large files! It loads everything into memory
15121: #
15122: sub getuploaded {
15123:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
15124:     $uri=~s/^\///;
15125:     my $homeserver = &homeserver($cnum,$cdom);
15126:     my $hostname = &hostname($homeserver);
15127:     my $protocol = $protocol{$homeserver};
15128:     $protocol = 'http' if ($protocol ne 'https');
15129:     $uri = $protocol.'://'.$hostname.'/raw/'.$uri;
15130:     my $request=new HTTP::Request($reqtype,$uri);
15131:     my $response=&LONCAPA::LWPReq::makerequest($homeserver,$request,'',\%perlvar,'',0,1);
15132:     $$rtncode = $response->code;
15133:     if (! $response->is_success()) {
15134: 	return 'failed';
15135:     }      
15136:     if ($reqtype eq 'HEAD') {
15137: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
15138:     } elsif ($reqtype eq 'GET') {
15139: 	$$info = $response->content;
15140:     }
15141:     return 'ok';
15142: }
15143: 
15144: sub readfile {
15145:     my $file = shift;
15146:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
15147:     my $fh;
15148:     open($fh,"<",$file);
15149:     my $a='';
15150:     while (my $line = <$fh>) { $a .= $line; }
15151:     return $a;
15152: }
15153: 
15154: sub filelocation {
15155:     my ($dir,$file) = @_;
15156:     my $location;
15157:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
15158: 
15159:     if ($file =~ m-^/adm/-) {
15160: 	$file=~s-^/adm/wrapper/-/-;
15161: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
15162:     }
15163: 
15164:     if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
15165:         $location = $file;
15166:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
15167:         my ($udom,$uname,$filename)=
15168:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
15169:         my $home=&homeserver($uname,$udom);
15170:         my $is_me=0;
15171:         my @ids=&current_machine_ids();
15172:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
15173:         if ($is_me) {
15174:   	    $location=propath($udom,$uname).'/userfiles/'.$filename;
15175:         } else {
15176:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
15177:   	      $udom.'/'.$uname.'/'.$filename;
15178:         }
15179:     } elsif ($file =~ m-^/adm/-) {
15180: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
15181:     } else {
15182:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
15183:         $file=~s:^/(res|priv)/:/:;
15184:         my $space=$1;
15185:         if ( !( $file =~ m:^/:) ) {
15186:             $location = $dir. '/'.$file;
15187:         } else {
15188:             $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
15189:         }
15190:     }
15191:     $location=~s://+:/:g; # remove duplicate /
15192:     while ($location=~m{/\.\./}) {
15193: 	if ($location =~ m{/[^/]+/\.\./}) {
15194: 	    $location=~ s{/[^/]+/\.\./}{/}g;
15195: 	} else {
15196: 	    $location=~ s{/\.\./}{/}g;
15197: 	}
15198:     } #remove dir/..
15199:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
15200:     return $location;
15201: }
15202: 
15203: sub hreflocation {
15204:     my ($dir,$file)=@_;
15205:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
15206: 	$file=filelocation($dir,$file);
15207:     } elsif ($file=~m-^/adm/-) {
15208: 	$file=~s-^/adm/wrapper/-/-;
15209: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
15210:     }
15211:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
15212: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
15213:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
15214: 	$file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
15215: 	        {/uploaded/$1/$2/}x;
15216:     }
15217:     if ($file=~ m{^/userfiles/}) {
15218: 	$file =~ s{^/userfiles/}{/uploaded/};
15219:     }
15220:     return $file;
15221: }
15222: 
15223: 
15224: 
15225: 
15226: 
15227: sub current_machine_domains {
15228:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
15229: }
15230: 
15231: sub machine_domains {
15232:     my ($hostname) = @_;
15233:     my @domains;
15234:     my %hostname = &all_hostnames();
15235:     while( my($id, $name) = each(%hostname)) {
15236: #	&logthis("-$id-$name-$hostname-");
15237: 	if ($hostname eq $name) {
15238: 	    push(@domains,&host_domain($id));
15239: 	}
15240:     }
15241:     return @domains;
15242: }
15243: 
15244: sub current_machine_ids {
15245:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
15246: }
15247: 
15248: sub machine_ids {
15249:     my ($hostname) = @_;
15250:     $hostname ||= &hostname($perlvar{'lonHostID'});
15251:     my @ids;
15252:     my %name_to_host = &all_names();
15253:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
15254: 	return @{ $name_to_host{$hostname} };
15255:     }
15256:     return;
15257: }
15258: 
15259: sub additional_machine_domains {
15260:     my @domains;
15261:     if (-e "$perlvar{'lonTabDir'}/expected_domains.tab") {
15262:         if (open(my $fh,"<","$perlvar{'lonTabDir'}/expected_domains.tab")) {
15263:             while (my $line = <$fh>) {
15264:                 chomp($line);           
15265:                 $line =~ s/\s//g;
15266:                 push(@domains,$line);
15267:             }
15268:             close($fh);
15269:         }
15270:     }
15271:     return @domains;
15272: }
15273: 
15274: sub default_login_domain {
15275:     my $domain = $perlvar{'lonDefDomain'};
15276:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
15277:     foreach my $posdom (&current_machine_domains(),
15278:                         &additional_machine_domains()) {
15279:         if (lc($posdom) eq lc($testdomain)) {
15280:             $domain=$posdom;
15281:             last;
15282:         }
15283:     }
15284:     return $domain;
15285: }
15286: 
15287: sub shared_institution {
15288:     my ($dom,$lonhost) = @_;
15289:     if ($lonhost eq '') {
15290:         $lonhost = $perlvar{'lonHostID'};
15291:     }
15292:     my $same_intdom;
15293:     my $hostintdom = &internet_dom($lonhost);
15294:     if ($hostintdom ne '') {
15295:         my %iphost = &get_iphost();
15296:         my $primary_id = &domain($dom,'primary');
15297:         my $primary_ip = &get_host_ip($primary_id);
15298:         if (ref($iphost{$primary_ip}) eq 'ARRAY') {
15299:             foreach my $id (@{$iphost{$primary_ip}}) {
15300:                 my $intdom = &internet_dom($id);
15301:                 if ($intdom eq $hostintdom) {
15302:                     $same_intdom = 1;
15303:                     last;
15304:                 }
15305:             }
15306:         }
15307:     }
15308:     return $same_intdom;
15309: }
15310: 
15311: sub uses_sts {
15312:     my ($ignore_cache) = @_;
15313:     my $lonhost = $perlvar{'lonHostID'};
15314:     my $hostname = &hostname($lonhost);
15315:     my $sts_on;
15316:     if ($protocol{$lonhost} eq 'https') {
15317:         my $cachetime = 12*3600;
15318:         if (!$ignore_cache) {
15319:             ($sts_on,my $cached)=&is_cached_new('stspolicy',$lonhost);
15320:             if (defined($cached)) {
15321:                 return $sts_on;
15322:             }
15323:         }
15324:         my $url = $protocol{$lonhost}.'://'.$hostname.'/index.html';
15325:         my $request=new HTTP::Request('HEAD',$url);
15326:         my $response=&LONCAPA::LWPReq::makerequest($lonhost,$request,'',\%perlvar,'','','',1);
15327:         if ($response->is_success) {
15328:             my $has_sts = $response->header('Strict-Transport-Security');
15329:             if ($has_sts eq '') {
15330:                 $sts_on = 0;
15331:             } else {
15332:                 if ($has_sts =~ /\Qmax-age=\E(\d+)/) {
15333:                     my $maxage = $1;
15334:                     if ($maxage) {
15335:                         $sts_on = 1;
15336:                     } else {
15337:                         $sts_on = 0;
15338:                     }
15339:                 } else {
15340:                     $sts_on = 0;
15341:                 }
15342:             }
15343:             return &do_cache_new('stspolicy',$lonhost,$sts_on,$cachetime);
15344:         }
15345:     }
15346:     return;
15347: }
15348: 
15349: sub waf_allssl {
15350:     my ($host_name) = @_;
15351:     my $alias = &get_proxy_alias();
15352:     if ($host_name eq '') {
15353:         $host_name = $ENV{'SERVER_NAME'};
15354:     }
15355:     if (($host_name ne '') && ($alias eq $host_name)) {
15356:         my $serverhomedom = &host_domain($perlvar{'lonHostID'});
15357:         my %defdomdefaults = &get_domain_defaults($serverhomedom);
15358:         if ($defdomdefaults{'waf_sslopt'}) {
15359:             return $defdomdefaults{'waf_sslopt'};
15360:         }
15361:     }
15362:     return;
15363: }
15364: 
15365: sub get_requestor_ip {
15366:     my ($r,$nolookup,$noproxy) = @_;
15367:     my $from_ip;
15368:     if (ref($r)) {
15369:         if ($r->can('useragent_ip')) {
15370:             if ($noproxy && $r->can('client_ip')) {
15371:                 $from_ip = $r->client_ip();
15372:             } else {
15373:                 $from_ip = $r->useragent_ip();
15374:             }
15375:         } elsif ($r->connection->can('remote_ip')) {
15376:             $from_ip = $r->connection->remote_ip();
15377:         } else {
15378:             $from_ip = $r->get_remote_host($nolookup);
15379:         }
15380:     } else {
15381:         $from_ip = $ENV{'REMOTE_ADDR'};
15382:     }
15383:     return $from_ip if ($noproxy); 
15384:     # Who controls proxy settings for server
15385:     my $dom_in_use = $Apache::lonnet::perlvar{'lonDefDomain'};
15386:     my $proxyinfo = &get_proxy_settings($dom_in_use);
15387:     if ((ref($proxyinfo) eq 'HASH') && ($from_ip)) {
15388:         if ($proxyinfo->{'vpnint'}) {
15389:             if (&ip_match($from_ip,$proxyinfo->{'vpnint'})) {
15390:                 return $from_ip;
15391:             }
15392:         }
15393:         if ($proxyinfo->{'trusted'}) {
15394:             if (&ip_match($from_ip,$proxyinfo->{'trusted'})) {
15395:                 my $ipheader = $proxyinfo->{'ipheader'};
15396:                 my ($ip,$xfor);
15397:                 if (ref($r)) {
15398:                     if ($ipheader) {
15399:                         $ip = $r->headers_in->{$ipheader};
15400:                     }
15401:                     $xfor = $r->headers_in->{'X-Forwarded-For'};
15402:                 } else {
15403:                     if ($ipheader) {
15404:                         $ip = $ENV{'HTTP_'.uc($ipheader)};
15405:                     }
15406:                     $xfor = $ENV{'HTTP_X_FORWARDED_FOR'};
15407:                 }
15408:                 if (($ip eq '') && ($xfor ne '')) {
15409:                     foreach my $poss_ip (reverse(split(/\s*,\s*/,$xfor))) {
15410:                         unless (&ip_match($poss_ip,$proxyinfo->{'trusted'})) {
15411:                             $ip = $poss_ip;
15412:                             last;
15413:                         }
15414:                     }
15415:                 }
15416:                 if ($ip ne '') {
15417:                     return $ip;
15418:                 }
15419:             }
15420:         }
15421:     }
15422:     return $from_ip;
15423: }
15424: 
15425: sub get_proxy_settings {
15426:     my ($dom_in_use) = @_;
15427:     my %domdefaults = &get_domain_defaults($dom_in_use);
15428:     my $proxyinfo = {
15429:                        ipheader => $domdefaults{'waf_ipheader'},
15430:                        trusted  => $domdefaults{'waf_trusted'},
15431:                        vpnint   => $domdefaults{'waf_vpnint'},
15432:                        vpnext   => $domdefaults{'waf_vpnext'},
15433:                        sslopt   => $domdefaults{'waf_sslopt'},
15434:                     };
15435:     return $proxyinfo;
15436: }
15437: 
15438: sub ip_match {
15439:     my ($ip,$pattern_str) = @_;
15440:     $ip=Net::CIDR::cidrvalidate($ip);
15441:     if ($ip) {
15442:         return Net::CIDR::cidrlookup($ip,split(/\s*,\s*/,$pattern_str));
15443:     }
15444:     return;
15445: }
15446: 
15447: sub get_proxy_alias {
15448:     my ($lonid) = @_;
15449:     if ($lonid eq '') {
15450:         $lonid = $perlvar{'lonHostID'};
15451:     }
15452:     if (!defined(&hostname($lonid))) {
15453:         return;
15454:     }
15455:     if ($lonid ne '') {
15456:         my ($alias,$cached) = &is_cached_new('proxyalias',$lonid);
15457:         if ($cached) {
15458:             return $alias;
15459:         }
15460:         my $dom = &host_domain($lonid);
15461:         if ($dom ne '') {
15462:             my $cachetime = 60*60*24;
15463:             my %domconfig =
15464:                 &get_dom('configuration',['wafproxy'],$dom);
15465:             if (ref($domconfig{'wafproxy'}) eq 'HASH') {
15466:                 if (ref($domconfig{'wafproxy'}{'alias'}) eq 'HASH') {
15467:                     $alias = $domconfig{'wafproxy'}{'alias'}{$lonid};
15468:                 }
15469:             }
15470:             return &do_cache_new('proxyalias',$lonid,$alias,$cachetime);
15471:         }
15472:     }
15473:     return;
15474: }
15475: 
15476: sub use_proxy_alias {
15477:     my ($r,$lonid) = @_;
15478:     my $alias = &get_proxy_alias($lonid);
15479:     if ($alias) {
15480:         my $dom = &host_domain($lonid);
15481:         if ($dom ne '') {
15482:             my $proxyinfo = &get_proxy_settings($dom);
15483:             my ($vpnint,$remote_ip);
15484:             if (ref($proxyinfo) eq 'HASH') {
15485:                 $vpnint = $proxyinfo->{'vpnint'};
15486:                 if ($vpnint) {
15487:                     $remote_ip = &get_requestor_ip($r,1,1);
15488:                 }
15489:             }
15490:             unless ($vpnint && &ip_match($remote_ip,$vpnint)) {
15491:                 return $alias;
15492:             }
15493:         }
15494:     }
15495:     return;
15496: }
15497: 
15498: sub alias_sso {
15499:     my ($lonid) = @_;
15500:     if ($lonid eq '') {
15501:         $lonid = $perlvar{'lonHostID'};
15502:     }
15503:     if (!defined(&hostname($lonid))) {
15504:         return;
15505:     }
15506:     if ($lonid ne '') {
15507:         my ($use_alias,$cached) = &is_cached_new('proxysaml',$lonid);
15508:         if ($cached) {
15509:             return $use_alias;
15510:         }
15511:         my $dom = &host_domain($lonid);
15512:         if ($dom ne '') {
15513:             my $cachetime = 60*60*24;
15514:             my %domconfig =
15515:                 &get_dom('configuration',['wafproxy'],$dom);
15516:             if (ref($domconfig{'wafproxy'}) eq 'HASH') {
15517:                 if (ref($domconfig{'wafproxy'}{'saml'}) eq 'HASH') {
15518:                     $use_alias = $domconfig{'wafproxy'}{'saml'}{$lonid};
15519:                 }
15520:             }
15521:             return &do_cache_new('proxysaml',$lonid,$use_alias,$cachetime);
15522:         }
15523:     }
15524:     return;
15525: }
15526: 
15527: sub get_saml_landing {
15528:     my ($lonid) = @_;
15529:     if ($lonid eq '') {
15530:         my $defdom = &default_login_domain();
15531:         my @hosts = &current_machine_ids();
15532:         if (@hosts > 1) {
15533:             foreach my $hostid (@hosts) {
15534:                 if (&host_domain($hostid) eq $defdom) {
15535:                     $lonid = $hostid;
15536:                     last;
15537:                 }
15538:             }
15539:         } else {
15540:             $lonid = $perlvar{'lonHostID'};
15541:         }
15542:         if ($lonid) {
15543:             unless (&host_domain($lonid) eq $defdom) {
15544:                 return;
15545:             }
15546:         } else {
15547:             return;
15548:         }
15549:     } elsif (!defined(&hostname($lonid))) {
15550:         return;
15551:     }
15552:     my ($landing,$cached) = &is_cached_new('samllanding',$lonid);
15553:     if ($cached) {
15554:         return $landing;
15555:     }
15556:     my $dom = &host_domain($lonid);
15557:     if ($dom ne '') {
15558:         my $cachetime = 60*60*24;
15559:         my %domconfig =
15560:             &get_dom('configuration',['login'],$dom);
15561:         if (ref($domconfig{'login'}) eq 'HASH') {
15562:             if (ref($domconfig{'login'}{'saml'}) eq 'HASH') {
15563:                 if (ref($domconfig{'login'}{'saml'}{$lonid}) eq 'HASH') {
15564:                     $landing = 1;
15565:                 }
15566:             }
15567:         }
15568:         return &do_cache_new('samllanding',$lonid,$landing,$cachetime);
15569:     }
15570:     return;
15571: }
15572: 
15573: # ------------------------------------------------------------- Declutters URLs
15574: 
15575: sub declutter {
15576:     my $thisfn=shift;
15577:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
15578:     unless ($thisfn=~m{^/home/httpd/html/priv/}) {
15579:         $thisfn=~s{^/home/httpd/html}{};
15580:     }
15581:     $thisfn=~s/^\///;
15582:     $thisfn=~s|^adm/wrapper/||;
15583:     $thisfn=~s|^adm/coursedocs/showdoc/||;
15584:     $thisfn=~s/^res\///;
15585:     $thisfn=~s/^priv\///;
15586:     unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
15587:         $thisfn=~s/\?.+$//;
15588:     }
15589:     return $thisfn;
15590: }
15591: 
15592: # ------------------------------------------------------------- Clutter up URLs
15593: 
15594: sub clutter {
15595:     my $thisfn='/'.&declutter(shift);
15596:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
15597: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
15598:        $thisfn='/res'.$thisfn; 
15599:     }
15600:     if ($thisfn !~m|^/adm|) {
15601: 	if ($thisfn =~ m|^/ext/|) {
15602: 	    $thisfn='/adm/wrapper'.$thisfn;
15603: 	} else {
15604: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
15605: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
15606: 	    if ($embstyle eq 'ssi'
15607: 		|| ($embstyle eq 'hdn')
15608: 		|| ($embstyle eq 'rat')
15609: 		|| ($embstyle eq 'prv')
15610: 		|| ($embstyle eq 'ign')) {
15611: 		#do nothing with these
15612: 	    } elsif (($embstyle eq 'img') 
15613: 		|| ($embstyle eq 'emb')
15614: 		|| ($embstyle eq 'wrp')) {
15615: 		$thisfn='/adm/wrapper'.$thisfn;
15616: 	    } elsif ($embstyle eq 'unk'
15617: 		     && $thisfn!~/\.(sequence|page)$/) {
15618: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
15619: 	    } else {
15620: #		&logthis("Got a blank emb style");
15621: 	    }
15622: 	}
15623:     } elsif ($thisfn =~ m{^/adm/$match_domain/$match_courseid/\d+/ext\.tool$}) {
15624:         $thisfn='/adm/wrapper'.$thisfn;
15625:     }
15626:     return $thisfn;
15627: }
15628: 
15629: sub clutter_with_no_wrapper {
15630:     my $uri = &clutter(shift);
15631:     if ($uri =~ m-^/adm/-) {
15632: 	$uri =~ s-^/adm/wrapper/-/-;
15633: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
15634:     }
15635:     return $uri;
15636: }
15637: 
15638: sub freeze_escape {
15639:     my ($value)=@_;
15640:     if (ref($value)) {
15641: 	$value=&nfreeze($value);
15642: 	return '__FROZEN__'.&escape($value);
15643:     }
15644:     return &escape($value);
15645: }
15646: 
15647: 
15648: sub thaw_unescape {
15649:     my ($value)=@_;
15650:     if ($value =~ /^__FROZEN__/) {
15651: 	substr($value,0,10,undef);
15652: 	$value=&unescape($value);
15653: 	return &thaw($value);
15654:     }
15655:     return &unescape($value);
15656: }
15657: 
15658: sub correct_line_ends {
15659:     my ($result)=@_;
15660:     $$result =~s/\r\n/\n/mg;
15661:     $$result =~s/\r/\n/mg;
15662: }
15663: # ================================================================ Main Program
15664: 
15665: sub goodbye {
15666:    &logthis("Starting Shut down");
15667: #not converted to using infrastruture and probably shouldn't be
15668:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
15669: #converted
15670: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
15671:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
15672: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
15673: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
15674: #1.1 only
15675: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
15676: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
15677: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
15678: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
15679:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
15680:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
15681:    &logthis(sprintf("%-20s is %s",'hits',$hits));
15682:    &flushcourselogs();
15683:    &logthis("Shutting down");
15684: }
15685: 
15686: sub get_dns {
15687:     my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
15688:     if (!$ignore_cache) {
15689: 	my ($content,$cached)=
15690: 	    &is_cached_new('dns',$url);
15691: 	if ($cached) {
15692: 	    &$func($content,$hashref);
15693: 	    return;
15694: 	}
15695:     }
15696: 
15697:     my %alldns;
15698:     if (open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab")) {
15699:         foreach my $dns (<$config>) {
15700: 	    next if ($dns !~ /^\^(\S*)/x);
15701:             my $line = $1;
15702:             my ($host,$protocol) = split(/:/,$line);
15703:             if ($protocol ne 'https') {
15704:                 $protocol = 'http';
15705:             }
15706: 	    $alldns{$host} = $protocol;
15707:         }
15708:         close($config);
15709:     }
15710:     while (%alldns) {
15711: 	my ($dns) = sort { $b cmp $a } keys(%alldns);
15712:         my ($contents,@content);
15713:         if ($dns eq Sys::Hostname::FQDN::fqdn()) {
15714:             my $command = (split('/',$url))[3];
15715:             my ($dir,$file) = &parse_getdns_url($command,$url);
15716:             delete($alldns{$dns});
15717:             next if (($dir eq '') || ($file eq ''));
15718:             if (open(my $config,'<',"$dir/$file")) {
15719:                 @content = <$config>;
15720:                 close($config);
15721:             }
15722:             if ($url eq '/adm/dns/loncapaCRL') {
15723:                 $contents = join('',@content);
15724:             }
15725:         } else {
15726: 	    my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
15727:             my $response = &LONCAPA::LWPReq::makerequest('',$request,'',\%perlvar,30,0);
15728:             delete($alldns{$dns});
15729: 	    next if ($response->is_error());
15730:             if ($url eq '/adm/dns/loncapaCRL') {
15731:                 $contents = $response->content;
15732:             } else {
15733:                 @content = split("\n",$response->content);
15734:             }
15735:         }
15736:         if ($url eq '/adm/dns/loncapaCRL') {
15737:             return &$func($contents);
15738:         } else {
15739: 	    unless ($nocache) {
15740: 	        &do_cache_new('dns',$url,\@content,30*24*60*60);
15741: 	    }
15742: 	    &$func(\@content,$hashref);
15743:             return;
15744:         }
15745:     }
15746:     my $which = (split('/',$url,4))[3];
15747:     if ($which eq 'loncapaCRL') {
15748:         my $diskfile = "$perlvar{'lonCertificateDirectory'}/$perlvar{'lonnetCertRevocationList'}";
15749:         if (-e $diskfile) {
15750:             &logthis("unable to contact DNS, on disk file $diskfile not updated");
15751:         } else {
15752:             &logthis("unable to contact DNS, no on disk file $diskfile available");
15753:         }
15754:     } else {
15755:         &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
15756:         if (open(my $config,"<","$perlvar{'lonTabDir'}/dns_$which.tab")) {
15757:             my @content = <$config>;
15758:             close($config);
15759:             &$func(\@content,$hashref);
15760:         }
15761:     }
15762:     return;
15763: }
15764: 
15765: # ------------------------------------------------------Get DNS checksums file
15766: sub parse_dns_checksums_tab {
15767:     my ($lines,$hashref) = @_;
15768:     my $lonhost = $perlvar{'lonHostID'};
15769:     my $machine_dom = &host_domain($lonhost);
15770:     my $loncaparev = &get_server_loncaparev($machine_dom);
15771:     my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
15772:     my $webconfdir = '/etc/httpd/conf';
15773:     if ($distro =~ /^(ubuntu|debian)(\d+)$/) {
15774:         $webconfdir = '/etc/apache2';
15775:     } elsif ($distro =~ /^sles(\d+)$/) {
15776:         if ($1 >= 10) {
15777:             $webconfdir = '/etc/apache2';
15778:         }
15779:     } elsif ($distro =~ /^suse(\d+\.\d+)$/) {
15780:         if ($1 >= 10.0) {
15781:             $webconfdir = '/etc/apache2';
15782:         }
15783:     }
15784:     my ($release,$timestamp) = split(/\-/,$loncaparev);
15785:     my (%chksum,%revnum);
15786:     if (ref($lines) eq 'ARRAY') {
15787:         chomp(@{$lines});
15788:         my $version = shift(@{$lines});
15789:         if ($version eq $release) {  
15790:             foreach my $line (@{$lines}) {
15791:                 my ($file,$version,$shasum) = split(/,/,$line);
15792:                 if ($file =~ m{^/etc/httpd/conf}) {
15793:                     if ($webconfdir eq '/etc/apache2') {
15794:                         $file =~ s{^\Q/etc/httpd/conf/\E}{$webconfdir/};
15795:                     }
15796:                 }
15797:                 $chksum{$file} = $shasum;
15798:                 $revnum{$file} = $version;
15799:             }
15800:             if (ref($hashref) eq 'HASH') {
15801:                 %{$hashref} = (
15802:                                 sums     => \%chksum,
15803:                                 versions => \%revnum,
15804:                               );
15805:             }
15806:         }
15807:     }
15808:     return;
15809: }
15810: 
15811: sub fetch_dns_checksums {
15812:     my %checksums;
15813:     my $machine_dom = &host_domain($perlvar{'lonHostID'});
15814:     my $loncaparev = &get_server_loncaparev($machine_dom,$perlvar{'lonHostID'});
15815:     my ($release,$timestamp) = split(/\-/,$loncaparev);
15816:     &get_dns("/adm/dns/checksums/$release",\&parse_dns_checksums_tab,1,1,
15817:              \%checksums);
15818:     return \%checksums;
15819: }
15820: 
15821: sub fetch_crl_pemfile {
15822:     return &get_dns("/adm/dns/loncapaCRL",\&save_crl_pem,1,1);
15823: }
15824: 
15825: sub save_crl_pem {
15826:     my ($content) = @_;
15827:     my ($msg,$hadchanges);
15828:     if ($content ne '') {
15829:         my $now = time;
15830:         my $lonca = $perlvar{'lonCertificateDirectory'}.'/'.$perlvar{'lonnetCertificateAuthority'};
15831:         my $tmpcrl = $tmpdir.'/'.$perlvar{'lonnetCertRevocationList'}.'_'.$now.'.'.$$.'.tmp';
15832:         if (open(my $fh,'>',"$tmpcrl")) {
15833:             print $fh $content;
15834:             close($fh);
15835:             if (-e $lonca) {
15836:                 if (open(PIPE,"openssl crl -in $tmpcrl -inform pem -CAfile $lonca -noout 2>&1 |")) {
15837:                     my $check = <PIPE>;
15838:                     close(PIPE);
15839:                     chomp($check);
15840:                     if ($check eq 'verify OK') {
15841:                         my $dest = "$perlvar{'lonCertificateDirectory'}/$perlvar{'lonnetCertRevocationList'}";
15842:                         my $backup;
15843:                         if (-e $dest) {
15844:                             if (&File::Copy::move($dest,"$dest.bak")) {
15845:                                 $backup = 'ok';
15846:                             }
15847:                         }
15848:                         if (&File::Copy::move($tmpcrl,$dest)) {
15849:                             $msg = 'ok';
15850:                             if ($backup) {
15851:                                 my (%oldnums,%newnums);
15852:                                 if (open(PIPE, "openssl crl -inform PEM -text -noout -in $dest.bak |grep 'Serial Number' |")) {
15853:                                     while (<PIPE>) {
15854:                                         $oldnums{(split(/:/))[1]} = 1;
15855:                                     }
15856:                                     close(PIPE);
15857:                                 }
15858:                                 if (open(PIPE, "openssl crl -inform PEM -text -noout -in $dest |grep 'Serial Number' |")) {
15859:                                     while(<PIPE>) {
15860:                                         $newnums{(split(/:/))[1]} = 1;
15861:                                     }
15862:                                     close(PIPE);
15863:                                 }
15864:                                 foreach my $key (sort {$b <=> $a } (keys(%newnums))) {
15865:                                     unless (exists($oldnums{$key})) {
15866:                                         $hadchanges = 1;
15867:                                         last;
15868:                                     }
15869:                                 }
15870:                                 unless ($hadchanges) {
15871:                                     foreach my $key (sort {$b <=> $a } (keys(%oldnums))) {
15872:                                         unless (exists($newnums{$key})) {
15873:                                             $hadchanges = 1;
15874:                                             last;
15875:                                         }
15876:                                     }
15877:                                 }
15878:                             }
15879:                         }
15880:                     } else {
15881:                         unlink($tmpcrl);
15882:                     }
15883:                 } else {
15884:                     unlink($tmpcrl);
15885:                 }
15886:             } else {
15887:                 unlink($tmpcrl);
15888:             }
15889:         }
15890:     }
15891:     return ($msg,$hadchanges);
15892: }
15893: 
15894: sub parse_getdns_url {
15895:     my ($command,$url) = @_;
15896:     my $dir = $perlvar{'lonTabDir'};
15897:     my $file;
15898:     if ($command eq 'hosts') {
15899:         $file = 'dns_hosts.tab';
15900:     } elsif ($command eq 'domain') {
15901:         $file = 'dns_domain.tab';
15902:     } elsif ($command eq 'checksums') {
15903:         my $version = (split('/',$url))[4];
15904:         $file = "dns_checksums/$version.tab",
15905:     } elsif ($command eq 'loncapaCRL') {
15906:         $dir = $perlvar{'lonCertificateDirectory'};
15907:         $file = $perlvar{'lonnetCertRevocationList'};
15908:     }
15909:     return ($dir,$file);
15910: }
15911: 
15912: # ------------------------------------------------------------ Read domain file
15913: {
15914:     my $loaded;
15915:     my %domain;
15916: 
15917:     sub parse_domain_tab {
15918: 	my ($lines) = @_;
15919: 	foreach my $line (@$lines) {
15920: 	    next if ($line =~ /^(\#|\s*$ )/x);
15921: 
15922: 	    chomp($line);
15923: 	    my ($name,@elements) = split(/:/,$line,9);
15924: 	    my %this_domain;
15925: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
15926: 			       'lang_def', 'city', 'longi', 'lati',
15927: 			       'primary') {
15928: 		$this_domain{$field} = shift(@elements);
15929: 	    }
15930: 	    $domain{$name} = \%this_domain;
15931: 	}
15932:     }
15933: 
15934:     sub reset_domain_info {
15935: 	undef($loaded);
15936: 	undef(%domain);
15937:     }
15938: 
15939:     sub load_domain_tab {
15940: 	my ($ignore_cache,$nocache) = @_;
15941: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache,$nocache);
15942: 	my $fh;
15943: 	if (open($fh,"<",$perlvar{'lonTabDir'}.'/domain.tab')) {
15944: 	    my @lines = <$fh>;
15945: 	    &parse_domain_tab(\@lines);
15946: 	}
15947: 	close($fh);
15948: 	$loaded = 1;
15949:     }
15950: 
15951:     sub domain {
15952: 	&load_domain_tab() if (!$loaded);
15953: 
15954: 	my ($name,$what) = @_;
15955: 	return if ( !exists($domain{$name}) );
15956: 
15957: 	if (!$what) {
15958: 	    return $domain{$name}{'description'};
15959: 	}
15960: 	return $domain{$name}{$what};
15961:     }
15962: 
15963:     sub domain_info {
15964:         &load_domain_tab() if (!$loaded);
15965:         return %domain;
15966:     }
15967: 
15968: }
15969: 
15970: 
15971: # ------------------------------------------------------------- Read hosts file
15972: {
15973:     my %hostname;
15974:     my %hostdom;
15975:     my %libserv;
15976:     my $loaded;
15977:     my %name_to_host;
15978:     my %internetdom;
15979:     my %LC_dns_serv;
15980: 
15981:     sub parse_hosts_tab {
15982: 	my ($file) = @_;
15983: 	foreach my $configline (@$file) {
15984: 	    next if ($configline =~ /^(\#|\s*$ )/x);
15985:             chomp($configline);
15986: 	    if ($configline =~ /^\^/) {
15987:                 if ($configline =~ /^\^([\w.\-]+)/) {
15988:                     $LC_dns_serv{$1} = 1;
15989:                 }
15990:                 next;
15991:             }
15992: 	    my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
15993: 	    $name=~s/\s//g;
15994: 	    if ($id && $domain && $role && $name) {
15995:                 if ((exists($hostname{$id})) && ($hostname{$id} ne '')) {
15996:                     my $curr = $hostname{$id};
15997:                     my $skip;
15998:                     if (ref($name_to_host{$curr}) eq 'ARRAY') {
15999:                         if (($curr eq $name) && (@{$name_to_host{$curr}} == 1)) {
16000:                             $skip = 1;
16001:                         } else {
16002:                             @{$name_to_host{$curr}} = grep { $_ ne $id } @{$name_to_host{$curr}};
16003:                         }
16004:                     }
16005:                     unless ($skip) {
16006:                         push(@{$name_to_host{$name}},$id);
16007:                     }
16008:                 } else {
16009:                     push(@{$name_to_host{$name}},$id);
16010:                 }
16011: 		$hostname{$id}=$name;
16012: 		$hostdom{$id}=$domain;
16013: 		if ($role eq 'library') { $libserv{$id}=$name; }
16014:                 if (defined($protocol)) {
16015:                     if ($protocol eq 'https') {
16016:                         $protocol{$id} = $protocol;
16017:                     } else {
16018:                         $protocol{$id} = 'http'; 
16019:                     }
16020:                 } else {
16021:                     $protocol{$id} = 'http';
16022:                 }
16023:                 if (defined($intdom)) {
16024:                     $internetdom{$id} = $intdom;
16025:                 }
16026: 	    }
16027: 	}
16028:     }
16029:     
16030:     sub reset_hosts_info {
16031: 	&purge_remembered();
16032: 	&reset_domain_info();
16033: 	&reset_hosts_ip_info();
16034:         undef(%internetdom);
16035: 	undef(%name_to_host);
16036: 	undef(%hostname);
16037: 	undef(%hostdom);
16038: 	undef(%libserv);
16039: 	undef($loaded);
16040:     }
16041: 
16042:     sub load_hosts_tab {
16043: 	my ($ignore_cache,$nocache) = @_;
16044: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache,$nocache);
16045: 	open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab");
16046: 	my @config = <$config>;
16047: 	&parse_hosts_tab(\@config);
16048: 	close($config);
16049: 	$loaded=1;
16050:     }
16051: 
16052:     sub hostname {
16053: 	&load_hosts_tab() if (!$loaded);
16054: 
16055: 	my ($lonid) = @_;
16056: 	return $hostname{$lonid};
16057:     }
16058: 
16059:     sub all_hostnames {
16060: 	&load_hosts_tab() if (!$loaded);
16061: 
16062: 	return %hostname;
16063:     }
16064: 
16065:     sub all_names {
16066:         my ($ignore_cache,$nocache) = @_;
16067: 	&load_hosts_tab($ignore_cache,$nocache) if (!$loaded);
16068: 
16069: 	return %name_to_host;
16070:     }
16071: 
16072:     sub all_host_domain {
16073:         &load_hosts_tab() if (!$loaded);
16074:         return %hostdom;
16075:     }
16076: 
16077:     sub all_host_intdom {
16078:         &load_hosts_tab() if (!$loaded);
16079:         return %internetdom;
16080:     }
16081: 
16082:     sub is_library {
16083: 	&load_hosts_tab() if (!$loaded);
16084: 
16085: 	return exists($libserv{$_[0]});
16086:     }
16087: 
16088:     sub all_library {
16089: 	&load_hosts_tab() if (!$loaded);
16090: 
16091: 	return %libserv;
16092:     }
16093: 
16094:     sub unique_library {
16095: 	#2x reverse removes all hostnames that appear more than once
16096:         my %unique = reverse &all_library();
16097:         return reverse %unique;
16098:     }
16099: 
16100:     sub get_servers {
16101: 	&load_hosts_tab() if (!$loaded);
16102: 
16103: 	my ($domain,$type) = @_;
16104: 	my %possible_hosts = ($type eq 'library') ? %libserv
16105: 	                                          : %hostname;
16106: 	my %result;
16107: 	if (ref($domain) eq 'ARRAY') {
16108: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
16109: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
16110: 		    $result{$host} = $hostname;
16111: 		}
16112: 	    }
16113: 	} else {
16114: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
16115: 		if ($hostdom{$host} eq $domain) {
16116: 		    $result{$host} = $hostname;
16117: 		}
16118: 	    }
16119: 	}
16120: 	return %result;
16121:     }
16122: 
16123:     sub get_unique_servers {
16124:         my %unique = reverse &get_servers(@_);
16125: 	return reverse %unique;
16126:     }
16127: 
16128:     sub host_domain {
16129: 	&load_hosts_tab() if (!$loaded);
16130: 
16131: 	my ($lonid) = @_;
16132: 	return $hostdom{$lonid};
16133:     }
16134: 
16135:     sub all_domains {
16136: 	&load_hosts_tab() if (!$loaded);
16137: 
16138: 	my %seen;
16139: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
16140: 	return @uniq;
16141:     }
16142: 
16143:     sub internet_dom {
16144:         &load_hosts_tab() if (!$loaded);
16145: 
16146:         my ($lonid) = @_;
16147:         return $internetdom{$lonid};
16148:     }
16149: 
16150:     sub is_LC_dns {
16151:         &load_hosts_tab() if (!$loaded);
16152: 
16153:         my ($hostname) = @_;
16154:         return exists($LC_dns_serv{$hostname});
16155:     }
16156: 
16157: }
16158: 
16159: { 
16160:     my %iphost;
16161:     my %name_to_ip;
16162:     my %lonid_to_ip;
16163: 
16164:     sub get_hosts_from_ip {
16165: 	my ($ip) = @_;
16166: 	my %iphosts = &get_iphost();
16167: 	if (ref($iphosts{$ip})) {
16168: 	    return @{$iphosts{$ip}};
16169: 	}
16170: 	return;
16171:     }
16172:     
16173:     sub reset_hosts_ip_info {
16174: 	undef(%iphost);
16175: 	undef(%name_to_ip);
16176: 	undef(%lonid_to_ip);
16177:     }
16178: 
16179:     sub get_host_ip {
16180: 	my ($lonid) = @_;
16181: 	if (exists($lonid_to_ip{$lonid})) {
16182: 	    return $lonid_to_ip{$lonid};
16183: 	}
16184: 	my $name=&hostname($lonid);
16185:    	my $ip = gethostbyname($name);
16186: 	return if (!$ip || length($ip) ne 4);
16187: 	$ip=inet_ntoa($ip);
16188: 	$name_to_ip{$name}   = $ip;
16189: 	$lonid_to_ip{$lonid} = $ip;
16190: 	return $ip;
16191:     }
16192:     
16193:     sub get_iphost {
16194: 	my ($ignore_cache,$nocache) = @_;
16195: 
16196: 	if (!$ignore_cache) {
16197: 	    if (%iphost) {
16198: 		return %iphost;
16199: 	    }
16200: 	    my ($ip_info,$cached)=
16201: 		&is_cached_new('iphost','iphost');
16202: 	    if ($cached) {
16203: 		%iphost      = %{$ip_info->[0]};
16204: 		%name_to_ip  = %{$ip_info->[1]};
16205: 		%lonid_to_ip = %{$ip_info->[2]};
16206: 		return %iphost;
16207: 	    }
16208: 	}
16209: 
16210: 	# get yesterday's info for fallback
16211: 	my %old_name_to_ip;
16212: 	my ($ip_info,$cached)=
16213: 	    &is_cached_new('iphost','iphost');
16214: 	if ($cached) {
16215: 	    %old_name_to_ip = %{$ip_info->[1]};
16216: 	}
16217: 
16218: 	my %name_to_host = &all_names($ignore_cache,$nocache);
16219: 	foreach my $name (keys(%name_to_host)) {
16220: 	    my $ip;
16221: 	    if (!exists($name_to_ip{$name})) {
16222: 		$ip = gethostbyname($name);
16223: 		if (!$ip || length($ip) ne 4) {
16224: 		    if (defined($old_name_to_ip{$name})) {
16225: 			$ip = $old_name_to_ip{$name};
16226: 			&logthis("Can't find $name defaulting to old $ip");
16227: 		    } else {
16228: 			&logthis("Name $name no IP found");
16229: 			next;
16230: 		    }
16231: 		} else {
16232: 		    $ip=inet_ntoa($ip);
16233: 		}
16234: 		$name_to_ip{$name} = $ip;
16235: 	    } else {
16236: 		$ip = $name_to_ip{$name};
16237: 	    }
16238: 	    foreach my $id (@{ $name_to_host{$name} }) {
16239: 		$lonid_to_ip{$id} = $ip;
16240: 	    }
16241: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
16242: 	}
16243:         unless ($nocache) {
16244: 	    &do_cache_new('iphost','iphost',
16245: 		          [\%iphost,\%name_to_ip,\%lonid_to_ip],
16246: 		          48*60*60);
16247:         }
16248: 
16249: 	return %iphost;
16250:     }
16251: 
16252:     #
16253:     #  Given a DNS returns the loncapa host name for that DNS 
16254:     # 
16255:     sub host_from_dns {
16256:         my ($dns) = @_;
16257:         my @hosts;
16258:         my $ip;
16259: 
16260:         if (exists($name_to_ip{$dns})) {
16261:             $ip = $name_to_ip{$dns};
16262:         }
16263:         if (!$ip) {
16264:             $ip = gethostbyname($dns); # Initial translation to IP is in net order.
16265:             if (length($ip) == 4) { 
16266: 	        $ip   = &IO::Socket::inet_ntoa($ip);
16267:             }
16268:         }
16269:         if ($ip) {
16270: 	    @hosts = get_hosts_from_ip($ip);
16271: 	    return $hosts[0];
16272:         }
16273:         return undef;
16274:     }
16275: 
16276:     sub get_internet_names {
16277:         my ($lonid) = @_;
16278:         return if ($lonid eq '');
16279:         my ($idnref,$cached)=
16280:             &is_cached_new('internetnames',$lonid);
16281:         if ($cached) {
16282:             return $idnref;
16283:         }
16284:         my $ip = &get_host_ip($lonid);
16285:         my @hosts = &get_hosts_from_ip($ip);
16286:         my %iphost = &get_iphost();
16287:         my (@idns,%seen);
16288:         foreach my $id (@hosts) {
16289:             my $dom = &host_domain($id);
16290:             my $prim_id = &domain($dom,'primary');
16291:             my $prim_ip = &get_host_ip($prim_id);
16292:             next if ($seen{$prim_ip});
16293:             if (ref($iphost{$prim_ip}) eq 'ARRAY') {
16294:                 foreach my $id (@{$iphost{$prim_ip}}) {
16295:                     my $intdom = &internet_dom($id);
16296:                     unless (grep(/^\Q$intdom\E$/,@idns)) {
16297:                         push(@idns,$intdom);
16298:                     }
16299:                 }
16300:             }
16301:             $seen{$prim_ip} = 1;
16302:         }
16303:         return &do_cache_new('internetnames',$lonid,\@idns,12*60*60);
16304:     }
16305: 
16306: }
16307: 
16308: sub all_loncaparevs {
16309:     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);
16310: }
16311: 
16312: # ---------------------------------------------------------- Read loncaparev table
16313: {
16314:     sub load_loncaparevs { 
16315:         if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
16316:             if (open(my $config,"<","$perlvar{'lonTabDir'}/loncaparevs.tab")) {
16317:                 while (my $configline=<$config>) {
16318:                     chomp($configline);
16319:                     my ($hostid,$loncaparev)=split(/:/,$configline);
16320:                     $loncaparevs{$hostid}=$loncaparev;
16321:                 }
16322:                 close($config);
16323:             }
16324:         }
16325:     }
16326: }
16327: 
16328: # ---------------------------------------------------------- Read serverhostID table
16329: {
16330:     sub load_serverhomeIDs {
16331:         if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
16332:             if (open(my $config,"<","$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
16333:                 while (my $configline=<$config>) {
16334:                     chomp($configline);
16335:                     my ($name,$id)=split(/:/,$configline);
16336:                     $serverhomeIDs{$name}=$id;
16337:                 }
16338:                 close($config);
16339:             }
16340:         }
16341:     }
16342: }
16343: 
16344: 
16345: BEGIN {
16346: 
16347: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
16348:     unless ($readit) {
16349: {
16350:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
16351:     %perlvar = (%perlvar,%{$configvars});
16352: }
16353: 
16354: 
16355: # ------------------------------------------------------ Read spare server file
16356: {
16357:     open(my $config,"<","$perlvar{'lonTabDir'}/spare.tab");
16358: 
16359:     while (my $configline=<$config>) {
16360:        chomp($configline);
16361:        if ($configline) {
16362: 	   my ($host,$type) = split(':',$configline,2);
16363: 	   if (!defined($type) || $type eq '') { $type = 'default' };
16364: 	   push(@{ $spareid{$type} }, $host);
16365:        }
16366:     }
16367:     close($config);
16368: }
16369: # ------------------------------------------------------------ Read permissions
16370: {
16371:     open(my $config,"<","$perlvar{'lonTabDir'}/roles.tab");
16372: 
16373:     while (my $configline=<$config>) {
16374: 	chomp($configline);
16375: 	if ($configline) {
16376: 	    my ($role,$perm)=split(/ /,$configline);
16377: 	    if ($perm ne '') { $pr{$role}=$perm; }
16378: 	}
16379:     }
16380:     close($config);
16381: }
16382: 
16383: # -------------------------------------------- Read plain texts for permissions
16384: {
16385:     open(my $config,"<","$perlvar{'lonTabDir'}/rolesplain.tab");
16386: 
16387:     while (my $configline=<$config>) {
16388: 	chomp($configline);
16389: 	if ($configline) {
16390: 	    my ($short,@plain)=split(/:/,$configline);
16391:             %{$prp{$short}} = ();
16392: 	    if (@plain > 0) {
16393:                 $prp{$short}{'std'} = $plain[0];
16394:                 for (my $i=1; $i<@plain; $i++) {
16395:                     $prp{$short}{'alt'.$i} = $plain[$i];  
16396:                 }
16397:             }
16398: 	}
16399:     }
16400:     close($config);
16401: }
16402: 
16403: # ---------------------------------------------------------- Read package table
16404: {
16405:     open(my $config,"<","$perlvar{'lonTabDir'}/packages.tab");
16406: 
16407:     while (my $configline=<$config>) {
16408: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
16409: 	chomp($configline);
16410: 	my ($short,$plain)=split(/:/,$configline);
16411: 	my ($pack,$name)=split(/\&/,$short);
16412: 	if ($plain ne '') {
16413: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
16414: 	    $packagetab{$short}=$plain; 
16415: 	}
16416:     }
16417:     close($config);
16418: }
16419: 
16420: # ---------------------------------------------------------- Read loncaparev table
16421: 
16422: &load_loncaparevs();
16423: 
16424: # ---------------------------------------------------------- Read serverhostID table
16425: 
16426: &load_serverhomeIDs();
16427: 
16428: # ---------------------------------------------------------- Read releaseslist XML
16429: {
16430:     my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
16431:     if (-e $file) {
16432:         my $parser = HTML::LCParser->new($file);
16433:         while (my $token = $parser->get_token()) {
16434:             if ($token->[0] eq 'S') {
16435:                 my $item = $token->[1];
16436:                 my $name = $token->[2]{'name'};
16437:                 my $value = $token->[2]{'value'};
16438:                 my $valuematch = $token->[2]{'valuematch'};
16439:                 my $namematch = $token->[2]{'namematch'};
16440:                 if ($item eq 'parameter') {
16441:                     if (($namematch ne '') || (($name ne '') && ($value ne '' || $valuematch ne ''))) {
16442:                         my $release = $parser->get_text();
16443:                         $release =~ s/(^\s*|\s*$ )//gx;
16444:                         $needsrelease{$item.':'.$name.':'.$value.':'.$valuematch.':'.$namematch} = $release;
16445:                     }
16446:                 } elsif ($item ne '' && $name ne '') {
16447:                     my $release = $parser->get_text();
16448:                     $release =~ s/(^\s*|\s*$ )//gx;
16449:                     $needsrelease{$item.':'.$name.':'.$value} = $release;
16450:                 }
16451:             }
16452:         }
16453:     }
16454: }
16455: 
16456: # ---------------------------------------------------------- Read managers table
16457: {
16458:     if (-e "$perlvar{'lonTabDir'}/managers.tab") {
16459:         if (open(my $config,"<","$perlvar{'lonTabDir'}/managers.tab")) {
16460:             while (my $configline=<$config>) {
16461:                 chomp($configline);
16462:                 next if ($configline =~ /^\#/);
16463:                 if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
16464:                     $managerstab{$configline} = 1;
16465:                 }
16466:             }
16467:             close($config);
16468:         }
16469:     }
16470: }
16471: 
16472: # ------------- set up temporary directory
16473: {
16474:     $tmpdir = LONCAPA::tempdir();
16475: 
16476: }
16477: 
16478: # ------------- set default texengine (domain default overrides this)
16479: {
16480:     $deftex = LONCAPA::texengine();
16481: }
16482: 
16483: # ------------- set default minimum length for passwords for internal auth users
16484: {
16485:     $passwdmin = LONCAPA::passwd_min();
16486: }
16487: 
16488: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
16489: 				'compress_threshold'=> 20_000,
16490:  			        });
16491: 
16492: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
16493: $dumpcount=0;
16494: $locknum=0;
16495: 
16496: &logtouch();
16497: &logthis('<font color="yellow">INFO: Read configuration</font>');
16498: $readit=1;
16499:     {
16500: 	use integer;
16501: 	my $test=(2**32)+1;
16502: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
16503: 	&logthis(" Detected 64bit platform ($_64bit)");
16504:     }
16505: }
16506: }
16507: 
16508: 1;
16509: __END__
16510: 
16511: =pod
16512: 
16513: =head1 NAME
16514: 
16515: Apache::lonnet - Subroutines to ask questions about things in the network.
16516: 
16517: =head1 SYNOPSIS
16518: 
16519: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
16520: 
16521:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
16522: 
16523: Common parameters:
16524: 
16525: =over 4
16526: 
16527: =item *
16528: 
16529: $uname : an internal username (if $cname expecting a course Id specifically)
16530: 
16531: =item *
16532: 
16533: $udom : a domain (if $cdom expecting a course's domain specifically)
16534: 
16535: =item *
16536: 
16537: $symb : a resource instance identifier
16538: 
16539: =item *
16540: 
16541: $namespace : the name of a .db file that contains the data needed or
16542: being set.
16543: 
16544: =back
16545: 
16546: =head1 OVERVIEW
16547: 
16548: lonnet provides subroutines which interact with the
16549: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
16550: about classes, users, and resources.
16551: 
16552: For many of these objects you can also use this to store data about
16553: them or modify them in various ways.
16554: 
16555: =head2 Symbs
16556: 
16557: To identify a specific instance of a resource, LON-CAPA uses symbols
16558: or "symbs"X<symb>. These identifiers are built from the URL of the
16559: map, the resource number of the resource in the map, and the URL of
16560: the resource itself. The latter is somewhat redundant, but might help
16561: if maps change.
16562: 
16563: An example is
16564: 
16565:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
16566: 
16567: The respective map entry is
16568: 
16569:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
16570:   title="Problem 2">
16571:  </resource>
16572: 
16573: Symbs are used by the random number generator, as well as to store and
16574: restore data specific to a certain instance of for example a problem.
16575: 
16576: =head2 Storing And Retrieving Data
16577: 
16578: X<store()>X<cstore()>X<restore()>Three of the most important functions
16579: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
16580: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
16581: is is the non-critical message twin of cstore. These functions are for
16582: handlers to store a perl hash to a user's permanent data space in an
16583: easy manner, and to retrieve it again on another call. It is expected
16584: that a handler would use this once at the beginning to retrieve data,
16585: and then again once at the end to send only the new data back.
16586: 
16587: The data is stored in the user's data directory on the user's
16588: homeserver under the ID of the course.
16589: 
16590: The hash that is returned by restore will have all of the previous
16591: value for all of the elements of the hash.
16592: 
16593: Example:
16594: 
16595:  #creating a hash
16596:  my %hash;
16597:  $hash{'foo'}='bar';
16598: 
16599:  #storing it
16600:  &Apache::lonnet::cstore(\%hash);
16601: 
16602:  #changing a value
16603:  $hash{'foo'}='notbar';
16604: 
16605:  #adding a new value
16606:  $hash{'bar'}='foo';
16607:  &Apache::lonnet::cstore(\%hash);
16608: 
16609:  #retrieving the hash
16610:  my %history=&Apache::lonnet::restore();
16611: 
16612:  #print the hash
16613:  foreach my $key (sort(keys(%history))) {
16614:    print("\%history{$key} = $history{$key}");
16615:  }
16616: 
16617: Will print out:
16618: 
16619:  %history{1:foo} = bar
16620:  %history{1:keys} = foo:timestamp
16621:  %history{1:timestamp} = 990455579
16622:  %history{2:bar} = foo
16623:  %history{2:foo} = notbar
16624:  %history{2:keys} = foo:bar:timestamp
16625:  %history{2:timestamp} = 990455580
16626:  %history{bar} = foo
16627:  %history{foo} = notbar
16628:  %history{timestamp} = 990455580
16629:  %history{version} = 2
16630: 
16631: Note that the special hash entries C<keys>, C<version> and
16632: C<timestamp> were added to the hash. C<version> will be equal to the
16633: total number of versions of the data that have been stored. The
16634: C<timestamp> attribute will be the UNIX time the hash was
16635: stored. C<keys> is available in every historical section to list which
16636: keys were added or changed at a specific historical revision of a
16637: hash.
16638: 
16639: B<Warning>: do not store the hash that restore returns directly. This
16640: will cause a mess since it will restore the historical keys as if the
16641: were new keys. I.E. 1:foo will become 1:1:foo etc.
16642: 
16643: Calling convention:
16644: 
16645:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname);
16646:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$laststore);
16647: 
16648: For more detailed information, see lonnet specific documentation.
16649: 
16650: =head1 RETURN MESSAGES
16651: 
16652: =over 4
16653: 
16654: =item * B<con_lost>: unable to contact remote host
16655: 
16656: =item * B<con_delayed>: unable to contact remote host, message will be delivered
16657: when the connection is brought back up
16658: 
16659: =item * B<con_failed>: unable to contact remote host and unable to save message
16660: for later delivery
16661: 
16662: =item * B<error:>: an error a occurred, a description of the error follows the :
16663: 
16664: =item * B<no_such_host>: unable to fund a host associated with the user/domain
16665: that was requested
16666: 
16667: =back
16668: 
16669: =head1 PUBLIC SUBROUTINES
16670: 
16671: =head2 Session Environment Functions
16672: 
16673: =over 4
16674: 
16675: =item * 
16676: X<appenv()>
16677: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
16678: the user envirnoment file, and will be restored for each access this
16679: user makes during this session, also modifies the %env for the current
16680: process. Optional rolesarrayref - if defined contains a reference to an array
16681: of roles which are exempt from the restriction on modifying user.role entries 
16682: in the user's environment.db and in %env.    
16683: 
16684: =item *
16685: X<delenv()>
16686: B<delenv($delthis,$regexp)>: removes all items from the session
16687: environment file that begin with $delthis. If the 
16688: optional second arg - $regexp - is true, $delthis is treated as a 
16689: regular expression, otherwise \Q$delthis\E is used. 
16690: The values are also deleted from the current processes %env.
16691: 
16692: =item * get_env_multiple($name) 
16693: 
16694: gets $name from the %env hash, it seemlessly handles the cases where multiple
16695: values may be defined and end up as an array ref.
16696: 
16697: returns an array of values
16698: 
16699: =back
16700: 
16701: =head2 User Information
16702: 
16703: =over 4
16704: 
16705: =item *
16706: X<queryauthenticate()>
16707: B<queryauthenticate($uname,$udom)>: try to determine user's current 
16708: authentication scheme
16709: 
16710: =item *
16711: X<authenticate()>
16712: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
16713: authenticate user from domain's lib servers (first use the current
16714: one). C<$upass> should be the users password.
16715: $checkdefauth is optional (value is 1 if a check should be made to
16716:    authenticate user using default authentication method, and allow
16717:    account creation if username does not have account in the domain).
16718: $clientcancheckhost is optional (value is 1 if checking whether the
16719:    server can host will occur on the client side in lonauth.pm).   
16720: 
16721: =item *
16722: X<homeserver()>
16723: B<homeserver($uname,$udom)>: find the server which has
16724: the user's directory and files (there must be only one), this caches
16725: the answer, and also caches if there is a borken connection.
16726: 
16727: =item *
16728: X<idget()>
16729: B<idget($udom,$idsref,$namespace)>: find the usernames behind either 
16730: a list of student/employee IDs or clicker IDs
16731: (student/employee IDs are a unique resource in a domain, there must be 
16732: only 1 ID per username, and only 1 username per ID in a specific domain).
16733: clickerIDs are not necessarily unique, as students might share clickers.
16734: (returns hash: id=>name,id=>name)
16735: 
16736: =item *
16737: X<idrget()>
16738: B<idrget($udom,@unames)>: find the IDs behind a list of
16739: usernames (returns hash: name=>id,name=>id)
16740: 
16741: =item *
16742: X<idput()>
16743: B<idput($udom,$idsref,$uhome,$namespace)>: store away a list of 
16744: names and associated student/employee IDs or clicker IDs.
16745: 
16746: =item *
16747: X<iddel()>
16748: B<iddel($udom,$idshashref,$uhome,$namespace)>: delete unwanted 
16749: student/employee ID or clicker ID username look-ups from domain.
16750: The homeserver ($uhome) and namespace ($namespace) are optional.
16751: If no $uhome is provided, it will be determined usig &homeserver()
16752: for each user.  If no $namespace is provided, the default is ids.
16753: 
16754: =item *
16755: X<updateclickers()>
16756: B<updateclickers($udom,$action,$idshashref,$uhome,$critical)>: update 
16757: clicker ID-to-username look-ups in clickers.db on library server.
16758: Permitted actions are add or del (i.e., add or delete). The 
16759: clickers.db contains clickerID as keys (escaped), and each corresponding
16760: value is an escaped comma-separated list of usernames (for whom the
16761: library server is the homeserver), who registered that particular ID.
16762: If $critical is true, the update will be sent via &critical, otherwise
16763: &reply() will be used.
16764: 
16765: =item *
16766: X<rolesinit()>
16767: B<rolesinit($udom,$username)>: get user privileges.
16768: returns user role, first access and timer interval hashes
16769: 
16770: =item *
16771: X<privileged()>
16772: B<privileged($username,$domain)>: returns a true if user has a
16773: privileged and active role (i.e. su or dc), false otherwise.
16774: 
16775: =item *
16776: X<getsection()>
16777: B<getsection($udom,$uname,$cname)>: finds the section of student in the
16778: course $cname, return section name/number or '' for "not in course"
16779: and '-1' for "no section"
16780: 
16781: =item *
16782: X<userenvironment()>
16783: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
16784: passed in @what from the requested user's environment, returns a hash
16785: 
16786: =item * 
16787: X<userlog_query()>
16788: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
16789: activity.log file. %filters defines filters applied when parsing the
16790: log file. These can be start or end timestamps, or the type of action
16791: - log to look for Login or Logout events, check for Checkin or
16792: Checkout, role for role selection. The response is in the form
16793: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
16794: escaped strings of the action recorded in the activity.log file.
16795: 
16796: =back
16797: 
16798: =head2 User Roles
16799: 
16800: =over 4
16801: 
16802: =item *
16803: 
16804: allowed($priv,$uri,$symb,$role,$clientip,$noblockcheck) : check for a user privilege; 
16805: returns codes for allowed actions.
16806: 
16807: The first argument is required, all others are optional.
16808: 
16809: $priv is the privilege being checked.
16810: $uri contains additional information about what is being checked for access (e.g.,
16811: URL, course ID etc.). 
16812: $symb is the unique resource instance identifier in a course; if needed,
16813: but not provided, it will be retrieved via a call to &symbread(). 
16814: $role is the role for which a priv is being checked (only used if priv is evb). 
16815: $clientip is the user's IP address (only used when checking for access to portfolio 
16816: files).
16817: $noblockcheck, if true, skips calls to &has_comm_blocking() for the bre priv. This 
16818: prevents recursive calls to &allowed.
16819: 
16820:  F: full access
16821:  U,I,K: authentication modes (cxx only)
16822:  '': forbidden
16823:  1: user needs to choose course
16824:  2: browse allowed
16825:  A: passphrase authentication needed
16826:  B: access temporarily blocked because of a blocking event in a course.
16827:  D: access blocked because access is required via session initiated via deep-link 
16828: 
16829: =item *
16830: 
16831: constructaccess($url,$setpriv) : check for access to construction space URL
16832: 
16833: See if the owner domain and name in the URL match those in the
16834: expected environment.  If so, return three element list
16835: ($ownername,$ownerdomain,$ownerhome).
16836: 
16837: Otherwise return the null string.
16838: 
16839: If second argument 'setpriv' is true, it assigns the privileges,
16840: and returns the same three element list, unless the owner has
16841: blocked "ad hoc" Domain Coordinator access to the Author Space,
16842: in which case the null string is returned.
16843: 
16844: =item *
16845: 
16846: definerole($rolename,$sysrole,$domrole,$courole,$uname,$udom) : define role;
16847: define a custom role rolename set privileges in format of lonTabs/roles.tab
16848: for system, domain, and course level. $uname and $udom are optional (current
16849: user's username and domain will be used when either of $uname or $udom are absent.
16850: 
16851: =item *
16852: 
16853: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
16854: (rolesplain.tab); plain text explanation of a user role term.
16855: $type is Course (default) or Community.
16856: If $forcedefault evaluates to true, text returned will be default 
16857: text for $type. Otherwise, if this is a course, the text returned 
16858: will be a custom name for the role (if defined in the course's 
16859: environment).  If no custom name is defined the default is returned.
16860:    
16861: =item *
16862: 
16863: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv) :
16864: All arguments are optional. Returns a hash of a roles, either for
16865: co-author/assistant author roles for a user's Construction Space
16866: (default), or if $context is 'userroles', roles for the user himself,
16867: In the hash, keys are set to colon-separated $uname,$udom,$role, and
16868: (optionally) if $withsec is true, a fourth colon-separated item - $section.
16869: For each key, value is set to colon-separated start and end times for
16870: the role.  If no username and domain are specified, will default to
16871: current user/domain. Types, roles, and roledoms are references to arrays
16872: of role statuses (active, future or previous), roles 
16873: (e.g., cc,in, st etc.) and domains of the roles which can be used
16874: to restrict the list of roles reported. If no array ref is 
16875: provided for types, will default to return only active roles.
16876: 
16877: =item *
16878: 
16879: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
16880: user: $uname:$udom has a role in the course: $cdom_$cnum. 
16881: 
16882: Additional optional arguments are: $type (if role checking is to be restricted 
16883: to certain user status types -- previous (expired roles), active (currently
16884: available roles) or future (roles available in the future), and
16885: $hideprivileged -- if true will not report course roles for users who
16886: have active Domain Coordinator role in course's domain or in additional
16887: domains (specified in 'Domains to check for privileged users' in course
16888: environment -- set via:  Course Settings -> Classlists and staff listing).
16889: 
16890: =item *
16891: 
16892: privileged($username,$domain,$possdomains,$possroles) : returns 1 if user
16893: $username:$domain is a privileged user (e.g., Domain Coordinator or Super User)
16894: $possdomains and $possroles are optional array refs -- to domains to check and
16895: roles to check.  If $possdomains is not specified, a dump will be done of the
16896: users' roles.db to check for a dc or su role in any domain. This can be
16897: time consuming if &privileged is called repeatedly (e.g., when displaying a
16898: classlist), so in such cases, supplying a $possdomains array is preferred, as
16899: this then allows &privileged_by_domain() to be used, which caches the identity
16900: of privileged users, eliminating the need for repeated calls to &dump().
16901: 
16902: =item *
16903: 
16904: privileged_by_domain($possdomains,$roles) : returns a hash of a hash of a hash,
16905: where the outer hash keys are domains specified in the $possdomains array ref,
16906: next inner hash keys are privileged roles specified in the $roles array ref,
16907: and the innermost hash contains key = value pairs for username:domain = end:start
16908: for active or future "privileged" users with that role in that domain. To avoid
16909: repeated dumps of domain roles -- via &get_domain_roles() -- contents of the
16910: innerhash are cached using priv_$role and $dom as the identifiers.
16911: 
16912: =back
16913: 
16914: =head2 User Modification
16915: 
16916: =over 4
16917: 
16918: =item *
16919: 
16920: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
16921: user for the level given by URL.  Optional start and end dates (leave empty
16922: string or zero for "no date")
16923: 
16924: =item *
16925: 
16926: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
16927: change a users, password, possible return values are: ok,
16928: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
16929: refused
16930: 
16931: =item *
16932: 
16933: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
16934: 
16935: =item *
16936: 
16937: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
16938:            $forceid,$desiredhome,$email,$inststatus,$candelete) :
16939: 
16940: will update user information (firstname,middlename,lastname,generation,
16941: permanentemail), and if forceid is true, student/employee ID also.
16942: A user's institutional affiliation(s) can also be updated.
16943: User information fields will not be overwritten with empty entries 
16944: unless the field is included in the $candelete array reference.
16945: This array is included when a single user is modified via "Manage Users",
16946: or when Autoupdate.pl is run by cron in a domain.
16947: 
16948: =item *
16949: 
16950: modifystudent
16951: 
16952: modify a student's enrollment and identification information.
16953: The course id is resolved based on the current user's environment.  
16954: This means the invoking user must be a course coordinator or otherwise
16955: associated with a course.
16956: 
16957: This call is essentially a wrapper for lonnet::modifyuser and
16958: lonnet::modify_student_enrollment
16959: 
16960: Inputs: 
16961: 
16962: =over 4
16963: 
16964: =item B<$udom> Student's loncapa domain
16965: 
16966: =item B<$uname> Student's loncapa login name
16967: 
16968: =item B<$uid> Student/Employee ID
16969: 
16970: =item B<$umode> Student's authentication mode
16971: 
16972: =item B<$upass> Student's password
16973: 
16974: =item B<$first> Student's first name
16975: 
16976: =item B<$middle> Student's middle name
16977: 
16978: =item B<$last> Student's last name
16979: 
16980: =item B<$gene> Student's generation
16981: 
16982: =item B<$usec> Student's section in course
16983: 
16984: =item B<$end> Unix time of the roles expiration
16985: 
16986: =item B<$start> Unix time of the roles start date
16987: 
16988: =item B<$forceid> If defined, allow $uid to be changed
16989: 
16990: =item B<$desiredhome> server to use as home server for student
16991: 
16992: =item B<$email> Student's permanent e-mail address
16993: 
16994: =item B<$type> Type of enrollment (auto or manual)
16995: 
16996: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
16997: 
16998: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
16999: 
17000: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
17001: 
17002: =item B<$context> role change context (shown in User Management Logs display in a course)
17003: 
17004: =item B<$inststatus> institutional status of user - : separated string of escaped status types
17005: 
17006: =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.
17007: 
17008: =back
17009: 
17010: =item *
17011: 
17012: modify_student_enrollment
17013: 
17014: Change a student's enrollment status in a class.  The environment variable
17015: 'role.request.course' must be defined for this function to proceed.
17016: 
17017: Inputs:
17018: 
17019: =over 4
17020: 
17021: =item $udom, student's domain
17022: 
17023: =item $uname, student's name
17024: 
17025: =item $uid, student's user id
17026: 
17027: =item $first, student's first name
17028: 
17029: =item $middle
17030: 
17031: =item $last
17032: 
17033: =item $gene
17034: 
17035: =item $usec
17036: 
17037: =item $end
17038: 
17039: =item $start
17040: 
17041: =item $type
17042: 
17043: =item $locktype
17044: 
17045: =item $cid
17046: 
17047: =item $selfenroll
17048: 
17049: =item $context
17050: 
17051: =item $credits, number of credits student will earn from this class
17052: 
17053: =item $instsec, institutional course section code for student
17054: 
17055: =back
17056: 
17057: 
17058: =item *
17059: 
17060: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
17061: custom role; give a custom role to a user for the level given by URL.  Specify
17062: name and domain of role author, and role name
17063: 
17064: =item *
17065: 
17066: revokerole($udom,$uname,$url,$role) : revoke a role for url
17067: 
17068: =item *
17069: 
17070: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
17071: 
17072: =back
17073: 
17074: =head2 Course Infomation
17075: 
17076: =over 4
17077: 
17078: =item *
17079: 
17080: coursedescription($courseid,$options) : returns a hash of information about the
17081: specified course id, including all environment settings for the
17082: course, the description of the course will be in the hash under the
17083: key 'description'
17084: 
17085: $options is an optional parameter that if supplied is a hash reference that controls
17086: what how this function works.  It has the following key/values:
17087: 
17088: =over 4
17089: 
17090: =item freshen_cache
17091: 
17092: If defined, and the environment cache for the course is valid, it is 
17093: returned in the returned hash.
17094: 
17095: =item one_time
17096: 
17097: If defined, the last cache time is set to _now_
17098: 
17099: =item user
17100: 
17101: If defined, the supplied username is used instead of the current user.
17102: 
17103: 
17104: =back
17105: 
17106: =item *
17107: 
17108: resdata($name,$domain,$type,@which) : request for current parameter
17109: setting for a specific $type, where $type is either 'course' or 'user',
17110: @what should be a list of parameters to ask about. This routine caches
17111: answers for 10 minutes.
17112: 
17113: =item *
17114: 
17115: get_courseresdata($courseid, $domain) : dump the entire course resource
17116: data base, returning a hash that is keyed by the resource name and has
17117: values that are the resource value.  I believe that the timestamps and
17118: versions are also returned.
17119: 
17120: =back
17121: 
17122: =head2 Course Modification
17123: 
17124: =over 4
17125: 
17126: =item *
17127: 
17128: writecoursepref($courseid,%prefs) : write preferences (environment
17129: database) for a course
17130: 
17131: =item *
17132: 
17133: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
17134: 
17135: =item *
17136: 
17137: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
17138: 
17139: =item *
17140: 
17141: is_course($courseid), is_course($cdom, $cnum)
17142: 
17143: Accepts either a combined $courseid (in the form of domain_courseid) or the
17144: two component version $cdom, $cnum. It checks if the specified course exists.
17145: 
17146: Returns:
17147:     undef if the course doesn't exist, otherwise
17148:     in scalar context the combined courseid.
17149:     in list context the two components of the course identifier, domain and 
17150:     courseid.    
17151: 
17152: =back
17153: 
17154: =head2 Bubblesheet Configuration
17155: 
17156: =over 4
17157: 
17158: =item *
17159: 
17160: get_scantron_config($which)
17161: 
17162: $which - the name of the configuration to parse from the file.
17163: 
17164: Parses and returns the bubblesheet configuration line selected as a
17165: hash of configuration file fields.
17166: 
17167: 
17168: Returns:
17169:     If the named configuration is not in the file, an empty
17170:     hash is returned.
17171: 
17172:     a hash with the fields
17173:       name         - internal name for the this configuration setup
17174:       description  - text to display to operator that describes this config
17175:       CODElocation - if 0 or the string 'none'
17176:                           - no CODE exists for this config
17177:                      if -1 || the string 'letter'
17178:                           - a CODE exists for this config and is
17179:                             a string of letters
17180:                      Unsupported value (but planned for future support)
17181:                           if a positive integer
17182:                                - The CODE exists as the first n items from
17183:                                  the question section of the form
17184:                           if the string 'number'
17185:                                - The CODE exists for this config and is
17186:                                  a string of numbers
17187:       CODEstart   - (only matter if a CODE exists) column in the line where
17188:                      the CODE starts
17189:       CODElength  - length of the CODE
17190:       IDstart     - column where the student/employee ID starts
17191:       IDlength    - length of the student/employee ID info
17192:       Qstart      - column where the information from the bubbled
17193:                     'questions' start
17194:       Qlength     - number of columns comprising a single bubble line from
17195:                     the sheet. (usually either 1 or 10)
17196:       Qon         - either a single character representing the character used
17197:                     to signal a bubble was chosen in the positional setup, or
17198:                     the string 'letter' if the letter of the chosen bubble is
17199:                     in the final, or 'number' if a number representing the
17200:                     chosen bubble is in the file (1->A 0->J)
17201:       Qoff        - the character used to represent that a bubble was
17202:                     left blank
17203:       PaperID     - if the scanning process generates a unique number for each
17204:                     sheet scanned the column that this ID number starts in
17205:       PaperIDlength - number of columns that comprise the unique ID number
17206:                       for the sheet of paper
17207:       FirstName   - column that the first name starts in
17208:       FirstNameLength - number of columns that the first name spans
17209:       LastName    - column that the last name starts in
17210:       LastNameLength - number of columns that the last name spans
17211:       BubblesPerRow - number of bubbles available in each row used to
17212:                       bubble an answer. (If not specified, 10 assumed).
17213: 
17214: 
17215: =item *
17216: 
17217: get_scantronformat_file($cdom)
17218: 
17219: $cdom - the course's domain (optional); if not supplied, uses
17220: domain for current $env{'request.course.id'}.
17221: 
17222: Returns an array containing lines from the scantron format file for
17223: the domain of the course.
17224: 
17225: If a url for a custom.tab file is listed in domain's configuration.db,
17226: lines are from this file.
17227: 
17228: Otherwise, if a default.tab has been published in RES space by the
17229: domainconfig user, lines are from this file.
17230: 
17231: Otherwise, fall back to getting lines from the legacy file on the
17232: local server:  /home/httpd/lonTabs/default_scantronformat.tab
17233: 
17234: =back
17235: 
17236: =head2 Resource Subroutines
17237: 
17238: =over 4
17239: 
17240: =item *
17241: 
17242: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
17243: 
17244: =item *
17245: 
17246: repcopy($filename) : subscribes to the requested file, and attempts to
17247: replicate from the owning library server, Might return
17248: 'unavailable', 'not_found', 'forbidden', 'ok', or
17249: 'bad_request', also attempts to grab the metadata for the
17250: resource. Expects the local filesystem pathname
17251: (/home/httpd/html/res/....)
17252: 
17253: =back
17254: 
17255: =head2 Resource Information
17256: 
17257: =over 4
17258: 
17259: =item *
17260: 
17261: EXT($varname,$symb,$udom,$uname,$usection,$recurse,$cid) : evaluates 
17262: and returns the value of a variety of different possible values,
17263: $varname should be a request string, and the other parameters can be
17264: used to specify who and what one is asking about. Ordinarily, $cid 
17265: does not need to be specified, as it is retrived from 
17266: $env{'request.course.id'}, but &Apache::lonnet::EXT() is called
17267: within lonuserstate::loadmap() when initializing a course, before
17268: $env{'request.course.id'} has been set, so it needs to be provided
17269: in that one case.
17270: 
17271: Possible values for $varname are environment.lastname (or other item
17272: from the envirnment hash), user.name (or someother aspect about the
17273: user), resource.0.maxtries (or some other part and parameter of a
17274: resource)
17275: 
17276: =item *
17277: 
17278: directcondval($number) : get current value of a condition; reads from a state
17279: string
17280: 
17281: =item *
17282: 
17283: condval($condidx) : value of condition index based on state
17284: 
17285: =item *
17286: 
17287: metadata($uri,$what,$toolsymb,$liburi,$prefix,$depthcount) : request a
17288: resource's metadata, $what should be either a specific key, or either
17289: 'keys' (to get a list of possible keys) or 'packages' to get a list of
17290: packages that this resource currently uses, the last 3 arguments are 
17291: only used internally for recursive metadata.
17292: 
17293: the toolsymb is only used where the uri is for an external tool (for which
17294: the uri as well as the symb are guaranteed to be unique).
17295: 
17296: this function automatically caches all requests except any made recursively
17297: to retrieve a list of metadata keys for an imported library file ($liburi is 
17298: defined).
17299: 
17300: =item *
17301: 
17302: metadata_query($query,$custom,$customshow) : make a metadata query against the
17303: network of library servers; returns file handle of where SQL and regex results
17304: will be stored for query
17305: 
17306: =item *
17307: 
17308: symbread($filename,$donotrecurse,$ignorecachednull,$checkforblock,$possibles) : 
17309: return symbolic list entry (all arguments optional). 
17310: 
17311: Args: filename is the filename (including path) for the file for which a symb 
17312: is required; donotrecurse, if true will prevent calls to allowed() being made 
17313: to check access status if more than one resource was found in the bighash 
17314: (see rev. 1.249) to avoid an infinite loop if an ambiguous resource is part of 
17315: a randompick); ignorecachednull, if true will prevent a symb of '' being 
17316: returned if $env{$cache_str} is defined as ''; checkforblock if true will
17317: cause possible symbs to be checked to determine if they are subject to content
17318: blocking, if so they will not be included as possible symbs; possibles is a
17319: ref to a hash, which, as a side effect, will be populated with all possible 
17320: symbs (content blocking not tested).
17321:  
17322: returns the data handle
17323: 
17324: =item *
17325: 
17326: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
17327: and is a possible symb for the URL in $thisfn, and if is an encrypted
17328: resource that the user accessed using /enc/ returns a 1 on success, 0
17329: on failure, user must be in a course, as it assumes the existence of
17330: the course initial hash, and uses $env('request.course.id'}.  The third
17331: arg is an optional reference to a scalar.  If this arg is passed in the 
17332: call to symbverify, it will be set to 1 if the symb has been set to be 
17333: encrypted; otherwise it will be null.  
17334: 
17335: =item *
17336: 
17337: symbclean($symb) : removes versions numbers from a symb, returns the
17338: cleaned symb
17339: 
17340: =item *
17341: 
17342: is_on_map($uri) : checks if the $uri is somewhere on the current
17343: course map, user must be in a course for it to work.
17344: 
17345: =item *
17346: 
17347: numval($salt) : return random seed value (addend for rndseed)
17348: 
17349: =item *
17350: 
17351: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
17352: a random seed, all arguments are optional, if they aren't sent it uses the
17353: environment to derive them. Note: if symb isn't sent and it can't get one
17354: from &symbread it will use the current time as its return value
17355: 
17356: =item *
17357: 
17358: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
17359: unfakeable, receipt
17360: 
17361: =item *
17362: 
17363: receipt() : API to ireceipt working off of env values; given out to users
17364: 
17365: =item *
17366: 
17367: countacc($url) : count the number of accesses to a given URL
17368: 
17369: =item *
17370: 
17371: 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
17372: 
17373: =item *
17374: 
17375: 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)
17376: 
17377: =item *
17378: 
17379: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
17380: 
17381: =item *
17382: 
17383: devalidate($symb) : devalidate temporary spreadsheet calculations,
17384: forcing spreadsheet to reevaluate the resource scores next time.
17385: 
17386: =item * 
17387: 
17388: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
17389: when viewing in course context.
17390: 
17391:  input: six args -- filename (decluttered), course number, course domain,
17392:                     url, symb (if registered) and group (if this is a 
17393:                     group item -- e.g., bulletin board, group page etc.).
17394: 
17395:  output: array of five scalars --
17396:          $cfile -- url for file editing if editable on current server
17397:          $home -- homeserver of resource (i.e., for author if published,
17398:                                           or course if uploaded.).
17399:          $switchserver --  1 if server switch will be needed.
17400:          $forceedit -- 1 if icon/link should be to go to edit mode 
17401:          $forceview -- 1 if icon/link should be to go to view mode
17402: 
17403: =item *
17404: 
17405: is_course_upload($file,$cnum,$cdom)
17406: 
17407: Used in course context to determine if current file was uploaded to 
17408: the course (i.e., would be found in /userfiles/docs on the course's 
17409: homeserver.
17410: 
17411:   input: 3 args -- filename (decluttered), course number and course domain.
17412:   output: boolean -- 1 if file was uploaded.
17413: 
17414: =back
17415: 
17416: =head2 Storing/Retreiving Data
17417: 
17418: =over 4
17419: 
17420: =item *
17421: 
17422: store($storehash,$symb,$namespace,$udom,$uname,$laststore) : stores hash
17423: permanently for this url; hashref needs to be given and should be a \%hashname;
17424: the remaining args aren't required and if they aren't passed or are '' they will
17425: be derived from the env (with the exception of $laststore, which is an 
17426: optional arg used when a user's submission is stored in grading).
17427: $laststore is $version=$timestamp, where $version is the most recent version
17428: number retrieved for the corresponding $symb in the $namespace db file, and
17429: $timestamp is the timestamp for that transaction (UNIX time).
17430: $laststore is currently only passed when cstore() is called by 
17431: structuretags::finalize_storage().
17432: 
17433: =item *
17434: 
17435: cstore($storehash,$symb,$namespace,$udom,$uname,$laststore) : same as store
17436: but uses critical subroutine
17437: 
17438: =item *
17439: 
17440: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
17441: all args are optional
17442: 
17443: =item *
17444: 
17445: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
17446: dumps the complete (or key matching regexp) namespace into a hash
17447: ($udom, $uname, $regexp, $range are optional) for a namespace that is
17448: normally &store()ed into
17449: 
17450: $range should be either an integer '100' (give me the first 100
17451:                                            matching records)
17452:               or be  two integers sperated by a - with no spaces
17453:                  '30-50' (give me the 30th through the 50th matching
17454:                           records)
17455: 
17456: 
17457: =item *
17458: 
17459: putstore($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog) :
17460: replaces a &store() version of data with a replacement set of data
17461: for a particular resource in a namespace passed in the $storehash hash 
17462: reference. If $tolog is true, the transaction is logged in the courselog
17463: with an action=PUTSTORE.
17464: 
17465: =item *
17466: 
17467: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
17468: works very similar to store/cstore, but all data is stored in a
17469: temporary location and can be reset using tmpreset, $storehash should
17470: be a hash reference, returns nothing on success
17471: 
17472: =item *
17473: 
17474: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
17475: similar to restore, but all data is stored in a temporary location and
17476: can be reset using tmpreset. Returns a hash of values on success,
17477: error string otherwise.
17478: 
17479: =item *
17480: 
17481: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
17482: deltes all keys for $symb form the temporary storage hash.
17483: 
17484: =item *
17485: 
17486: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
17487: reference filled in from namesp ($udom and $uname are optional)
17488: 
17489: =item *
17490: 
17491: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
17492: namesp ($udom and $uname are optional)
17493: 
17494: =item *
17495: 
17496: dump($namespace,$udom,$uname,$regexp,$range) : 
17497: dumps the complete (or key matching regexp) namespace into a hash
17498: ($udom, $uname, $regexp, $range are optional)
17499: 
17500: $range should be either an integer '100' (give me the first 100
17501:                                            matching records)
17502:               or be  two integers sperated by a - with no spaces
17503:                  '30-50' (give me the 30th through the 50th matching
17504:                           records)
17505: =item *
17506: 
17507: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
17508: $store can be a scalar, an array reference, or if the amount to be 
17509: incremented is > 1, a hash reference.
17510: 
17511: ($udom and $uname are optional)
17512: 
17513: =item *
17514: 
17515: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
17516: ($udom and $uname are optional)
17517: 
17518: =item *
17519: 
17520: cput($namespace,$storehash,$udom,$uname) : critical put
17521: ($udom and $uname are optional)
17522: 
17523: =item *
17524: 
17525: newput($namespace,$storehash,$udom,$uname) :
17526: 
17527: Attempts to store the items in the $storehash, but only if they don't
17528: currently exist, if this succeeds you can be certain that you have 
17529: successfully created a new key value pair in the $namespace db.
17530: 
17531: 
17532: Args:
17533:  $namespace: name of database to store values to
17534:  $storehash: hashref to store to the db
17535:  $udom: (optional) domain of user containing the db
17536:  $uname: (optional) name of user caontaining the db
17537: 
17538: Returns:
17539:  'ok' -> succeeded in storing all keys of $storehash
17540:  'key_exists: <key>' -> failed to anything out of $storehash, as at
17541:                         least <key> already existed in the db (other
17542:                         requested keys may also already exist)
17543:  'error: <msg>' -> unable to tie the DB or other error occurred
17544:  'con_lost' -> unable to contact request server
17545:  'refused' -> action was not allowed by remote machine
17546: 
17547: 
17548: =item *
17549: 
17550: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
17551: reference filled in from namesp (encrypts the return communication)
17552: ($udom and $uname are optional)
17553: 
17554: =item *
17555: 
17556: log($udom,$name,$home,$message) : write to permanent log for user; use
17557: critical subroutine
17558: 
17559: =item *
17560: 
17561: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
17562: array reference filled in from namespace found in domain level on either
17563: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
17564: 
17565: =item *
17566: 
17567: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
17568: domain level either on specified domain server ($uhome) or primary domain 
17569: server ($udom and $uhome are optional)
17570: 
17571: =item * 
17572: 
17573: get_domain_defaults($target_domain,$ignore_cache) : returns hash with defaults 
17574: for: authentication, language, quotas, timezone, date locale, and portal URL in
17575: the target domain.
17576: 
17577: May also include additional key => value pairs for the following groups:
17578: 
17579: =over
17580: 
17581: =item
17582: disk quotas (MB allocated by default to portfolios and authoring spaces).
17583: 
17584: =over
17585: 
17586: =item defaultquota, authorquota
17587: 
17588: =back
17589: 
17590: =item
17591: tools (availability of aboutme page, blog, webDAV access for authoring spaces,
17592: portfolio for users).
17593: 
17594: =over
17595: 
17596: =item
17597: aboutme, blog, webdav, portfolio
17598: 
17599: =back
17600: 
17601: =item
17602: requestcourses: ability to request courses, and how requests are processed.
17603: 
17604: =over
17605: 
17606: =item
17607: official, unofficial, community, textbook, placement
17608: 
17609: =back
17610: 
17611: =item
17612: inststatus: types of institutional affiliation, and order in which they are displayed.
17613: 
17614: =over
17615: 
17616: =item
17617: inststatustypes, inststatusorder, inststatusguest
17618: 
17619: =back
17620: 
17621: =item
17622: coursedefaults: can PDF forms can be created, default credits for courses, default quotas (MB)
17623: for course's uploaded content.
17624: 
17625: =over
17626: 
17627: =item
17628: canuse_pdfforms, officialcredits, unofficialcredits, textbookcredits, officialquota, unofficialquota, 
17629: communityquota, textbookquota, placementquota
17630: 
17631: =back
17632: 
17633: =item
17634: usersessions: set options for hosting of your users in other domains, and hosting of users from other domains
17635: on your servers.
17636: 
17637: =over
17638: 
17639: =item 
17640: remotesessions, hostedsessions
17641: 
17642: =back
17643: 
17644: =back
17645: 
17646: In cases where a domain coordinator has never used the "Set Domain Configuration"
17647: utility to create a configuration.db file on a domain's primary library server 
17648: only the following domain defaults: auth_def, auth_arg_def, lang_def
17649: -- corresponding values are authentication type (internal, krb4, krb5,
17650: or localauth), initial password or a kerberos realm, language (e.g., en-us) -- 
17651: will be available. Values are retrieved from cache (if current), unless the
17652: optional $ignore_cache arg is true, or from domain's configuration.db (if available),
17653: or lastly from values in lonTabs/dns_domain,tab, or lonTabs/domain.tab.
17654: 
17655: Typical usage:
17656: 
17657: %domdefaults = &get_domain_defaults($target_domain);
17658: 
17659: =back
17660: 
17661: =head2 Network Status Functions
17662: 
17663: =over 4
17664: 
17665: =item *
17666: 
17667: dirlist() : return directory list based on URI (first arg).
17668: 
17669: Inputs: 1 required, 5 optional.
17670: 
17671: =over
17672: 
17673: =item 
17674: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
17675: 
17676: =item
17677: $userdomain - domain of user/course to be listed. Extracted from $uri if absent. 
17678: 
17679: =item
17680: $username -  username of user/course to be listed. Extracted from $uri if absent. 
17681: 
17682: =item
17683: $getpropath - boolean: 1 if prepend path using &propath(). 
17684: 
17685: =item
17686: $getuserdir - boolean: 1 if prepend path for "userfiles".
17687: 
17688: =item 
17689: $alternateRoot - path to prepend in place of path from $uri.
17690: 
17691: =back
17692: 
17693: Returns: Array of up to two items.
17694: 
17695: =over
17696: 
17697: a reference to an array of files/subdirectories
17698: 
17699: =over
17700: 
17701: Each element in the array of files/subdirectories is a & separated list of
17702: item name and the result of running stat on the item.  If dirlist was requested
17703: for a file instead of a directory, the item name will be ''. For a directory 
17704: listing, if the item is a metadata file, the element will end &N&M 
17705: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
17706: default copyright set (1).  
17707: 
17708: =back
17709: 
17710: a scalar containing error condition (if encountered).
17711: 
17712: =over
17713: 
17714: =item 
17715: no_host (no homeserver identified for $username:$domain).
17716: 
17717: =item 
17718: no_such_host (server contacted for listing not identified as valid host).
17719: 
17720: =item 
17721: con_lost (connection to remote server failed).
17722: 
17723: =item 
17724: refused (invalid $username:$domain received on lond side).
17725: 
17726: =item 
17727: no_such_dir (directory at specified path on lond side does not exist). 
17728: 
17729: =item 
17730: empty (directory at specified path on lond side is empty).
17731: 
17732: =over
17733: 
17734: This is currently not encountered because the &ls3, &ls2, 
17735: &ls (_handler) routines on the lond side do not filter out
17736: . and .. from a directory listing. 
17737: 
17738: =back
17739: 
17740: =back
17741: 
17742: =back
17743: 
17744: =item *
17745: 
17746: spareserver() : find server with least workload from spare.tab
17747: 
17748: 
17749: =item *
17750: 
17751: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
17752: if there is no corresponding loncapa host.
17753: 
17754: =back
17755: 
17756: 
17757: =head2 Apache Request
17758: 
17759: =over 4
17760: 
17761: =item *
17762: 
17763: ssi($url,%hash) : server side include, does a complete request cycle on url to
17764: localhost, posts hash
17765: 
17766: =back
17767: 
17768: =head2 Data to String to Data
17769: 
17770: =over 4
17771: 
17772: =item *
17773: 
17774: hash2str(%hash) : convert a hash into a string complete with escaping and '='
17775: and '&' separators, supports elements that are arrayrefs and hashrefs
17776: 
17777: =item *
17778: 
17779: hashref2str($hashref) : convert a hashref into a string complete with
17780: escaping and '=' and '&' separators, supports elements that are
17781: arrayrefs and hashrefs
17782: 
17783: =item *
17784: 
17785: arrayref2str($arrayref) : convert an arrayref into a string complete
17786: with escaping and '&' separators, supports elements that are arrayrefs
17787: and hashrefs
17788: 
17789: =item *
17790: 
17791: str2hash($string) : convert string to hash using unescaping and
17792: splitting on '=' and '&', supports elements that are arrayrefs and
17793: hashrefs
17794: 
17795: =item *
17796: 
17797: str2array($string) : convert string to hash using unescaping and
17798: splitting on '&', supports elements that are arrayrefs and hashrefs
17799: 
17800: =back
17801: 
17802: =head2 Logging Routines
17803: 
17804: 
17805: These routines allow one to make log messages in the lonnet.log and
17806: lonnet.perm logfiles.
17807: 
17808: =over 4
17809: 
17810: =item *
17811: 
17812: logtouch() : make sure the logfile, lonnet.log, exists
17813: 
17814: =item *
17815: 
17816: logthis() : append message to the normal lonnet.log file, it gets
17817: preiodically rolled over and deleted.
17818: 
17819: =item *
17820: 
17821: logperm() : append a permanent message to lonnet.perm.log, this log
17822: file never gets deleted by any automated portion of the system, only
17823: messages of critical importance should go in here.
17824: 
17825: 
17826: =back
17827: 
17828: =head2 General File Helper Routines
17829: 
17830: =over 4
17831: 
17832: =item *
17833: 
17834: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
17835: (a) files in /uploaded
17836:   (i) If a local copy of the file exists - 
17837:       compares modification date of local copy with last-modified date for 
17838:       definitive version stored on home server for course. If local copy is 
17839:       stale, requests a new version from the home server and stores it. 
17840:       If the original has been removed from the home server, then local copy 
17841:       is unlinked.
17842:   (ii) If local copy does not exist -
17843:       requests the file from the home server and stores it. 
17844:   
17845:   If $caller is 'uploadrep':  
17846:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
17847:     for request for files originally uploaded via DOCS. 
17848:      - returns 'ok' if fresh local copy now available, -1 otherwise.
17849:   
17850:   Otherwise:
17851:      This indicates a call from the content generation phase of the request.
17852:      -  returns the entire contents of the file or -1.
17853:      
17854: (b) files in /res
17855:    - returns the entire contents of a file or -1; 
17856:    it properly subscribes to and replicates the file if neccessary.
17857: 
17858: 
17859: =item *
17860: 
17861: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
17862:                   reference
17863: 
17864: returns either a stat() list of data about the file or an empty list
17865: if the file doesn't exist or couldn't find out about it (connection
17866: problems or user unknown)
17867: 
17868: =item *
17869: 
17870: filelocation($dir,$file) : returns file system location of a file
17871: based on URI; meant to be "fairly clean" absolute reference, $dir is a
17872: directory that relative $file lookups are to looked in ($dir of /a/dir
17873: and a file of ../bob will become /a/bob)
17874: 
17875: =item *
17876: 
17877: hreflocation($dir,$file) : returns file system location or a URL; same as
17878: filelocation except for hrefs
17879: 
17880: =item *
17881: 
17882: declutter() : declutters URLs -- remove beginning slashes, 'res' etc.
17883: also removes beginning /home/httpd/html unless /priv/ follows it.
17884: 
17885: =back
17886: 
17887: =head2 Usererfile file routines (/uploaded*)
17888: 
17889: =over 4
17890: 
17891: =item *
17892: 
17893: userfileupload(): main rotine for putting a file in a user or course's
17894:                   filespace, arguments are,
17895: 
17896:  formname - required - this is the name of the element in $env where the
17897:            filename, and the contents of the file to create/modifed exist
17898:            the filename is in $env{'form.'.$formname.'.filename'} and the
17899:            contents of the file is located in $env{'form.'.$formname}
17900:  context - if coursedoc, store the file in the course of the active role
17901:              of the current user; 
17902:            if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
17903:            if 'canceloverwrite': delete file in tmp/overwrites directory
17904:  subdir - required - subdirectory to put the file in under ../userfiles/
17905:          if undefined, it will be placed in "unknown"
17906: 
17907:  (This routine calls clean_filename() to remove any dangerous
17908:  characters from the filename, and then calls finuserfileupload() to
17909:  complete the transaction)
17910: 
17911:  returns either the url of the uploaded file (/uploaded/....) if successful
17912:  and /adm/notfound.html if unsuccessful
17913: 
17914: =item *
17915: 
17916: clean_filename(): routine for cleaing a filename up for storage in
17917:                  userfile space, argument is:
17918: 
17919:  filename - proposed filename
17920: 
17921: returns: the new clean filename
17922: 
17923: =item *
17924: 
17925: finishuserfileupload(): routine that creates and sends the file to
17926: userspace, probably shouldn't be called directly
17927: 
17928:   docuname: username or courseid of destination for the file
17929:   docudom: domain of user/course of destination for the file
17930:   formname: same as for userfileupload()
17931:   fname: filename (including subdirectories) for the file
17932:   parser: if 'parse', will parse (html) file to extract references to objects, links etc.
17933:           if hashref, and context is scantron, will convert csv format to standard format
17934:   allfiles: reference to hash used to store objects found by parser
17935:   codebase: reference to hash used for codebases of java objects found by parser
17936:   thumbwidth: width (pixels) of thumbnail to be created for uploaded image
17937:   thumbheight: height (pixels) of thumbnail to be created for uploaded image
17938:   resizewidth: width to be used to resize image using resizeImage from ImageMagick
17939:   resizeheight: height to be used to resize image using resizeImage from ImageMagick
17940:   context: if 'overwrite', will move the uploaded file from its temporary location to
17941:             userfiles to facilitate overwriting a previously uploaded file with same name.
17942:   mimetype: reference to scalar to accommodate mime type determined
17943:             from File::MMagic if $parser = parse.
17944: 
17945:  returns either the url of the uploaded file (/uploaded/....) if successful
17946:  and /adm/notfound.html if unsuccessful (or an error message if context 
17947:  was 'overwrite').
17948:  
17949: 
17950: =item *
17951: 
17952: renameuserfile(): renames an existing userfile to a new name
17953: 
17954:   Args:
17955:    docuname: username or courseid of destination for the file
17956:    docudom: domain of user/course of destination for the file
17957:    old: current file name (including any subdirs under userfiles)
17958:    new: desired file name (including any subdirs under userfiles)
17959: 
17960: =item *
17961: 
17962: mkdiruserfile(): creates a directory is a userfiles dir
17963: 
17964:   Args:
17965:    docuname: username or courseid of destination for the file
17966:    docudom: domain of user/course of destination for the file
17967:    dir: dir to create (including any subdirs under userfiles)
17968: 
17969: =item *
17970: 
17971: removeuserfile(): removes a file that exists in userfiles
17972: 
17973:   Args:
17974:    docuname: username or courseid of destination for the file
17975:    docudom: domain of user/course of destination for the file
17976:    fname: filname to delete (including any subdirs under userfiles)
17977: 
17978: =item *
17979: 
17980: removeuploadedurl(): convience function for removeuserfile()
17981: 
17982:   Args:
17983:    url:  a full /uploaded/... url to delete
17984: 
17985: =item * 
17986: 
17987: get_portfile_permissions():
17988:   Args:
17989:     domain: domain of user or course contain the portfolio files
17990:     user: name of user or num of course contain the portfolio files
17991:   Returns:
17992:     hashref of a dump of the proper file_permissions.db
17993:    
17994: 
17995: =item * 
17996: 
17997: get_access_controls():
17998: 
17999: Args:
18000:   current_permissions: the hash ref returned from get_portfile_permissions()
18001:   group: (optional) the group you want the files associated with
18002:   file: (optional) the file you want access info on
18003: 
18004: Returns:
18005:     a hash (keys are file names) of hashes containing
18006:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
18007:         values are XML containing access control settings (see below) 
18008: 
18009: Internal notes:
18010: 
18011:  access controls are stored in file_permissions.db as key=value pairs.
18012:     key -> path to file/file_name\0uniqueID:scope_end_start
18013:         where scope -> public,guest,course,group,domains or users.
18014:               end -> UNIX time for end of access (0 -> no end date)
18015:               start -> UNIX time for start of access
18016: 
18017:     value -> XML description of access control
18018:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
18019:             <start></start>
18020:             <end></end>
18021: 
18022:             <password></password>  for scope type = guest
18023: 
18024:             <domain></domain>     for scope type = course or group
18025:             <number></number>
18026:             <roles id="">
18027:              <role></role>
18028:              <access></access>
18029:              <section></section>
18030:              <group></group>
18031:             </roles>
18032: 
18033:             <dom></dom>         for scope type = domains
18034: 
18035:             <users>             for scope type = users
18036:              <user>
18037:               <uname></uname>
18038:               <udom></udom>
18039:              </user>
18040:             </users>
18041:            </scope> 
18042:               
18043:  Access data is also aggregated for each file in an additional key=value pair:
18044:  key -> path to file/file_name\0accesscontrol 
18045:  value -> reference to hash
18046:           hash contains key = value pairs
18047:           where key = uniqueID:scope_end_start
18048:                 value = UNIX time record was last updated
18049: 
18050:           Used to improve speed of look-ups of access controls for each file.  
18051:  
18052:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
18053: 
18054: =item *
18055: 
18056: modify_access_controls():
18057: 
18058: Modifies access controls for a portfolio file
18059: Args
18060: 1. file name
18061: 2. reference to hash of required changes,
18062: 3. domain
18063: 4. username
18064:   where domain,username are the domain of the portfolio owner 
18065:   (either a user or a course) 
18066: 
18067: Returns:
18068: 1. result of additions or updates ('ok' or 'error', with error message). 
18069: 2. result of deletions ('ok' or 'error', with error message).
18070: 3. reference to hash of any new or updated access controls.
18071: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
18072:    key = integer (inbound ID)
18073:    value = uniqueID
18074: 
18075: =item *
18076: 
18077: get_timebased_id():
18078: 
18079: Attempts to get a unique timestamp-based suffix for use with items added to a 
18080: course via the Course Editor (e.g., folders, composite pages, 
18081: group bulletin boards).
18082: 
18083: Args: (first three required; six others optional)
18084: 
18085: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
18086:    docssequence, or name of group
18087: 
18088: 2. keyid (alphanumeric): name of temporary locking key in hash,
18089:    e.g., num, boardids
18090: 
18091: 3. namespace: name of gdbm file used to store suffixes already assigned;  
18092:    file will be named nohist_namespace.db
18093: 
18094: 4. cdom: domain of course; default is current course domain from %env
18095: 
18096: 5. cnum: course number; default is current course number from %env
18097: 
18098: 6. idtype: set to concat if an additional digit is to be appended to the 
18099:    unix timestamp to form the suffix, if the plain timestamp is already
18100:    in use.  Default is to not do this, but simply increment the unix 
18101:    timestamp by 1 until a unique key is obtained.
18102: 
18103: 7. who: holder of locking key; defaults to user:domain for user.
18104: 
18105: 8. locktries: number of attempts to obtain a lock (sleep of 1s before 
18106:    retrying); default is 3.
18107: 
18108: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.  
18109: 
18110: Returns:
18111: 
18112: 1. suffix obtained (numeric)
18113: 
18114: 2. result of deleting locking key (ok if deleted, or lock never obtained)
18115: 
18116: 3. error: contains (localized) error message if an error occurred.
18117: 
18118: 
18119: =back
18120: 
18121: =head2 HTTP Helper Routines
18122: 
18123: =over 4
18124: 
18125: =item *
18126: 
18127: escape() : unpack non-word characters into CGI-compatible hex codes
18128: 
18129: =item *
18130: 
18131: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
18132: 
18133: =back
18134: 
18135: =head1 PRIVATE SUBROUTINES
18136: 
18137: =head2 Underlying communication routines (Shouldn't call)
18138: 
18139: =over 4
18140: 
18141: =item *
18142: 
18143: subreply() : tries to pass a message to lonc, returns con_lost if incapable
18144: 
18145: =item *
18146: 
18147: reply() : uses subreply to send a message to remote machine, logs all failures
18148: 
18149: =item *
18150: 
18151: critical() : passes a critical message to another server; if cannot
18152: get through then place message in connection buffer directory and
18153: returns con_delayed, if incapable of saving message, returns
18154: con_failed
18155: 
18156: =item *
18157: 
18158: reconlonc() : tries to reconnect lonc client processes.
18159: 
18160: =back
18161: 
18162: =head2 Resource Access Logging
18163: 
18164: =over 4
18165: 
18166: =item *
18167: 
18168: flushcourselogs() : flush (save) buffer logs and access logs
18169: 
18170: =item *
18171: 
18172: courselog($what) : save message for course in hash
18173: 
18174: =item *
18175: 
18176: courseacclog($what) : save message for course using &courselog().  Perform
18177: special processing for specific resource types (problems, exams, quizzes, etc).
18178: 
18179: =item *
18180: 
18181: goodbye() : flush course logs and log shutting down; it is called in srm.conf
18182: as a PerlChildExitHandler
18183: 
18184: =back
18185: 
18186: =head2 Other
18187: 
18188: =over 4
18189: 
18190: =item *
18191: 
18192: symblist($mapname,%newhash) : update symbolic storage links
18193: 
18194: =back
18195: 
18196: =cut
18197: 

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