File:  [LON-CAPA] / loncom / lonnet / perl / lonnet.pm
Revision 1.1521: download - view: text, annotated - select for diffs
Thu Dec 28 15:57:28 2023 UTC (6 months, 2 weeks ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Portfolio shareability setting in domain defaults (by affiliation), with
  possible override for an individual user taken into account.

    1: # The LearningOnline Network
    2: # TCP networking package
    3: #
    4: # $Id: lonnet.pm,v 1.1521 2023/12/28 15:57:28 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);
 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:             }
 8035:         }
 8036:         if ($public) {
 8037:             return 'ok';
 8038:         } elsif (@ips > 0) {
 8039:             my $allowed;
 8040:             foreach my $ipkey (@ips) {
 8041:                 if (ref($access_hash->{$ipkey}{'ip'}) eq 'ARRAY') {
 8042:                     if (&Apache::loncommon::check_ip_acc(join(',',@{$access_hash->{$ipkey}{'ip'}}),$clientip)) {
 8043:                         $allowed = 1;
 8044:                         last; 
 8045:                     }
 8046:                 }
 8047:             }
 8048:             if ($allowed) {
 8049:                 return 'ok';
 8050:             }
 8051:         }
 8052:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 8053:             if ($guest) {
 8054:                 return $guest;
 8055:             }
 8056:         } else {
 8057:             if (@domains > 0) {
 8058:                 foreach my $domkey (@domains) {
 8059:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
 8060:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
 8061:                             return 'ok';
 8062:                         }
 8063:                     }
 8064:                 }
 8065:             }
 8066:             if (@users > 0) {
 8067:                 foreach my $userkey (@users) {
 8068:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
 8069:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
 8070:                             if (ref($item) eq 'HASH') {
 8071:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
 8072:                                     ($item->{'udom'} eq $env{'user.domain'})) {
 8073:                                     return 'ok';
 8074:                                 }
 8075:                             }
 8076:                         }
 8077:                     } 
 8078:                 }
 8079:             }
 8080:             my %roleshash;
 8081:             my @courses_and_groups = @courses;
 8082:             push(@courses_and_groups,@groups); 
 8083:             if (@courses_and_groups > 0) {
 8084:                 my (%allgroups,%allroles); 
 8085:                 my ($start,$end,$role,$sec,$group);
 8086:                 foreach my $envkey (%env) {
 8087:                     if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
 8088:                         my $cid = $2.'_'.$3; 
 8089:                         if ($1 eq 'gr') {
 8090:                             $group = $4;
 8091:                             $allgroups{$cid}{$group} = $env{$envkey};
 8092:                         } else {
 8093:                             if ($4 eq '') {
 8094:                                 $sec = 'none';
 8095:                             } else {
 8096:                                 $sec = $4;
 8097:                             }
 8098:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
 8099:                         }
 8100:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
 8101:                         my $cid = $2.'_'.$3;
 8102:                         if ($4 eq '') {
 8103:                             $sec = 'none';
 8104:                         } else {
 8105:                             $sec = $4;
 8106:                         }
 8107:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
 8108:                     }
 8109:                 }
 8110:                 if (keys(%allroles) == 0) {
 8111:                     return;
 8112:                 }
 8113:                 foreach my $key (@courses_and_groups) {
 8114:                     my %content = %{$$access_hash{$key}};
 8115:                     my $cnum = $content{'number'};
 8116:                     my $cdom = $content{'domain'};
 8117:                     my $cid = $cdom.'_'.$cnum;
 8118:                     if (!exists($allroles{$cid})) {
 8119:                         next;
 8120:                     }    
 8121:                     foreach my $role_id (keys(%{$content{'roles'}})) {
 8122:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
 8123:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
 8124:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
 8125:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
 8126:                         foreach my $role (keys(%{$allroles{$cid}})) {
 8127:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
 8128:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
 8129:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
 8130:                                         if (grep/^all$/,@sections) {
 8131:                                             return 'ok';
 8132:                                         } else {
 8133:                                             if (grep/^$sec$/,@sections) {
 8134:                                                 return 'ok';
 8135:                                             }
 8136:                                         }
 8137:                                     }
 8138:                                 }
 8139:                                 if (keys(%{$allgroups{$cid}}) == 0) {
 8140:                                     if (grep/^none$/,@groups) {
 8141:                                         return 'ok';
 8142:                                     }
 8143:                                 } else {
 8144:                                     if (grep/^all$/,@groups) {
 8145:                                         return 'ok';
 8146:                                     } 
 8147:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
 8148:                                         if (grep/^$group$/,@groups) {
 8149:                                             return 'ok';
 8150:                                         }
 8151:                                     }
 8152:                                 } 
 8153:                             }
 8154:                         }
 8155:                     }
 8156:                 }
 8157:             }
 8158:             if ($guest) {
 8159:                 return $guest;
 8160:             }
 8161:         }
 8162:     }
 8163:     return;
 8164: }
 8165: 
 8166: sub course_group_datechecker {
 8167:     my ($dates,$now,$status) = @_;
 8168:     my ($start,$end) = split(/\./,$dates);
 8169:     if (!$start && !$end) {
 8170:         return 'ok';
 8171:     }
 8172:     if (grep/^active$/,@{$status}) {
 8173:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
 8174:             return 'ok';
 8175:         }
 8176:     }
 8177:     if (grep/^previous$/,@{$status}) {
 8178:         if ($end > $now ) {
 8179:             return 'ok';
 8180:         }
 8181:     }
 8182:     if (grep/^future$/,@{$status}) {
 8183:         if ($start > $now) {
 8184:             return 'ok';
 8185:         }
 8186:     }
 8187:     return; 
 8188: }
 8189: 
 8190: sub parse_portfolio_url {
 8191:     my ($url) = @_;
 8192: 
 8193:     my ($type,$udom,$unum,$group,$file_name);
 8194:     
 8195:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
 8196: 	$type = 1;
 8197:         $udom = $1;
 8198:         $unum = $2;
 8199:         $file_name = $3;
 8200:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
 8201: 	$type = 2;
 8202:         $udom = $1;
 8203:         $unum = $2;
 8204:         $group = $3;
 8205:         $file_name = $3.'/'.$4;
 8206:     }
 8207:     if (wantarray) {
 8208: 	return ($type,$udom,$unum,$file_name,$group);
 8209:     }
 8210:     return $type;
 8211: }
 8212: 
 8213: sub is_portfolio_url {
 8214:     my ($url) = @_;
 8215:     return scalar(&parse_portfolio_url($url));
 8216: }
 8217: 
 8218: sub is_portfolio_file {
 8219:     my ($file) = @_;
 8220:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
 8221:         return 1;
 8222:     }
 8223:     return;
 8224: }
 8225: 
 8226: sub is_coursetool_logo {
 8227:     my ($uri) = @_;
 8228:     if ($env{'request.course.id'}) {
 8229:         my $courseurl = &courseid_to_courseurl($env{'request.course.id'});
 8230:         if ($uri =~ m{^/*uploaded\Q$courseurl\E/toollogo/\d+/[^/]+$}) {
 8231:             return 1;
 8232:         }
 8233:     }
 8234:     return;
 8235: }
 8236: 
 8237: sub usertools_access {
 8238:     my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
 8239:     my ($access,%tools);
 8240:     if ($context eq '') {
 8241:         $context = 'tools';
 8242:     }
 8243:     if ($context eq 'requestcourses') {
 8244:         %tools = (
 8245:                       official   => 1,
 8246:                       unofficial => 1,
 8247:                       community  => 1,
 8248:                       textbook   => 1,
 8249:                       placement  => 1,
 8250:                       lti        => 1,
 8251:                  );
 8252:     } elsif ($context eq 'requestauthor') {
 8253:         %tools = (
 8254:                       requestauthor => 1,
 8255:                  );
 8256:     } elsif ($context eq 'authordefaults') {
 8257:         %tools = (
 8258:                       webdav    => 1,
 8259:                  );
 8260:     } else {
 8261:         %tools = (
 8262:                       aboutme   => 1,
 8263:                       blog      => 1,
 8264:                       portfolio => 1,
 8265:                       portaccess => 1,
 8266:                       timezone  => 1,
 8267:                  );
 8268:     }
 8269:     return if (!defined($tools{$tool}));
 8270: 
 8271:     if (($udom eq '') || ($uname eq '')) {
 8272:         $udom = $env{'user.domain'};
 8273:         $uname = $env{'user.name'};
 8274:     }
 8275: 
 8276:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 8277:         if ($action ne 'reload') {
 8278:             if ($context eq 'requestcourses') {
 8279:                 return $env{'environment.canrequest.'.$tool};
 8280:             } elsif ($context eq 'requestauthor') {
 8281:                 return $env{'environment.canrequest.author'};
 8282:             } elsif ($context eq 'authordefaults') {
 8283:                 if ($tool eq 'webdav') {
 8284:                     return $env{'environment.availabletools.'.$tool};
 8285:                 }
 8286:             } else {
 8287:                 return $env{'environment.availabletools.'.$tool};
 8288:             }
 8289:         }
 8290:     }
 8291: 
 8292:     my ($toolstatus,$inststatus,$envkey);
 8293:     if ($context eq 'requestauthor') {
 8294:         $envkey = $context;
 8295:     } elsif ($context eq 'authordefaults') {
 8296:         if ($tool eq 'webdav') {
 8297:             $envkey = 'tools.'.$tool;
 8298:         }
 8299:     } else {
 8300:         $envkey = $context.'.'.$tool;
 8301:     }
 8302: 
 8303:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
 8304:          ($action ne 'reload')) {
 8305:         $toolstatus = $env{'environment.'.$envkey};
 8306:         $inststatus = $env{'environment.inststatus'};
 8307:     } else {
 8308:         if (ref($userenvref) eq 'HASH') {
 8309:             $toolstatus = $userenvref->{$envkey};
 8310:             $inststatus = $userenvref->{'inststatus'};
 8311:         } else {
 8312:             my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
 8313:             $toolstatus = $userenv{$envkey};
 8314:             $inststatus = $userenv{'inststatus'};
 8315:         }
 8316:     }
 8317: 
 8318:     if ($toolstatus ne '') {
 8319:         if ($toolstatus) {
 8320:             $access = 1;
 8321:         } else {
 8322:             $access = 0;
 8323:         }
 8324:         return $access;
 8325:     }
 8326: 
 8327:     my ($is_adv,%domdef);
 8328:     if (ref($is_advref) eq 'HASH') {
 8329:         $is_adv = $is_advref->{'is_adv'};
 8330:     } else {
 8331:         $is_adv = &is_advanced_user($udom,$uname);
 8332:     }
 8333:     if (ref($domdefref) eq 'HASH') {
 8334:         %domdef = %{$domdefref};
 8335:     } else {
 8336:         %domdef = &get_domain_defaults($udom);
 8337:     }
 8338:     if (ref($domdef{$tool}) eq 'HASH') {
 8339:         if ($is_adv) {
 8340:             if ($domdef{$tool}{'_LC_adv'} ne '') {
 8341:                 if ($domdef{$tool}{'_LC_adv'}) { 
 8342:                     $access = 1;
 8343:                 } else {
 8344:                     $access = 0;
 8345:                 }
 8346:                 return $access;
 8347:             }
 8348:         }
 8349:         if ($inststatus ne '') {
 8350:             my ($hasaccess,$hasnoaccess);
 8351:             foreach my $affiliation (split(/:/,$inststatus)) {
 8352:                 if ($domdef{$tool}{$affiliation} ne '') { 
 8353:                     if ($domdef{$tool}{$affiliation}) {
 8354:                         $hasaccess = 1;
 8355:                     } else {
 8356:                         $hasnoaccess = 1;
 8357:                     }
 8358:                 }
 8359:             }
 8360:             if ($hasaccess || $hasnoaccess) {
 8361:                 if ($hasaccess) {
 8362:                     $access = 1;
 8363:                 } elsif ($hasnoaccess) {
 8364:                     $access = 0; 
 8365:                 }
 8366:                 return $access;
 8367:             }
 8368:         } else {
 8369:             if ($domdef{$tool}{'default'} ne '') {
 8370:                 if ($domdef{$tool}{'default'}) {
 8371:                     $access = 1;
 8372:                 } elsif ($domdef{$tool}{'default'} == 0) {
 8373:                     $access = 0;
 8374:                 }
 8375:                 return $access;
 8376:             }
 8377:         }
 8378:     } else {
 8379:         if (($context eq 'tools') && ($tool ne 'webdav')) {
 8380:             $access = 1;
 8381:         } else {
 8382:             $access = 0;
 8383:         }
 8384:         return $access;
 8385:     }
 8386: }
 8387: 
 8388: sub is_course_owner {
 8389:     my ($cdom,$cnum,$udom,$uname) = @_;
 8390:     if (($udom eq '') || ($uname eq '')) {
 8391:         $udom = $env{'user.domain'};
 8392:         $uname = $env{'user.name'};
 8393:     }
 8394:     unless (($udom eq '') || ($uname eq '')) {
 8395:         if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
 8396:             if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
 8397:                 return 1;
 8398:             } else {
 8399:                 my %courseinfo = &coursedescription($cdom.'/'.$cnum);
 8400:                 if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
 8401:                     return 1;
 8402:                 }
 8403:             }
 8404:         }
 8405:     }
 8406:     return;
 8407: }
 8408: 
 8409: sub is_advanced_user {
 8410:     my ($udom,$uname,$nocache) = @_;
 8411:     my ($is_adv,$is_author,$use_cache,$hashid);
 8412:     if ($udom ne '' && $uname ne '') {
 8413:         if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 8414:             if (wantarray) {
 8415:                 return ($env{'user.adv'},$env{'user.author'});
 8416:             } else {
 8417:                 return $env{'user.adv'};
 8418:             }
 8419:         } elsif (!$nocache) {
 8420:             $use_cache = 1;
 8421:             $hashid = "$udom:$uname";  
 8422:             my ($info,$cached)=&is_cached_new('isadvau',$hashid);
 8423:             if ($cached) {
 8424:                 ($is_adv,$is_author) = split(/:/,$info);
 8425:                 if (wantarray) {
 8426:                     return ($is_adv,$is_author);
 8427:                 }
 8428:                 return $is_adv; 
 8429:             }
 8430:         }
 8431:     }
 8432:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
 8433:     my %allroles;
 8434:     foreach my $role (keys(%roleshash)) {
 8435:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
 8436:         my $area = '/'.$tdomain.'/'.$trest;
 8437:         if ($sec ne '') {
 8438:             $area .= '/'.$sec;
 8439:         }
 8440:         if (($area ne '') && ($trole ne '')) {
 8441:             my $spec=$trole.'.'.$area;
 8442:             if ($trole =~ /^cr\//) {
 8443:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
 8444:             } elsif ($trole ne 'gr') {
 8445:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
 8446:             }
 8447:             if ($trole eq 'au') {
 8448:                 $is_author = 1;
 8449:             }
 8450:         }
 8451:     }
 8452:     foreach my $role (keys(%allroles)) {
 8453:         last if ($is_adv);
 8454:         foreach my $item (split(/:/,$allroles{$role})) {
 8455:             if ($item ne '') {
 8456:                 my ($privilege,$restrictions)=split(/&/,$item);
 8457:                 if ($privilege eq 'adv') {
 8458:                     $is_adv = 1;
 8459:                     last;
 8460:                 }
 8461:             }
 8462:         }
 8463:     }
 8464:     if ($use_cache) {
 8465:         my $cachetime = 600;
 8466:         &do_cache_new('isadvau',$hashid,$is_adv.':'.$is_author,$cachetime);
 8467:     }
 8468:     if (wantarray) {
 8469:         return ($is_adv,$is_author);
 8470:     }
 8471:     return $is_adv;
 8472: }
 8473: 
 8474: sub check_can_request {
 8475:     my ($dom,$can_request,$request_domains,$uname,$udom) = @_;
 8476:     my $canreq = 0;
 8477:     if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
 8478:         $uname = $env{'user.name'};
 8479:         $udom = $env{'user.domain'};
 8480:     }
 8481:     my ($types,$typename) = &Apache::loncommon::course_types();
 8482:     my @options = ('approval','validate','autolimit');
 8483:     my $optregex = join('|',@options);
 8484:     if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
 8485:         my %willtrust;
 8486:         foreach my $type (@{$types}) {
 8487:             if (&usertools_access($uname,$udom,$type,undef,
 8488:                                   'requestcourses')) {
 8489:                 $canreq ++;
 8490:                 if (ref($request_domains) eq 'HASH') {
 8491:                     push(@{$request_domains->{$type}},$udom);
 8492:                 }
 8493:                 if ($dom eq $udom) {
 8494:                     $can_request->{$type} = 1;
 8495:                 }
 8496:             }
 8497:             if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '') &&
 8498:                 ($env{'environment.reqcrsotherdom.'.$type} ne '')) {
 8499:                 my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
 8500:                 if (@curr > 0) {
 8501:                     foreach my $item (@curr) {
 8502:                         if (ref($request_domains) eq 'HASH') {
 8503:                             my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
 8504:                             if ($otherdom ne '') {
 8505:                                 unless (exists($willtrust{$otherdom})) {
 8506:                                     $willtrust{$otherdom} = &will_trust('reqcrs',$env{'user.domain'},$otherdom);
 8507:                                 }
 8508:                                 if ($willtrust{$otherdom}) {
 8509:                                     if (ref($request_domains->{$type}) eq 'ARRAY') {
 8510:                                         unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
 8511:                                             push(@{$request_domains->{$type}},$otherdom);
 8512:                                         }
 8513:                                     } else {
 8514:                                         push(@{$request_domains->{$type}},$otherdom);
 8515:                                     }
 8516:                                 }
 8517:                             }
 8518:                         }
 8519:                     }
 8520:                     unless ($dom eq $env{'user.domain'}) {
 8521:                         $canreq ++;
 8522:                         if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
 8523:                             $can_request->{$type} = 1;
 8524:                         }
 8525:                     }
 8526:                 }
 8527:             }
 8528:         }
 8529:     }
 8530:     return $canreq;
 8531: }
 8532: 
 8533: # ---------------------------------------------- Custom access rule evaluation
 8534: 
 8535: sub customaccess {
 8536:     my ($priv,$uri)=@_;
 8537:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
 8538:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
 8539:     $udom = &LONCAPA::clean_domain($udom);
 8540:     $ucrs = &LONCAPA::clean_username($ucrs);
 8541:     my $access=0;
 8542:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
 8543: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
 8544: 	if ($type eq 'user') {
 8545: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
 8546: 		my ($tdom,$tuname)=split(m{/},$scope);
 8547: 		if ($tdom) {
 8548: 		    if ($tdom ne $env{'user.domain'}) { next; }
 8549: 		}
 8550: 		if ($tuname) {
 8551: 		    if ($tuname ne $env{'user.name'}) { next; }
 8552: 		}
 8553: 		$access=($effect eq 'allow');
 8554: 		last;
 8555: 	    }
 8556: 	} else {
 8557: 	    if ($role) {
 8558: 		if ($role ne $urole) { next; }
 8559: 	    }
 8560: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
 8561: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
 8562: 		if ($tdom) {
 8563: 		    if ($tdom ne $udom) { next; }
 8564: 		}
 8565: 		if ($tcrs) {
 8566: 		    if ($tcrs ne $ucrs) { next; }
 8567: 		}
 8568: 		if ($tsec) {
 8569: 		    if ($tsec ne $usec) { next; }
 8570: 		}
 8571: 		$access=($effect eq 'allow');
 8572: 		last;
 8573: 	    }
 8574: 	    if ($realm eq '' && $role eq '') {
 8575: 		$access=($effect eq 'allow');
 8576: 	    }
 8577: 	}
 8578:     }
 8579:     return $access;
 8580: }
 8581: 
 8582: # ------------------------------------------------- Check for a user privilege
 8583: 
 8584: sub allowed {
 8585:     my ($priv,$uri,$symb,$role,$clientip,$noblockcheck,$ignorecache,$nodeeplinkcheck,$nodeeplinkout)=@_;
 8586:     my $ver_orguri=$uri;
 8587:     $uri=&deversion($uri);
 8588:     my $orguri=$uri;
 8589:     $uri=&declutter($uri);
 8590: 
 8591:     if ($priv eq 'evb') {
 8592: # Evade communication block restrictions for specified role in a course or domain
 8593:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
 8594:             return $1;
 8595:         } else {
 8596:             return;
 8597:         }
 8598:     }
 8599: 
 8600:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
 8601: # Free bre access to adm and meta resources
 8602:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard|viewclasslist|aboutme|ext\.tool)$})) 
 8603: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
 8604: 	&& ($priv eq 'bre')) {
 8605: 	return 'F';
 8606:     }
 8607: 
 8608: # Free bre access to user's own portfolio contents
 8609:     my ($space,$domain,$name,@dir)=split('/',$uri);
 8610:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
 8611: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
 8612:         my %setters;
 8613:         my ($startblock,$endblock,$triggerblock,$by_ip,$blockdom) = 
 8614:             &Apache::loncommon::blockcheck(\%setters,'port',$clientip);
 8615:         if (($startblock && $endblock) || ($by_ip)) {
 8616:             return 'B';
 8617:         } else {
 8618:             return 'F';
 8619:         }
 8620:     }
 8621: 
 8622: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
 8623:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
 8624:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
 8625:         if (exists($env{'request.course.id'})) {
 8626:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 8627:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 8628:             if (($domain eq $cdom) && ($name eq $cnum)) {
 8629:                 my $courseprivid=$env{'request.course.id'};
 8630:                 $courseprivid=~s/\_/\//;
 8631:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
 8632:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
 8633:                     return $1; 
 8634:                 } else {
 8635:                     if ($env{'request.course.sec'}) {
 8636:                         $courseprivid.='/'.$env{'request.course.sec'};
 8637:                     }
 8638:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
 8639:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
 8640:                         return $2;
 8641:                     }
 8642:                 }
 8643:             }
 8644:         }
 8645:     }
 8646: 
 8647: # Free bre to public access
 8648: 
 8649:     if ($priv eq 'bre') {
 8650:         my $copyright;
 8651:         unless ($uri =~ /ext\.tool/) {
 8652:             $copyright=&metadata($uri,'copyright');
 8653:         }
 8654: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
 8655:            return 'F'; 
 8656:         }
 8657:         if ($copyright eq 'priv') {
 8658:             $uri=~/([^\/]+)\/([^\/]+)\//;
 8659: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
 8660: 		return '';
 8661:             }
 8662:         }
 8663:         if ($copyright eq 'domain') {
 8664:             $uri=~/([^\/]+)\/([^\/]+)\//;
 8665: 	    unless (($env{'user.domain'} eq $1) ||
 8666:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
 8667: 		return '';
 8668:             }
 8669:         }
 8670:         if ($env{'request.role'}=~ /li\.\//) {
 8671:             # Library role, so allow browsing of resources in this domain.
 8672:             return 'F';
 8673:         }
 8674:         if ($copyright eq 'custom') {
 8675: 	    unless (&customaccess($priv,$uri)) { return ''; }
 8676:         }
 8677:     }
 8678:     # Domain coordinator is trying to create a course
 8679:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
 8680:         # uri is the requested domain in this case.
 8681:         # comparison to 'request.role.domain' shows if the user has selected
 8682:         # a role of dc for the domain in question.
 8683:         return 'F' if ($uri eq $env{'request.role.domain'});
 8684:     }
 8685: 
 8686:     my $thisallowed='';
 8687:     my $statecond=0;
 8688:     my $courseprivid='';
 8689: 
 8690:     my $ownaccess;
 8691:     # Community Coordinator or Assistant Co-author browsing resource space.
 8692:     if (($priv eq 'bro') && ($env{'user.author'})) {
 8693:         if ($uri eq '') {
 8694:             $ownaccess = 1;
 8695:         } else {
 8696:             if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
 8697:                 my $udom = $env{'user.domain'};
 8698:                 my $uname = $env{'user.name'};
 8699:                 if ($uri =~ m{^\Q$udom\E/?$}) {
 8700:                     $ownaccess = 1;
 8701:                 } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
 8702:                     unless ($uri =~ m{\.\./}) {
 8703:                         $ownaccess = 1;
 8704:                     }
 8705:                 } elsif (($udom ne 'public') && ($uname ne 'public')) {
 8706:                     my $now = time;
 8707:                     if ($uri =~ m{^([^/]+)/?$}) {
 8708:                         my $adom = $1;
 8709:                         foreach my $key (keys(%env)) {
 8710:                             if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
 8711:                                 my ($start,$end) = split(/\./,$env{$key});
 8712:                                 if (($now >= $start) && (!$end || $end > $now)) {
 8713:                                     $ownaccess = 1;
 8714:                                     last;
 8715:                                 }
 8716:                             }
 8717:                         }
 8718:                     } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
 8719:                         my $adom = $1;
 8720:                         my $aname = $2;
 8721:                         foreach my $role ('ca','aa') { 
 8722:                             if ($env{"user.role.$role./$adom/$aname"}) {
 8723:                                 my ($start,$end) =
 8724:                                     split(/\./,$env{"user.role.$role./$adom/$aname"});
 8725:                                 if (($now >= $start) && (!$end || $end > $now)) {
 8726:                                     $ownaccess = 1;
 8727:                                     last;
 8728:                                 }
 8729:                             }
 8730:                         }
 8731:                     }
 8732:                 }
 8733:             }
 8734:         }
 8735:     }
 8736: 
 8737: # Course
 8738: 
 8739:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
 8740:         unless (($priv eq 'bro') && (!$ownaccess)) {
 8741:             $thisallowed.=$1;
 8742:         }
 8743:     }
 8744: 
 8745: # Domain
 8746: 
 8747:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
 8748:        =~/\Q$priv\E\&([^\:]*)/) {
 8749:         unless (($priv eq 'bro') && (!$ownaccess)) {
 8750:             $thisallowed.=$1;
 8751:         }
 8752:     }
 8753: 
 8754: # User who is not author or co-author might still be able to edit
 8755: # resource of an author in the domain (e.g., if Domain Coordinator).
 8756:     if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
 8757:         (&allowed('mdc',$env{'request.course.id'}))) {
 8758:         if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
 8759:             $thisallowed.=$1;
 8760:         }
 8761:     }
 8762: 
 8763: # Course: uri itself is a course
 8764:     my $courseuri=$uri;
 8765:     $courseuri=~s/\_(\d)/\/$1/;
 8766:     $courseuri=~s/^([^\/])/\/$1/;
 8767: 
 8768:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
 8769:        =~/\Q$priv\E\&([^\:]*)/) {
 8770:         if ($priv eq 'mip') {
 8771:             my $rem = $1;
 8772:             if (($uri ne '') && ($env{'request.course.id'} eq $uri) &&
 8773:                 ($env{'course.'.$env{'request.course.id'}.'.internal.courseowner'} eq $env{'user.name'}.':'.$env{'user.domain'})) {
 8774:                 my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 8775:                 if ($cdom ne '') {
 8776:                     my %passwdconf = &get_passwdconf($cdom);
 8777:                     if (ref($passwdconf{'crsownerchg'}) eq 'HASH') {
 8778:                         if (ref($passwdconf{'crsownerchg'}{'by'}) eq 'ARRAY') {
 8779:                             if (@{$passwdconf{'crsownerchg'}{'by'}}) {
 8780:                                 my @inststatuses = split(':',$env{'environment.inststatus'});
 8781:                                 unless (@inststatuses) {
 8782:                                     @inststatuses = ('default');
 8783:                                 }
 8784:                                 foreach my $status (@inststatuses) {
 8785:                                     if (grep(/^\Q$status\E$/,@{$passwdconf{'crsownerchg'}{'by'}})) {
 8786:                                         $thisallowed.=$rem;
 8787:                                     }
 8788:                                 }
 8789:                             }
 8790:                         }
 8791:                     }
 8792:                 }
 8793:             }
 8794:         } else {
 8795:             unless (($priv eq 'bro') && (!$ownaccess)) {
 8796:                 $thisallowed.=$1;
 8797:             }
 8798:         }
 8799:     }
 8800: 
 8801: # URI is an uploaded document for this course, default permissions don't matter
 8802: # not allowing 'edit' access (editupload) to uploaded course docs
 8803:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
 8804: 	$thisallowed='';
 8805:         my ($match)=&is_on_map($uri);
 8806:         if ($match) {
 8807:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
 8808:                   =~/\Q$priv\E\&([^\:]*)/) {
 8809:                 my $value = $1;
 8810:                 my $deeplinkblock;
 8811:                 unless ($nodeeplinkcheck) {
 8812:                     $deeplinkblock = &deeplink_check($priv,$symb,$uri);
 8813:                 }
 8814:                 if ($deeplinkblock) {
 8815:                     $thisallowed='D';
 8816:                 } elsif ($noblockcheck) {
 8817:                     $thisallowed.=$value;
 8818:                 } else {
 8819:                     my @blockers = &has_comm_blocking($priv,$symb,$uri,$ignorecache);
 8820:                     if (@blockers > 0) {
 8821:                         $thisallowed = 'B';
 8822:                     } else {
 8823:                         $thisallowed.=$value;
 8824:                     }
 8825:                 }
 8826:             }
 8827:         } else {
 8828:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
 8829:             if ($refuri) {
 8830:                 if ($refuri =~ m|^/adm/|) {
 8831:                     $thisallowed='F';
 8832:                 } else {
 8833:                     $refuri=&declutter($refuri);
 8834:                     my ($match) = &is_on_map($refuri);
 8835:                     if ($match) {
 8836:                         my $deeplinkblock;
 8837:                         unless ($nodeeplinkcheck) {
 8838:                             $deeplinkblock = &deeplink_check($priv,$symb,$refuri);
 8839:                         }
 8840:                         if ($deeplinkblock) {
 8841:                             $thisallowed='D';
 8842:                         } elsif ($noblockcheck) {
 8843:                             $thisallowed='F';
 8844:                         } else {
 8845:                             my @blockers = &has_comm_blocking($priv,'',$refuri,'',1);
 8846:                             if (@blockers > 0) {
 8847:                                 $thisallowed = 'B';
 8848:                             } else {
 8849:                                 $thisallowed='F';
 8850:                             }
 8851:                         }
 8852:                     }
 8853:                 }
 8854:             }
 8855:         }
 8856:     }
 8857: 
 8858:     if ($priv eq 'bre'
 8859: 	&& $thisallowed ne 'F' 
 8860: 	&& $thisallowed ne '2'
 8861: 	&& &is_portfolio_url($uri)) {
 8862: 	$thisallowed = &portfolio_access($uri,$clientip);
 8863:     }
 8864: 
 8865: # Full access at system, domain or course-wide level? Exit.
 8866:     if ($thisallowed=~/F/) {
 8867: 	return 'F';
 8868:     }
 8869: 
 8870: # If this is generating or modifying users, exit with special codes
 8871: 
 8872:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:vca:vaa:'=~/\:\Q$priv\E\:/) {
 8873: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
 8874: 	    my ($audom,$auname)=split('/',$uri);
 8875: # no author name given, so this just checks on the general right to make a co-author in this domain
 8876: 	    unless ($auname) { return $thisallowed; }
 8877: # an author name is given, so we are about to actually make a co-author for a certain account
 8878: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
 8879: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
 8880: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
 8881: 	} elsif (($priv eq 'vca') || ($priv eq 'vaa')) {
 8882:             my ($audom,$auname)=split('/',$uri);
 8883:             unless ($auname) { return $thisallowed; }
 8884:             unless (($env{'request.role'} eq "dc./$audom") ||
 8885:                     ($env{'request.role'} eq "ca./$uri")) {
 8886:                 return '';
 8887:             }
 8888: 	}
 8889: 	return $thisallowed;
 8890:     }
 8891: #
 8892: # Gathered so far: system, domain and course wide privileges
 8893: #
 8894: # Course: See if uri or referer is an individual resource that is part of 
 8895: # the course
 8896: 
 8897:     if ($env{'request.course.id'}) {
 8898: 
 8899:         if ($priv eq 'bre') {
 8900:             if (&is_coursetool_logo($uri)) {
 8901:                 return 'F';
 8902:             }
 8903:         }
 8904: 
 8905: # If this is modifying password (internal auth) domains must match for user and user's role.
 8906: 
 8907:         if ($priv eq 'mip') {
 8908:             if ($env{'user.domain'} eq $env{'request.role.domain'}) {
 8909:                 return $thisallowed;
 8910:             } else {
 8911:                 return '';
 8912:             }
 8913:         }
 8914: 
 8915:        $courseprivid=$env{'request.course.id'};
 8916:        if ($env{'request.course.sec'}) {
 8917:           $courseprivid.='/'.$env{'request.course.sec'};
 8918:        }
 8919:        $courseprivid=~s/\_/\//;
 8920:        my $checkreferer=1;
 8921:        my ($match,$cond)=&is_on_map($uri);
 8922:        if ($match) {
 8923:            $statecond=$cond;
 8924:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 8925:                =~/\Q$priv\E\&([^\:]*)/) {
 8926:                my $value = $1;
 8927:                if ($priv eq 'bre') {
 8928:                    my $deeplinkblock;
 8929:                    unless ($nodeeplinkcheck) {
 8930:                        $deeplinkblock = &deeplink_check($priv,$symb,$uri);
 8931:                    }
 8932:                    if ($deeplinkblock) {
 8933:                        $thisallowed = 'D';
 8934:                    } elsif ($noblockcheck) {
 8935:                        $thisallowed.=$value;
 8936:                    } else {
 8937:                        my @blockers = &has_comm_blocking($priv,$symb,$uri,$ignorecache);
 8938:                        if (@blockers > 0) {
 8939:                            $thisallowed = 'B';
 8940:                        } else {
 8941:                            $thisallowed.=$value;
 8942:                        }
 8943:                    }
 8944:                } else {
 8945:                    $thisallowed.=$value;
 8946:                }
 8947:                $checkreferer=0;
 8948:            }
 8949:        }
 8950: 
 8951:        if ($checkreferer) {
 8952: 	  my $refuri=$env{'httpref.'.$orguri};
 8953:             unless ($refuri) {
 8954:                 foreach my $key (keys(%env)) {
 8955: 		    if ($key=~/^httpref\..*\*/) {
 8956: 			my $pattern=$key;
 8957:                         $pattern=~s/^httpref\.\/res\///;
 8958:                         $pattern=~s/\*/\[\^\/\]\+/g;
 8959:                         $pattern=~s/\//\\\//g;
 8960:                         if ($orguri=~/$pattern/) {
 8961: 			    $refuri=$env{$key};
 8962:                         }
 8963:                     }
 8964:                 }
 8965:             }
 8966: 
 8967:          if ($refuri) { 
 8968: 	  $refuri=&declutter($refuri);
 8969:           my ($match,$cond)=&is_on_map($refuri);
 8970:             if ($match) {
 8971:               my $refstatecond=$cond;
 8972:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 8973:                   =~/\Q$priv\E\&([^\:]*)/) {
 8974:                   my $value = $1;
 8975:                   if ($priv eq 'bre') {
 8976:                       my $deeplinkblock;
 8977:                       unless ($nodeeplinkcheck) {
 8978:                           $deeplinkblock = &deeplink_check($priv,$symb,$refuri);
 8979:                       }
 8980:                       if ($deeplinkblock) {
 8981:                           $thisallowed = 'D';
 8982:                       } elsif ($noblockcheck) {
 8983:                           $thisallowed.=$value;
 8984:                       } else {
 8985:                           my @blockers = &has_comm_blocking($priv,'',$refuri,'',1);
 8986:                           if (@blockers > 0) {
 8987:                               $thisallowed = 'B';
 8988:                           } else {
 8989:                               $thisallowed.=$value;
 8990:                           }
 8991:                       }
 8992:                   } else {
 8993:                       $thisallowed.=$value;
 8994:                   }
 8995:                   $uri=$refuri;
 8996:                   $statecond=$refstatecond;
 8997:               }
 8998:           }
 8999:         }
 9000:        }
 9001:    }
 9002: 
 9003: #
 9004: # Gathered now: all privileges that could apply, and condition number
 9005: # 
 9006: #
 9007: # Full or no access?
 9008: #
 9009: 
 9010:     if ($thisallowed=~/F/) {
 9011: 	return 'F';
 9012:     }
 9013: 
 9014:     unless ($thisallowed) {
 9015:         return '';
 9016:     }
 9017: 
 9018: # Restrictions exist, deal with them
 9019: #
 9020: #   C:according to course preferences
 9021: #   R:according to resource settings
 9022: #   L:unless locked
 9023: #   X:according to user session state
 9024: #
 9025: 
 9026: # Possibly locked functionality, check all courses
 9027: # In roles.tab, L (unless locked) available for bre, pch, plc, pac and sma.
 9028: # Locks might take effect only after 10 minutes cache expiration for other
 9029: # courses, and 2 minutes for current course, in which user has st or ta role
 9030: # which is neither expired nor a future role (unless current course).
 9031: 
 9032:     my ($needlockcheck,$now,$crsonly);
 9033:     if ($thisallowed=~/L/) {
 9034:         $now = time;
 9035:         if ($priv eq 'bre') {
 9036:             if ($uri ne '') {
 9037:                 if ($orguri =~ m{^/+res/}) {
 9038:                     if ($uri =~ m{^lib/templates/}) {
 9039:                         if ($env{'request.course.id'}) {
 9040:                             $crsonly = 1;
 9041:                             $needlockcheck = 1;
 9042:                         }
 9043:                     } else {
 9044:                         $needlockcheck = 1;
 9045:                     }
 9046:                 } elsif ($env{'request.course.id'}) {
 9047:                     my ($crsdom,$crsnum) = split('_',$env{'request.course.id'});
 9048:                     if (($uri =~ m{^(adm|uploaded|public)/$crsdom/$crsnum/}) ||
 9049:                         ($uri =~ m{^adm/$match_domain/$match_username/\d+/(smppg|bulletinboard)$})) {
 9050:                         $crsonly = 1;
 9051:                     }
 9052:                     $needlockcheck = 1;
 9053:                 }
 9054:             }
 9055:         } elsif (($priv eq 'pch') || ($priv eq 'plc') || ($priv eq 'pac') || ($priv eq 'sma')) {
 9056:             $needlockcheck = 1;
 9057:         }
 9058:     }
 9059:     if ($needlockcheck) {
 9060:         foreach my $envkey (keys(%env)) {
 9061:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
 9062:                my $courseid=$2;
 9063:                my $roleid=$1.'.'.$2;
 9064:                $courseid=~s/^\///;
 9065:                unless ($env{'request.role'} eq $roleid) {
 9066:                    my ($start,$end) = split(/\./,$env{$envkey});
 9067:                    next unless (($now >= $start) && (!$end || $end > $now));
 9068:                }
 9069:                my $expiretime=600;
 9070:                if ($env{'request.role'} eq $roleid) {
 9071: 		  $expiretime=120;
 9072:                }
 9073: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
 9074:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
 9075:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
 9076: 		   &coursedescription($courseid,{'freshen_cache' => 1});
 9077:                }
 9078:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
 9079:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
 9080: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
 9081:                        &log($env{'user.domain'},$env{'user.name'},
 9082:                             $env{'user.home'},
 9083:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
 9084:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 9085:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 9086: 		       return '';
 9087:                    }
 9088:                }
 9089:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
 9090:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
 9091: 		   if ($env{$prefix.'priv.'.$priv.'.lock.expire'}>time) {
 9092:                        &log($env{'user.domain'},$env{'user.name'},
 9093:                             $env{'user.home'},
 9094:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
 9095:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 9096:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 9097: 		       return '';
 9098:                    }
 9099:                }
 9100: 	   }
 9101:        }
 9102:     }
 9103: 
 9104: #
 9105: # Rest of the restrictions depend on selected course
 9106: #
 9107: 
 9108:     unless ($env{'request.course.id'}) {
 9109: 	if ($thisallowed eq 'A') {
 9110: 	    return 'A';
 9111:         } elsif ($thisallowed eq 'B') {
 9112:             return 'B';
 9113: 	} else {
 9114: 	    return '1';
 9115: 	}
 9116:     }
 9117: 
 9118: #
 9119: # Now user is definitely in a course
 9120: #
 9121: 
 9122: 
 9123: # Course preferences
 9124: 
 9125:    if ($thisallowed=~/C/) {
 9126:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 9127:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
 9128:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
 9129: 	   =~/\Q$rolecode\E/) {
 9130: 	   if (($priv ne 'pch') && ($priv ne 'plc') && ($priv ne 'pac')) {
 9131: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 9132: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
 9133: 			$env{'request.course.id'});
 9134: 	   }
 9135:            return '';
 9136:        }
 9137: 
 9138:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
 9139: 	   =~/\Q$unamedom\E/) {
 9140: 	   if (($priv ne 'pch') && ($priv ne 'plc') && ($priv ne 'pac')) {
 9141: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
 9142: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
 9143: 			$env{'request.course.id'});
 9144: 	   }
 9145:            return '';
 9146:        }
 9147:    }
 9148: 
 9149: # Resource preferences
 9150: 
 9151:    if ($thisallowed=~/R/) {
 9152:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 9153:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
 9154: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
 9155: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 9156: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
 9157: 	   }
 9158: 	   return '';
 9159:        }
 9160:    }
 9161: 
 9162: # Restricted for deeplinked session?
 9163: 
 9164:     if ($env{'request.deeplink.login'}) {
 9165:         if ($env{'acc.deeplinkout'} && !$nodeeplinkout) {
 9166:             if (!$symb) { $symb=&symbread($uri,1); }
 9167:             if (($symb) && ($env{'acc.deeplinkout'}=~/\&\Q$symb\E\&/)) {
 9168:                 return '';
 9169:             }
 9170:         }
 9171:     }
 9172: 
 9173: # Restricted by state or randomout?
 9174: 
 9175:    if ($thisallowed=~/X/) {
 9176:       if ($env{'acc.randomout'}) {
 9177: 	 if (!$symb) { $symb=&symbread($uri,1); }
 9178:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
 9179:             return ''; 
 9180:          }
 9181:       }
 9182:       if (&condval($statecond)) {
 9183: 	 return '2';
 9184:       } else {
 9185:          return '';
 9186:       }
 9187:    }
 9188: 
 9189:     if ($thisallowed eq 'A') {
 9190: 	return 'A';
 9191:     } elsif ($thisallowed eq 'B') {
 9192:         return 'B';
 9193:     } elsif ($thisallowed eq 'D') {
 9194:         return 'D';
 9195:     }
 9196:    return 'F';
 9197: }
 9198: 
 9199: # ------------------------------------------- Check construction space access
 9200: 
 9201: sub constructaccess {
 9202:     my ($url,$setpriv)=@_;
 9203: 
 9204: # We do not allow editing of previous versions of files
 9205:     if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
 9206: 
 9207: # Get username and domain from URL
 9208:     my ($ownername,$ownerdomain,$ownerhome);
 9209: 
 9210:     ($ownerdomain,$ownername) =
 9211:         ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)(?:/daxepage|/daxeopen)?/priv/($match_domain)/($match_username)(?:/|$)});
 9212: 
 9213: # The URL does not really point to any authorspace, forget it
 9214:     unless (($ownername) && ($ownerdomain)) { return ''; }
 9215: 
 9216: # Now we need to see if the user has access to the authorspace of
 9217: # $ownername at $ownerdomain
 9218: 
 9219:     if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
 9220: # Real author for this?
 9221:        $ownerhome = $env{'user.home'};
 9222:        if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
 9223:           return ($ownername,$ownerdomain,$ownerhome);
 9224:        }
 9225:     } elsif (&is_course($ownerdomain,$ownername)) {
 9226: # Course Authoring Space?
 9227:         if ($env{'request.course.id'}) {
 9228:             if (($ownername eq $env{'course.'.$env{'request.course.id'}.'.num'}) &&
 9229:                 ($ownerdomain eq $env{'course.'.$env{'request.course.id'}.'.domain'})) {
 9230:                 if (&allowed('mdc',$env{'request.course.id'})) {
 9231:                     return if ($env{'course.'.$env{'request.course.id'}.'.internal.crsauthor'} eq '0');
 9232:                     unless ($env{'course.'.$env{'request.course.id'}.'.internal.crsauthor'}) {
 9233:                         my %domdefs = &get_domain_defaults($ownerdomain);
 9234:                         my $type = lc($env{'course.'.$env{'request.course.id'}.'.type'});
 9235:                         unless (($type eq 'community') || ($type eq 'placement')) {
 9236:                             $type = 'unofficial';
 9237:                             if ($env{'course.'.$env{'request.course.id'}.'internal.coursecode'} ne '') {
 9238:                                 $type = 'official';
 9239:                             } elsif ($env{'course.'.$env{'request.course.id'}.'internal.textbook'} ne '') {
 9240:                                 $type = 'textbook';
 9241:                             } else {
 9242:                                 $type = 'unofficial';
 9243:                             }
 9244:                         }
 9245:                         return if ($domdefs{$type.'crsauthor'} eq '0');
 9246:                     }
 9247:                     $ownerhome = $env{'course.'.$env{'request.course.id'}.'.home'};
 9248:                     return ($ownername,$ownerdomain,$ownerhome);
 9249:                 }
 9250:             }
 9251:         }
 9252:         return '';
 9253:     } else {
 9254: # Co-author for this?
 9255:         if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
 9256:             exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
 9257:             $ownerhome = &homeserver($ownername,$ownerdomain);
 9258:             return ($ownername,$ownerdomain,$ownerhome);
 9259:         }
 9260:     }
 9261: 
 9262: # We don't have any access right now. If we are not possibly going to do anything about this,
 9263: # we might as well leave
 9264:    unless ($setpriv) { return ''; }
 9265: 
 9266: # Backdoor access?
 9267:     my $allowed=&allowed('eco',$ownerdomain);
 9268: # Nope
 9269:     unless ($allowed) { return ''; }
 9270: # Looks like we may have access, but could be locked by the owner of the construction space
 9271:     if ($allowed eq 'U') {
 9272:         my %blocked=&get('environment',['domcoord.author'],
 9273:                          $ownerdomain,$ownername);
 9274: # Is blocked by owner
 9275:         if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
 9276:     }
 9277:     if (($allowed eq 'F') || ($allowed eq 'U')) {
 9278: # Grant temporary access
 9279:         my $then=$env{'user.login.time'};
 9280:         my $update=$env{'user.update.time'};
 9281:         if (!$update) { $update = $then; }
 9282:         my $refresh=$env{'user.refresh.time'};
 9283:         if (!$refresh) { $refresh = $update; }
 9284:         my $now = time;
 9285:         &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
 9286:                            $now,'ca','constructaccess');
 9287:         $ownerhome = &homeserver($ownername,$ownerdomain);
 9288:         return($ownername,$ownerdomain,$ownerhome);
 9289:     }
 9290: # No business here
 9291:     return '';
 9292: }
 9293: 
 9294: # ----------------------------------------------------------- Content Blocking
 9295: 
 9296: {
 9297: # Caches for faster Course Contents display where content blocking
 9298: # is in operation (i.e., interval param set) for timed quiz.
 9299: #
 9300: # User for whom data are being temporarily cached.
 9301: my $cacheduser='';
 9302: # Course for which data are being temporarily cached.
 9303: my $cachedcid='';
 9304: # Cached blockers for this user (a hash of blocking items). 
 9305: my %cachedblockers=();
 9306: # When the data were last cached.
 9307: my $cachedlast='';
 9308: 
 9309: sub load_all_blockers {
 9310:     my ($uname,$udom)=@_;
 9311:     if (($uname ne '') && ($udom ne '')) { 
 9312:         if (($cacheduser eq $uname.':'.$udom) &&
 9313:             ($cachedcid eq $env{'request.course.id'}) &&
 9314:             (abs($cachedlast-time)<5)) {
 9315:             return;
 9316:         }
 9317:     }
 9318:     $cachedlast=time;
 9319:     $cacheduser=$uname.':'.$udom;
 9320:     $cachedcid=$env{'request.course.id'};
 9321:     %cachedblockers = &get_commblock_resources();
 9322:     return;
 9323: }
 9324: 
 9325: sub get_comm_blocks {
 9326:     my ($cdom,$cnum) = @_;
 9327:     if ($cdom eq '' || $cnum eq '') {
 9328:         return unless ($env{'request.course.id'});
 9329:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 9330:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 9331:     }
 9332:     my %commblocks;
 9333:     my $hashid=$cdom.'_'.$cnum;
 9334:     my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
 9335:     if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
 9336:         %commblocks = %{$blocksref};
 9337:     } else {
 9338:         %commblocks = &dump('comm_block',$cdom,$cnum);
 9339:         my $cachetime = 600;
 9340:         &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
 9341:     }
 9342:     return %commblocks;
 9343: }
 9344: 
 9345: sub get_commblock_resources {
 9346:     my ($blocks) = @_;
 9347:     my %blockers = ();
 9348:     return %blockers unless ($env{'request.course.id'});
 9349:     my $courseurl = &courseid_to_courseurl($env{'request.course.id'});
 9350:     if ($env{'request.course.sec'}) {
 9351:         $courseurl .= '/'.$env{'request.course.sec'};
 9352:     }
 9353:     return %blockers if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseurl} =~/evb\&([^\:]*)/);
 9354:     my %commblocks;
 9355:     if (ref($blocks) eq 'HASH') {
 9356:         %commblocks = %{$blocks};
 9357:     } else {
 9358:         %commblocks = &get_comm_blocks();
 9359:     }
 9360:     return %blockers unless (keys(%commblocks) > 0); 
 9361:     my $navmap = Apache::lonnavmaps::navmap->new();
 9362:     return %blockers unless (ref($navmap));
 9363:     my $now = time;
 9364:     foreach my $block (keys(%commblocks)) {
 9365:         if ($block =~ /^(\d+)____(\d+)$/) {
 9366:             my ($start,$end) = ($1,$2);
 9367:             if ($start <= $now && $end >= $now) {
 9368:                 if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
 9369:                     if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
 9370:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
 9371:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
 9372:                                 $blockers{$block}{maps} = $commblocks{$block}{'blocks'}{'docs'}{'maps'}; 
 9373:                             }
 9374:                         }
 9375:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
 9376:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
 9377:                                 $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
 9378:                             }
 9379:                         }
 9380:                     }
 9381:                 }
 9382:             }
 9383:         } elsif ($block =~ /^firstaccess____(.+)$/) {
 9384:             my $item = $1;
 9385:             if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
 9386:                 if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
 9387:                     my (@interval,$mapname);
 9388:                     my $type = 'map';
 9389:                     if ($item eq 'course') {
 9390:                         $type = 'course';
 9391:                         @interval=&EXT("resource.0.interval");
 9392:                     } else {
 9393:                         if ($item =~ /___\d+___/) {
 9394:                             $type = 'resource';
 9395:                             @interval=&EXT("resource.0.interval",$item);
 9396:                         } else {
 9397:                             $mapname = &deversion($item);
 9398:                             if (ref($navmap)) {
 9399:                                 my $timelimit = $navmap->get_mapparam(undef,$mapname,'0.interval');
 9400:                                 @interval = ($timelimit,'map');
 9401:                             }
 9402:                         }
 9403:                     }
 9404:                     if ($interval[0] =~ /^(\d+)/) {
 9405:                         my $timelimit = $1; 
 9406:                         my $first_access;
 9407:                         if ($type eq 'resource') {
 9408:                             $first_access=&get_first_access($interval[1],$item);
 9409:                         } elsif ($type eq 'map') {
 9410:                             $first_access=&get_first_access($interval[1],undef,$item);
 9411:                         } else {
 9412:                             $first_access=&get_first_access($interval[1]);
 9413:                         }
 9414:                         if ($first_access) {
 9415:                             my $timesup = $first_access+$timelimit;
 9416:                             if ($timesup > $now) {
 9417:                                 my $activeblock;
 9418:                                 if ($type eq 'resource') {
 9419:                                     if (ref($navmap)) {
 9420:                                         my $res = $navmap->getBySymb($item);
 9421:                                         if ($res->answerable()) {
 9422:                                             $activeblock = 1;
 9423:                                         }
 9424:                                     }
 9425:                                 } elsif ($type eq 'map') {
 9426:                                     my $mapsymb = &symbread($mapname,1);
 9427:                                     if (($mapsymb) && (ref($navmap))) {
 9428:                                         my $mapres = $navmap->getBySymb($mapsymb);
 9429:                                         if (ref($mapres)) {
 9430:                                             my $first = $mapres->map_start();
 9431:                                             my $finish = $mapres->map_finish();
 9432:                                             my $it = $navmap->getIterator($first,$finish,undef,0,0);
 9433:                                             if (ref($it)) {
 9434:                                                 my $res;
 9435:                                                 while ($res = $it->next(undef,1)) {
 9436:                                                     next unless (ref($res));
 9437:                                                     my $symb = $res->symb();
 9438:                                                     next if (($symb eq $mapsymb) || ($symb eq ''));
 9439:                                                     @interval=&EXT("resource.0.interval",$symb);
 9440:                                                     if ($interval[1] eq 'map') {
 9441:                                                         if ($res->answerable()) {
 9442:                                                             $activeblock = 1;
 9443:                                                             last;
 9444:                                                         }
 9445:                                                     }
 9446:                                                 }
 9447:                                             }
 9448:                                         }
 9449:                                     }
 9450:                                 }
 9451:                                 if ($activeblock) {
 9452:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
 9453:                                          if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
 9454:                                              $blockers{$block}{'maps'} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
 9455:                                          }
 9456:                                     }
 9457:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
 9458:                                         if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
 9459:                                             $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
 9460:                                         }
 9461:                                     }
 9462:                                 }
 9463:                             }
 9464:                         }
 9465:                     }
 9466:                 }
 9467:             }
 9468:         }
 9469:     }
 9470:     return %blockers;
 9471: }
 9472: 
 9473: sub has_comm_blocking {
 9474:     my ($priv,$symb,$uri,$ignoresymbdb,$noenccheck,$blocked,$blocks) = @_;
 9475:     my @blockers;
 9476:     return unless ($env{'request.course.id'});
 9477:     return unless ($priv eq 'bre');
 9478:     return if ($env{'request.state'} eq 'construct');
 9479:     my $courseurl = &courseid_to_courseurl($env{'request.course.id'});
 9480:     if ($env{'request.course.sec'}) {
 9481:         $courseurl .= '/'.$env{'request.course.sec'};
 9482:     }
 9483:     return if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseurl} =~/evb\&([^\:]*)/);
 9484:     my %blockinfo;
 9485:     if (ref($blocks) eq 'HASH') {
 9486:         %blockinfo = &get_commblock_resources($blocks);
 9487:     } else {
 9488:         &load_all_blockers($env{'user.name'},$env{'user.domain'});
 9489:         %blockinfo = %cachedblockers;
 9490:     }
 9491:     return unless (keys(%blockinfo) > 0);
 9492:     my (%possibles,@symbs);
 9493:     if (!$symb) {
 9494:         $symb = &symbread($uri,1,1,1,\%possibles,$ignoresymbdb,$noenccheck);
 9495:     }
 9496:     if ($symb) {
 9497:         @symbs = ($symb);
 9498:     } elsif (keys(%possibles)) { 
 9499:         @symbs = keys(%possibles);
 9500:     }
 9501:     my $noblock;
 9502:     foreach my $symb (@symbs) {
 9503:         last if ($noblock);
 9504:         my ($map,$resid,$resurl)=&decode_symb($symb);
 9505:         foreach my $block (keys(%blockinfo)) {
 9506:             if ($block =~ /^firstaccess____(.+)$/) {
 9507:                 my $item = $1;
 9508:                 unless ($blocked) {
 9509:                     if (($item eq $map) || ($item eq $symb)) {
 9510:                         $noblock = 1;
 9511:                         last;
 9512:                     }
 9513:                 }
 9514:             }
 9515:             if (ref($blockinfo{$block}) eq 'HASH') {
 9516:                 if (ref($blockinfo{$block}{'resources'}) eq 'HASH') {
 9517:                     if ($blockinfo{$block}{'resources'}{$symb}) {
 9518:                         unless (grep(/^\Q$block\E$/,@blockers)) {
 9519:                             push(@blockers,$block);
 9520:                         }
 9521:                     }
 9522:                 }
 9523:                 if (ref($blockinfo{$block}{'maps'}) eq 'HASH') {
 9524:                     if ($blockinfo{$block}{'maps'}{$map}) {
 9525:                         unless (grep(/^\Q$block\E$/,@blockers)) {
 9526:                             push(@blockers,$block);
 9527:                         }
 9528:                     }
 9529:                 }
 9530:             }
 9531:         }
 9532:     }
 9533:     unless ($noblock) { 
 9534:         return @blockers;
 9535:     }
 9536:     return;
 9537: }
 9538: }
 9539: 
 9540: sub deeplink_check {
 9541:     my ($priv,$symb,$uri) = @_;
 9542:     return unless ($env{'request.course.id'});
 9543:     return unless ($priv eq 'bre');
 9544:     return if ($env{'request.state'} eq 'construct');
 9545:     return if ($env{'request.role.adv'});
 9546:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 9547:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 9548:     my (%possibles,@symbs);
 9549:     if (!$symb) {
 9550:         $symb = &symbread($uri,1,1,1,\%possibles);
 9551:     }
 9552:     if ($symb) {
 9553:         @symbs = ($symb);
 9554:     } elsif (keys(%possibles)) {
 9555:         @symbs = keys(%possibles);
 9556:     }
 9557: 
 9558:     my ($deeplink_symb,$allow);
 9559:     if ($env{'request.deeplink.login'}) {
 9560:         $deeplink_symb = &Apache::loncommon::deeplink_login_symb($cnum,$cdom);
 9561:     }
 9562:     foreach my $symb (@symbs) {
 9563:         last if ($allow);
 9564:         my $deeplink = &EXT("resource.0.deeplink",$symb);
 9565:         if ($deeplink eq '') {
 9566:             $allow = 1;
 9567:         } else {
 9568:             my ($state,$others,$listed,$scope,$protect) = split(/,/,$deeplink);
 9569:             if ($state ne 'only') {
 9570:                 $allow = 1;
 9571:             } else {
 9572:                 my $check_deeplink_entry;
 9573:                 if ($protect ne 'none') {
 9574:                     my ($acctype,$item) = split(/:/,$protect);
 9575:                     if (($acctype eq 'ltic') && ($env{'user.linkprotector'})) {
 9576:                         if (grep(/^\Q$item\Ec$/,split(/,/,$env{'user.linkprotector'}))) {
 9577:                             $check_deeplink_entry = 1
 9578:                         }
 9579:                     } elsif (($acctype eq 'ltid') && ($env{'user.linkprotector'})) {
 9580:                         if (grep(/^\Q$item\Ed$/,split(/,/,$env{'user.linkprotector'}))) {
 9581:                             $check_deeplink_entry = 1;
 9582:                         }
 9583:                     } elsif (($acctype eq 'key') && ($env{'user.deeplinkkey'})) {
 9584:                         if (grep(/^\Q$item\E$/,split(/,/,$env{'user.deeplinkkey'}))) {
 9585:                             $check_deeplink_entry = 1;
 9586:                         }
 9587:                     }
 9588:                 }
 9589:                 if (($protect eq 'none') || ($check_deeplink_entry)) {
 9590:                     if ($scope eq 'res') {
 9591:                         if ($symb eq $deeplink_symb) {
 9592:                             $allow = 1;
 9593:                         }
 9594:                     } elsif (($scope eq 'map') || ($scope eq 'rec')) {
 9595:                         my ($map_from_symb,$map_from_login);
 9596:                         $map_from_symb = &deversion((&decode_symb($symb))[0]);
 9597:                         if ($deeplink_symb =~ /\.(page|sequence)$/) {
 9598:                             $map_from_login = &deversion((&decode_symb($deeplink_symb))[2]);
 9599:                         } else {
 9600:                             $map_from_login = &deversion((&decode_symb($deeplink_symb))[0]);
 9601:                         }
 9602:                         if (($map_from_symb) && ($map_from_login)) {
 9603:                             if ($map_from_symb eq $map_from_login) {
 9604:                                 $allow = 1;
 9605:                             } elsif ($scope eq 'rec') {
 9606:                                 my @recurseup = &get_map_hierarchy($map_from_symb,$env{'request.course.id'});
 9607:                                 if (grep(/^\Q$map_from_login\E$/,@recurseup)) {
 9608:                                     $allow = 1;
 9609:                                 }
 9610:                             }
 9611:                         }
 9612:                     }
 9613:                 }
 9614:             }
 9615:         }
 9616:     }
 9617:     return if ($allow);
 9618:     return 1;
 9619: }
 9620: 
 9621: # -------------------------------- Deversion and split uri into path an filename   
 9622: 
 9623: #
 9624: #   Removes the version from a URI and
 9625: #   splits it in to its filename and path to the filename.
 9626: #   Seems like File::Basename could have done this more clearly.
 9627: #   Parameters:
 9628: #      $uri   - input URI
 9629: #   Returns:
 9630: #     Two element list consisting of 
 9631: #     $pathname  - the URI up to and excluding the trailing /
 9632: #     $filename  - The part of the URI following the last /
 9633: #  NOTE:
 9634: #    Another realization of this is simply:
 9635: #    use File::Basename;
 9636: #    ...
 9637: #    $uri = shift;
 9638: #    $filename = basename($uri);
 9639: #    $path     = dirname($uri);
 9640: #    return ($filename, $path);
 9641: #
 9642: #     The implementation below is probably faster however.
 9643: #
 9644: sub split_uri_for_cond {
 9645:     my $uri=&deversion(&declutter(shift));
 9646:     my @uriparts=split(/\//,$uri);
 9647:     my $filename=pop(@uriparts);
 9648:     my $pathname=join('/',@uriparts);
 9649:     return ($pathname,$filename);
 9650: }
 9651: # --------------------------------------------------- Is a resource on the map?
 9652: 
 9653: sub is_on_map {
 9654:     my ($pathname,$filename) = &split_uri_for_cond(shift);
 9655:     #Trying to find the conditional for the file
 9656:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
 9657: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
 9658:     if ($match) {
 9659: 	return (1,$1);
 9660:     } else {
 9661: 	return (0,0);
 9662:     }
 9663: }
 9664: 
 9665: # --------------------------------------------------------- Get symb from alias
 9666: 
 9667: sub get_symb_from_alias {
 9668:     my $symb=shift;
 9669:     my ($map,$resid,$url)=&decode_symb($symb);
 9670: # Already is a symb
 9671:     if ($url) { return $symb; }
 9672: # Must be an alias
 9673:     my $aliassymb='';
 9674:     my %bighash;
 9675:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 9676:                             &GDBM_READER(),0640)) {
 9677:         my $rid=$bighash{'mapalias_'.$symb};
 9678: 	if ($rid) {
 9679: 	    my ($mapid,$resid)=split(/\./,$rid);
 9680: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
 9681: 				    $resid,$bighash{'src_'.$rid});
 9682: 	}
 9683:         untie %bighash;
 9684:     }
 9685:     return $aliassymb;
 9686: }
 9687: 
 9688: # ----------------------------------------------------------------- Define Role
 9689: 
 9690: sub definerole {
 9691:   if (allowed('mcr','/')) {
 9692:     my ($rolename,$sysrole,$domrole,$courole,$uname,$udom)=@_;
 9693:     foreach my $role (split(':',$sysrole)) {
 9694: 	my ($crole,$cqual)=split(/\&/,$role);
 9695:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
 9696:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
 9697: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 9698:                return "refused:s:$crole&$cqual"; 
 9699:             }
 9700:         }
 9701:     }
 9702:     foreach my $role (split(':',$domrole)) {
 9703: 	my ($crole,$cqual)=split(/\&/,$role);
 9704:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
 9705:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
 9706: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
 9707:                return "refused:d:$crole&$cqual"; 
 9708:             }
 9709:         }
 9710:     }
 9711:     foreach my $role (split(':',$courole)) {
 9712: 	my ($crole,$cqual)=split(/\&/,$role);
 9713:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
 9714:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
 9715: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 9716:                return "refused:c:$crole&$cqual"; 
 9717:             }
 9718:         }
 9719:     }
 9720:     my $uhome;
 9721:     if (($uname ne '') && ($udom ne '')) {
 9722:         $uhome = &homeserver($uname,$udom);
 9723:         return $uhome if ($uhome eq 'no_host');
 9724:     } else {
 9725:         $uname = $env{'user.name'};
 9726:         $udom = $env{'user.domain'};
 9727:         $uhome = $env{'user.home'};
 9728:     }
 9729:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
 9730:                 "$udom:$uname:rolesdef_$rolename=".
 9731:                 escape($sysrole.'_'.$domrole.'_'.$courole);
 9732:     return reply($command,$uhome);
 9733:   } else {
 9734:     return 'refused';
 9735:   }
 9736: }
 9737: 
 9738: # ---------------- Make a metadata query against the network of library servers
 9739: 
 9740: sub metadata_query {
 9741:     my ($query,$custom,$customshow,$server_array,$domains_hash)=@_;
 9742:     my %rhash;
 9743:     my %libserv = &all_library();
 9744:     my @server_list = (defined($server_array) ? @$server_array
 9745:                                               : keys(%libserv) );
 9746:     for my $server (@server_list) {
 9747:         my $domains = ''; 
 9748:         if (ref($domains_hash) eq 'HASH') {
 9749:             $domains = $domains_hash->{$server}; 
 9750:         }
 9751: 	unless ($custom or $customshow) {
 9752: 	    my $reply=&reply("querysend:".&escape($query).':::'.&escape($domains),$server);
 9753: 	    $rhash{$server}=$reply;
 9754: 	}
 9755: 	else {
 9756: 	    my $reply=&reply("querysend:".&escape($query).':'.
 9757: 			     &escape($custom).':'.&escape($customshow).':'.&escape($domains),
 9758: 			     $server);
 9759: 	    $rhash{$server}=$reply;
 9760: 	}
 9761:     }
 9762:     return \%rhash;
 9763: }
 9764: 
 9765: # ----------------------------------------- Send log queries and wait for reply
 9766: 
 9767: sub log_query {
 9768:     my ($uname,$udom,$query,%filters)=@_;
 9769:     my $uhome=&homeserver($uname,$udom);
 9770:     if ($uhome eq 'no_host') { return 'error: no_host'; }
 9771:     my $uhost=&hostname($uhome);
 9772:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
 9773:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
 9774:                        $uhome);
 9775:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
 9776:     return get_query_reply($queryid);
 9777: }
 9778: 
 9779: # -------------------------- Update MySQL table for portfolio file
 9780: 
 9781: sub update_portfolio_table {
 9782:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
 9783:     if ($group ne '') {
 9784:         $file_name =~s /^\Q$group\E//;
 9785:     }
 9786:     my $homeserver = &homeserver($uname,$udom);
 9787:     my $queryid=
 9788:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
 9789:                ':'.&escape($file_name).':'.$action,$homeserver);
 9790:     my $reply = &get_query_reply($queryid);
 9791:     return $reply;
 9792: }
 9793: 
 9794: # -------------------------- Update MySQL allusers table
 9795: 
 9796: sub update_allusers_table {
 9797:     my ($uname,$udom,$names) = @_;
 9798:     my $homeserver = &homeserver($uname,$udom);
 9799:     my $queryid=
 9800:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
 9801:                'lastname='.&escape($names->{'lastname'}).'%%'.
 9802:                'firstname='.&escape($names->{'firstname'}).'%%'.
 9803:                'middlename='.&escape($names->{'middlename'}).'%%'.
 9804:                'generation='.&escape($names->{'generation'}).'%%'.
 9805:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
 9806:                'id='.&escape($names->{'id'}),$homeserver);
 9807:     return;
 9808: }
 9809: 
 9810: # ------- Request retrieval of institutional classlists for course(s)
 9811: 
 9812: sub fetch_enrollment_query {
 9813:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
 9814:     my ($homeserver,$sleep,$loopmax);
 9815:     my $maxtries = 1;
 9816:     if ($context eq 'automated') {
 9817:         $homeserver = $perlvar{'lonHostID'};
 9818:         $sleep = 2;
 9819:         $loopmax = 100;
 9820:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
 9821:     } else {
 9822:         $homeserver = &homeserver($cnum,$dom);
 9823:     }
 9824:     my $host=&hostname($homeserver);
 9825:     my $cmd = '';
 9826:     foreach my $affiliate (keys(%{$affiliatesref})) {
 9827:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
 9828:     }
 9829:     $cmd =~ s/%%$//;
 9830:     $cmd = &escape($cmd);
 9831:     my $query = 'fetchenrollment';
 9832:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
 9833:     unless ($queryid=~/^\Q$host\E\_/) { 
 9834:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
 9835:         return 'error: '.$queryid;
 9836:     }
 9837:     my $reply = &get_query_reply($queryid,$sleep,$loopmax);
 9838:     my $tries = 1;
 9839:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 9840:         $reply = &get_query_reply($queryid,$sleep,$loopmax);
 9841:         $tries ++;
 9842:     }
 9843:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 9844:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 9845:     } else {
 9846:         my @responses = split(/:/,$reply);
 9847:         if (grep { $_ eq $homeserver } &current_machine_ids()) {
 9848:             foreach my $line (@responses) {
 9849:                 my ($key,$value) = split(/=/,$line,2);
 9850:                 $$replyref{$key} = $value;
 9851:             }
 9852:         } else {
 9853:             my $pathname = LONCAPA::tempdir();
 9854:             foreach my $line (@responses) {
 9855:                 my ($key,$value) = split(/=/,$line);
 9856:                 $$replyref{$key} = $value;
 9857:                 if ($value > 0) {
 9858:                     foreach my $item (@{$$affiliatesref{$key}}) {
 9859:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
 9860:                         my $destname = $pathname.'/'.$filename;
 9861:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
 9862:                         if ($xml_classlist =~ /^error/) {
 9863:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
 9864:                         } else {
 9865:                             if ( open(FILE,">",$destname) ) {
 9866:                                 print FILE &unescape($xml_classlist);
 9867:                                 close(FILE);
 9868:                             } else {
 9869:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
 9870:                             }
 9871:                         }
 9872:                     }
 9873:                 }
 9874:             }
 9875:         }
 9876:         return 'ok';
 9877:     }
 9878:     return 'error';
 9879: }
 9880: 
 9881: sub get_query_reply {
 9882:     my ($queryid,$sleep,$loopmax) = @_;
 9883:     if (($sleep eq '') || ($sleep !~ /^\d+\.?\d*$/)) {
 9884:         $sleep = 0.2;
 9885:     }
 9886:     if (($loopmax eq '') || ($loopmax =~ /\D/)) {
 9887:         $loopmax = 100;
 9888:     }
 9889:     my $replyfile=LONCAPA::tempdir().$queryid;
 9890:     my $reply='';
 9891:     for (1..$loopmax) {
 9892: 	sleep($sleep);
 9893:         if (-e $replyfile.'.end') {
 9894: 	    if (open(my $fh,"<",$replyfile)) {
 9895: 		$reply = join('',<$fh>);
 9896: 		close($fh);
 9897: 	   } else { return 'error: reply_file_error'; }
 9898:            return &unescape($reply);
 9899: 	}
 9900:     }
 9901:     return 'timeout:'.$queryid;
 9902: }
 9903: 
 9904: sub courselog_query {
 9905: #
 9906: # possible filters:
 9907: # url: url or symb
 9908: # username
 9909: # domain
 9910: # action: view, submit, grade
 9911: # start: timestamp
 9912: # end: timestamp
 9913: #
 9914:     my (%filters)=@_;
 9915:     unless ($env{'request.course.id'}) { return 'no_course'; }
 9916:     if ($filters{'url'}) {
 9917: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
 9918:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
 9919:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
 9920:     }
 9921:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 9922:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 9923:     return &log_query($cname,$cdom,'courselog',%filters);
 9924: }
 9925: 
 9926: sub userlog_query {
 9927: #
 9928: # possible filters:
 9929: # action: log check role
 9930: # start: timestamp
 9931: # end: timestamp
 9932: #
 9933:     my ($uname,$udom,%filters)=@_;
 9934:     return &log_query($uname,$udom,'userlog',%filters);
 9935: }
 9936: 
 9937: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
 9938: 
 9939: sub auto_run {
 9940:     my ($cnum,$cdom) = @_;
 9941:     my $response = 0;
 9942:     my $settings;
 9943:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
 9944:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
 9945:         $settings = $domconfig{'autoenroll'};
 9946:         if ($settings->{'run'} eq '1') {
 9947:             $response = 1;
 9948:         }
 9949:     } else {
 9950:         my $homeserver;
 9951:         if (&is_course($cdom,$cnum)) {
 9952:             $homeserver = &homeserver($cnum,$cdom);
 9953:         } else {
 9954:             $homeserver = &domain($cdom,'primary');
 9955:         }
 9956:         if ($homeserver ne 'no_host') {
 9957:             $response = &reply('autorun:'.$cdom,$homeserver);
 9958:         }
 9959:     }
 9960:     return $response;
 9961: }
 9962: 
 9963: sub auto_get_sections {
 9964:     my ($cnum,$cdom,$inst_coursecode) = @_;
 9965:     my $homeserver;
 9966:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) { 
 9967:         $homeserver = &homeserver($cnum,$cdom);
 9968:     }
 9969:     if (!defined($homeserver)) { 
 9970:         if ($cdom =~ /^$match_domain$/) {
 9971:             $homeserver = &domain($cdom,'primary');
 9972:         }
 9973:     }
 9974:     my @secs;
 9975:     if (defined($homeserver)) {
 9976:         my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
 9977:         unless ($response eq 'refused') {
 9978:             @secs = split(/:/,$response);
 9979:         }
 9980:     }
 9981:     return @secs;
 9982: }
 9983: 
 9984: sub auto_new_course {
 9985:     my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
 9986:     my $homeserver = &homeserver($cnum,$cdom);
 9987:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
 9988:     return $response;
 9989: }
 9990: 
 9991: sub auto_validate_courseID {
 9992:     my ($cnum,$cdom,$inst_course_id) = @_;
 9993:     my $homeserver = &homeserver($cnum,$cdom);
 9994:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
 9995:     return $response;
 9996: }
 9997: 
 9998: sub auto_validate_instcode {
 9999:     my ($cnum,$cdom,$instcode,$owner) = @_;
10000:     my ($homeserver,$response);
10001:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
10002:         $homeserver = &homeserver($cnum,$cdom);
10003:     }
10004:     if (!defined($homeserver)) {
10005:         if ($cdom =~ /^$match_domain$/) {
10006:             $homeserver = &domain($cdom,'primary');
10007:         }
10008:     }
10009:     $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
10010:                         &escape($instcode).':'.&escape($owner),$homeserver));
10011:     my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
10012:     return ($outcome,$description,$defaultcredits);
10013: }
10014: 
10015: sub auto_validate_inst_crosslist {
10016:     my ($cnum,$cdom,$instcode,$inst_xlist,$coowner) = @_;
10017:     my ($homeserver,$response);
10018:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
10019:         $homeserver = &homeserver($cnum,$cdom);
10020:     }
10021:     if (!defined($homeserver)) {
10022:         if ($cdom =~ /^$match_domain$/) {
10023:             $homeserver = &domain($cdom,'primary');
10024:         }
10025:     }
10026:     unless (($homeserver eq '') || ($homeserver eq 'no_host')) {
10027:         $response=&reply('autovalidateinstcrosslist:'.$cdom.':'.
10028:                          &escape($instcode).':'.&escape($inst_xlist).':'.
10029:                          &escape($coowner),$homeserver);
10030:     }
10031:     return $response;
10032: }
10033: 
10034: sub auto_create_password {
10035:     my ($cnum,$cdom,$authparam,$udom) = @_;
10036:     my ($homeserver,$response);
10037:     my $create_passwd = 0;
10038:     my $authchk = '';
10039:     if ($udom =~ /^$match_domain$/) {
10040:         $homeserver = &domain($udom,'primary');
10041:     }
10042:     if ($homeserver eq '') {
10043:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
10044:             $homeserver = &homeserver($cnum,$cdom);
10045:         }
10046:     }
10047:     if ($homeserver eq '') {
10048:         $authchk = 'nodomain';
10049:     } else {
10050:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
10051:         if ($response eq 'refused') {
10052:             $authchk = 'refused';
10053:         } else {
10054:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
10055:         }
10056:     }
10057:     return ($authparam,$create_passwd,$authchk);
10058: }
10059: 
10060: sub auto_photo_permission {
10061:     my ($cnum,$cdom,$students) = @_;
10062:     my $homeserver = &homeserver($cnum,$cdom);
10063:     my ($outcome,$perm_reqd,$conditions) = 
10064: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
10065:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
10066: 	return (undef,undef);
10067:     }
10068:     return ($outcome,$perm_reqd,$conditions);
10069: }
10070: 
10071: sub auto_checkphotos {
10072:     my ($uname,$udom,$pid) = @_;
10073:     my $homeserver = &homeserver($uname,$udom);
10074:     my ($result,$resulttype);
10075:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
10076: 				   &escape($uname).':'.&escape($pid),
10077: 				   $homeserver));
10078:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
10079: 	return (undef,undef);
10080:     }
10081:     if ($outcome) {
10082:         ($result,$resulttype) = split(/:/,$outcome);
10083:     } 
10084:     return ($result,$resulttype);
10085: }
10086: 
10087: sub auto_photochoice {
10088:     my ($cnum,$cdom) = @_;
10089:     my $homeserver = &homeserver($cnum,$cdom);
10090:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
10091: 						       &escape($cdom),
10092: 						       $homeserver)));
10093:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
10094: 	return (undef,undef);
10095:     }
10096:     return ($update,$comment);
10097: }
10098: 
10099: sub auto_photoupdate {
10100:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
10101:     my $homeserver = &homeserver($cnum,$dom);
10102:     my $host=&hostname($homeserver);
10103:     my $cmd = '';
10104:     my $maxtries = 1;
10105:     foreach my $affiliate (keys(%{$affiliatesref})) {
10106:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
10107:     }
10108:     $cmd =~ s/%%$//;
10109:     $cmd = &escape($cmd);
10110:     my $query = 'institutionalphotos';
10111:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
10112:     unless ($queryid=~/^\Q$host\E\_/) {
10113:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
10114:         return 'error: '.$queryid;
10115:     }
10116:     my $reply = &get_query_reply($queryid);
10117:     my $tries = 1;
10118:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
10119:         $reply = &get_query_reply($queryid);
10120:         $tries ++;
10121:     }
10122:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
10123:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
10124:     } else {
10125:         my @responses = split(/:/,$reply);
10126:         my $outcome = shift(@responses); 
10127:         foreach my $item (@responses) {
10128:             my ($key,$value) = split(/=/,$item);
10129:             $$photo{$key} = $value;
10130:         }
10131:         return $outcome;
10132:     }
10133:     return 'error';
10134: }
10135: 
10136: sub auto_instcode_format {
10137:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
10138: 	$cat_order) = @_;
10139:     my $courses = '';
10140:     my @homeservers;
10141:     if ($caller eq 'global') {
10142: 	my %servers = &get_servers($codedom,'library');
10143: 	foreach my $tryserver (keys(%servers)) {
10144: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
10145: 		push(@homeservers,$tryserver);
10146: 	    }
10147:         }
10148:     } elsif ($caller eq 'requests') {
10149:         if ($codedom =~ /^$match_domain$/) {
10150:             my $chome = &domain($codedom,'primary');
10151:             unless ($chome eq 'no_host') {
10152:                 push(@homeservers,$chome);
10153:             }
10154:         }
10155:     } else {
10156:         push(@homeservers,&homeserver($caller,$codedom));
10157:     }
10158:     foreach my $code (keys(%{$instcodes})) {
10159:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
10160:     }
10161:     chop($courses);
10162:     my $ok_response = 0;
10163:     my $response;
10164:     while (@homeservers > 0 && $ok_response == 0) {
10165:         my $server = shift(@homeservers); 
10166:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
10167:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
10168:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
10169: 		split(/:/,$response);
10170:             %{$codes} = (%{$codes},&str2hash($codes_str));
10171:             push(@{$codetitles},&str2array($codetitles_str));
10172:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
10173:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
10174:             $ok_response = 1;
10175:         }
10176:     }
10177:     if ($ok_response) {
10178:         return 'ok';
10179:     } else {
10180:         return $response;
10181:     }
10182: }
10183: 
10184: sub auto_instcode_defaults {
10185:     my ($domain,$returnhash,$code_order) = @_;
10186:     my @homeservers;
10187: 
10188:     my %servers = &get_servers($domain,'library');
10189:     foreach my $tryserver (keys(%servers)) {
10190: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
10191: 	    push(@homeservers,$tryserver);
10192: 	}
10193:     }
10194: 
10195:     my $response;
10196:     foreach my $server (@homeservers) {
10197:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
10198:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
10199: 	
10200: 	foreach my $pair (split(/\&/,$response)) {
10201: 	    my ($name,$value)=split(/\=/,$pair);
10202: 	    if ($name eq 'code_order') {
10203: 		@{$code_order} = split(/\&/,&unescape($value));
10204: 	    } else {
10205: 		$returnhash->{&unescape($name)}=&unescape($value);
10206: 	    }
10207: 	}
10208: 	return 'ok';
10209:     }
10210: 
10211:     return $response;
10212: }
10213: 
10214: sub auto_possible_instcodes {
10215:     my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
10216:     unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') && 
10217:             (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
10218:         return;
10219:     }
10220:     my (@homeservers,$uhome);
10221:     if (defined(&domain($domain,'primary'))) {
10222:         $uhome=&domain($domain,'primary');
10223:         push(@homeservers,&domain($domain,'primary'));
10224:     } else {
10225:         my %servers = &get_servers($domain,'library');
10226:         foreach my $tryserver (keys(%servers)) {
10227:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
10228:                 push(@homeservers,$tryserver);
10229:             }
10230:         }
10231:     }
10232:     my $response;
10233:     foreach my $server (@homeservers) {
10234:         $response=&reply('autopossibleinstcodes:'.$domain,$server);
10235:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
10236:         my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) = 
10237:             split(':',$response);
10238:         @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
10239:         @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
10240:         foreach my $item (split('&',$cat_title)) {   
10241:             my ($name,$value)=split('=',$item);
10242:             $cat_titles->{&unescape($name)}=&thaw_unescape($value);
10243:         }
10244:         foreach my $item (split('&',$cat_order)) {
10245:             my ($name,$value)=split('=',$item);
10246:             $cat_orders->{&unescape($name)}=&thaw_unescape($value);
10247:         }
10248:         return 'ok';
10249:     }
10250:     return $response;
10251: }
10252: 
10253: sub auto_courserequest_checks {
10254:     my ($dom) = @_;
10255:     my ($homeserver,%validations);
10256:     if ($dom =~ /^$match_domain$/) {
10257:         $homeserver = &domain($dom,'primary');
10258:     }
10259:     unless ($homeserver eq 'no_host') {
10260:         my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
10261:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
10262:             my @items = split(/&/,$response);
10263:             foreach my $item (@items) {
10264:                 my ($key,$value) = split('=',$item);
10265:                 $validations{&unescape($key)} = &thaw_unescape($value);
10266:             }
10267:         }
10268:     }
10269:     return %validations; 
10270: }
10271: 
10272: sub auto_courserequest_validation {
10273:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist,$custominfo) = @_;
10274:     my ($homeserver,$response);
10275:     if ($dom =~ /^$match_domain$/) {
10276:         $homeserver = &domain($dom,'primary');
10277:     }
10278:     unless ($homeserver eq 'no_host') {
10279:         my $customdata;
10280:         if (ref($custominfo) eq 'HASH') {
10281:             $customdata = &freeze_escape($custominfo);
10282:         }
10283:         $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
10284:                                     ':'.&escape($crstype).':'.&escape($inststatuslist).
10285:                                     ':'.&escape($instcode).':'.&escape($instseclist).':'.
10286:                                     $customdata,$homeserver));
10287:     }
10288:     return $response;
10289: }
10290: 
10291: sub auto_validate_class_sec {
10292:     my ($cdom,$cnum,$owners,$inst_class) = @_;
10293:     my $homeserver = &homeserver($cnum,$cdom);
10294:     my $ownerlist;
10295:     if (ref($owners) eq 'ARRAY') {
10296:         $ownerlist = join(',',@{$owners});
10297:     } else {
10298:         $ownerlist = $owners;
10299:     }
10300:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
10301:                         &escape($ownerlist).':'.$cdom,$homeserver);
10302:     return $response;
10303: }
10304: 
10305: sub auto_instsec_reformat {
10306:     my ($cdom,$action,$instsecref) = @_;
10307:     return unless(($action eq 'clutter') || ($action eq 'declutter'));
10308:     my @homeservers;
10309:     if (defined(&domain($cdom,'primary'))) {
10310:         push(@homeservers,&domain($cdom,'primary'));
10311:     } else {
10312:         my %servers = &get_servers($cdom,'library');
10313:         foreach my $tryserver (keys(%servers)) {
10314:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
10315:                 push(@homeservers,$tryserver);
10316:             }
10317:         }
10318:     }
10319:     my $response;
10320:     my %reformatted = %{$instsecref};
10321:     foreach my $server (@homeservers) {
10322:         if (ref($instsecref) eq 'HASH') {
10323:             my $info = &freeze_escape($instsecref);
10324:             my $response=&reply('autoinstsecreformat:'.$cdom.':'.
10325:                                 $action.':'.$info,$server);
10326:             next if ($response =~ /(con_lost|error|no_such_host|refused|unknown_command)/);
10327:             my @items = split(/&/,$response);
10328:             foreach my $item (@items) {
10329:                 my ($key,$value) = split(/=/,$item);
10330:                 $reformatted{&unescape($key)} = &thaw_unescape($value);
10331:             }
10332:         }
10333:     }
10334:     return %reformatted;
10335: }
10336: 
10337: sub auto_validate_instclasses {
10338:     my ($cdom,$cnum,$owners,$classesref) = @_;
10339:     my ($homeserver,%validations);
10340:     $homeserver = &homeserver($cnum,$cdom);
10341:     unless ($homeserver eq 'no_host') {
10342:         my $ownerlist;
10343:         if (ref($owners) eq 'ARRAY') {
10344:             $ownerlist = join(',',@{$owners});
10345:         } else {
10346:             $ownerlist = $owners;
10347:         }
10348:         if (ref($classesref) eq 'HASH') {
10349:             my $classes = &freeze_escape($classesref);
10350:             my $response=&reply('autovalidateinstclasses:'.&escape($ownerlist).
10351:                                 ':'.$cdom.':'.$classes,$homeserver);
10352:             unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
10353:                 my @items = split(/&/,$response);
10354:                 foreach my $item (@items) {
10355:                     my ($key,$value) = split('=',$item);
10356:                     $validations{&unescape($key)} = &thaw_unescape($value);
10357:                 }
10358:             }
10359:         }
10360:     }
10361:     return %validations;
10362: }
10363: 
10364: sub auto_crsreq_update {
10365:     my ($cdom,$cnum,$crstype,$action,$ownername,$ownerdomain,$fullname,$title,
10366:         $code,$accessstart,$accessend,$inbound) = @_;
10367:     my ($homeserver,%crsreqresponse);
10368:     if ($cdom =~ /^$match_domain$/) {
10369:         $homeserver = &domain($cdom,'primary');
10370:     }
10371:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
10372:         my $info;
10373:         if (ref($inbound) eq 'HASH') {
10374:             $info = &freeze_escape($inbound);
10375:         }
10376:         my $response=&reply('autocrsrequpdate:'.$cdom.':'.$cnum.':'.&escape($crstype).
10377:                             ':'.&escape($action).':'.&escape($ownername).':'.
10378:                             &escape($ownerdomain).':'.&escape($fullname).':'.
10379:                             &escape($title).':'.&escape($code).':'.
10380:                             &escape($accessstart).':'.&escape($accessend).':'.$info,
10381:                             $homeserver);
10382:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
10383:             my @items = split(/&/,$response);
10384:             foreach my $item (@items) {
10385:                 my ($key,$value) = split('=',$item);
10386:                 $crsreqresponse{&unescape($key)} = &thaw_unescape($value);
10387:             }
10388:         }
10389:     }
10390:     return \%crsreqresponse;
10391: }
10392: 
10393: sub auto_export_grades {
10394:     my ($cdom,$cnum,$inforef,$gradesref) = @_;
10395:     my ($homeserver,%exportresponse);
10396:     if ($cdom =~ /^$match_domain$/) {
10397:         $homeserver = &domain($cdom,'primary');
10398:     }
10399:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
10400:         my $info;
10401:         if (ref($inforef) eq 'HASH') {
10402:             $info = &freeze_escape($inforef);
10403:         }
10404:         if (ref($gradesref) eq 'HASH') {
10405:             my $grades = &freeze_escape($gradesref);
10406:             my $response=&reply('encrypt:autoexportgrades:'.$cdom.':'.$cnum.':'.
10407:                                 $info.':'.$grades,$homeserver);
10408:             unless ($response =~ /(con_lost|error|no_such_host|refused|unknown_command)/) {
10409:                 my @items = split(/&/,$response);
10410:                 foreach my $item (@items) {
10411:                     my ($key,$value) = split('=',$item);
10412:                     $exportresponse{&unescape($key)} = &thaw_unescape($value);
10413:                 }
10414:             }
10415:         }
10416:     }
10417:     return \%exportresponse;
10418: }
10419: 
10420: sub check_instcode_cloning {
10421:     my ($codedefaults,$code_order,$cloner,$clonefromcode,$clonetocode) = @_;
10422:     unless ((ref($codedefaults) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
10423:         return;
10424:     }
10425:     my $canclone;
10426:     if (@{$code_order} > 0) {
10427:         my $instcoderegexp ='^';
10428:         my @clonecodes = split(/\&/,$cloner);
10429:         foreach my $item (@{$code_order}) {
10430:             if (grep(/^\Q$item\E=/,@clonecodes)) {
10431:                 foreach my $pair (@clonecodes) {
10432:                     my ($key,$val) = split(/\=/,$pair,2);
10433:                     $val = &unescape($val);
10434:                     if ($key eq $item) {
10435:                         $instcoderegexp .= '('.$val.')';
10436:                         last;
10437:                     }
10438:                 }
10439:             } else {
10440:                 $instcoderegexp .= $codedefaults->{$item};
10441:             }
10442:         }
10443:         $instcoderegexp .= '$';
10444:         my (@from,@to);
10445:         eval {
10446:                (@from) = ($clonefromcode =~ /$instcoderegexp/);
10447:                (@to) = ($clonetocode =~ /$instcoderegexp/);
10448:         };
10449:         if ((@from > 0) && (@to > 0)) {
10450:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
10451:             if (!@diffs) {
10452:                 $canclone = 1;
10453:             }
10454:         }
10455:     }
10456:     return $canclone;
10457: }
10458: 
10459: sub default_instcode_cloning {
10460:     my ($clonedom,$domdefclone,$clonefromcode,$clonetocode,$codedefaultsref,$codeorderref) = @_;
10461:     my (%codedefaults,@code_order,$canclone);
10462:     if ((ref($codedefaultsref) eq 'HASH') && (ref($codeorderref) eq 'ARRAY')) {
10463:         %codedefaults = %{$codedefaultsref};
10464:         @code_order = @{$codeorderref};
10465:     } elsif ($clonedom) {
10466:         &auto_instcode_defaults($clonedom,\%codedefaults,\@code_order);
10467:     }
10468:     if (($domdefclone) && (@code_order)) {
10469:         my @clonecodes = split(/\+/,$domdefclone);
10470:         my $instcoderegexp ='^';
10471:         foreach my $item (@code_order) {
10472:             if (grep(/^\Q$item\E$/,@clonecodes)) {
10473:                 $instcoderegexp .= '('.$codedefaults{$item}.')';
10474:             } else {
10475:                 $instcoderegexp .= $codedefaults{$item};
10476:             }
10477:         }
10478:         $instcoderegexp .= '$';
10479:         my (@from,@to);
10480:         eval {
10481:             (@from) = ($clonefromcode =~ /$instcoderegexp/);
10482:             (@to) = ($clonetocode =~ /$instcoderegexp/);
10483:         };
10484:         if ((@from > 0) && (@to > 0)) {
10485:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
10486:             if (!@diffs) {
10487:                 $canclone = 1;
10488:             }
10489:         }
10490:     }
10491:     return $canclone;
10492: }
10493: 
10494: # ------------------------------------------------------- Course Group routines
10495: 
10496: sub get_coursegroups {
10497:     my ($cdom,$cnum,$group,$namespace) = @_;
10498:     return(&dump($namespace,$cdom,$cnum,$group));
10499: }
10500: 
10501: sub modify_coursegroup {
10502:     my ($cdom,$cnum,$groupsettings) = @_;
10503:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
10504: }
10505: 
10506: sub toggle_coursegroup_status {
10507:     my ($cdom,$cnum,$group,$action) = @_;
10508:     my ($from_namespace,$to_namespace);
10509:     if ($action eq 'delete') {
10510:         $from_namespace = 'coursegroups';
10511:         $to_namespace = 'deleted_groups';
10512:     } else {
10513:         $from_namespace = 'deleted_groups';
10514:         $to_namespace = 'coursegroups';
10515:     }
10516:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
10517:     if (my $tmp = &error(%curr_group)) {
10518:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
10519:         return ('read error',$tmp);
10520:     } else {
10521:         my %savedsettings = %curr_group; 
10522:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
10523:         my $deloutcome;
10524:         if ($result eq 'ok') {
10525:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
10526:         } else {
10527:             return ('write error',$result);
10528:         }
10529:         if ($deloutcome eq 'ok') {
10530:             return 'ok';
10531:         } else {
10532:             return ('delete error',$deloutcome);
10533:         }
10534:     }
10535: }
10536: 
10537: sub modify_group_roles {
10538:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context,
10539:         $othdomby,$requester) = @_;
10540:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
10541:     my $role = 'gr/'.&escape($userprivs);
10542:     my ($uname,$udom) = split(/:/,$user);
10543:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context,
10544:                              $othdomby,$requester);
10545:     if ($result eq 'ok') {
10546:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
10547:     }
10548:     return $result;
10549: }
10550: 
10551: sub modify_coursegroup_membership {
10552:     my ($cdom,$cnum,$membership) = @_;
10553:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
10554:     return $result;
10555: }
10556: 
10557: sub get_active_groups {
10558:     my ($udom,$uname,$cdom,$cnum) = @_;
10559:     my $now = time;
10560:     my %groups = ();
10561:     foreach my $key (keys(%env)) {
10562:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
10563:             my ($start,$end) = split(/\./,$env{$key});
10564:             if (($end!=0) && ($end<$now)) { next; }
10565:             if (($start!=0) && ($start>$now)) { next; }
10566:             if ($1 eq $cdom && $2 eq $cnum) {
10567:                 $groups{$3} = $env{$key} ;
10568:             }
10569:         }
10570:     }
10571:     return %groups;
10572: }
10573: 
10574: sub get_group_membership {
10575:     my ($cdom,$cnum,$group) = @_;
10576:     return(&dump('groupmembership',$cdom,$cnum,$group));
10577: }
10578: 
10579: sub get_users_groups {
10580:     my ($udom,$uname,$courseid) = @_;
10581:     my @usersgroups;
10582:     my $cachetime=1800;
10583: 
10584:     my $hashid="$udom:$uname:$courseid";
10585:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
10586:     if (defined($cached)) {
10587:         @usersgroups = split(/:/,$grouplist);
10588:     } else {  
10589:         $grouplist = '';
10590:         my $courseurl = &courseid_to_courseurl($courseid);
10591:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
10592:         my $access_end = $env{'course.'.$courseid.
10593:                               '.default_enrollment_end_date'};
10594:         my $now = time;
10595:         foreach my $key (keys(%roleshash)) {
10596:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
10597:                 my $group = $1;
10598:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
10599:                     my $start = $2;
10600:                     my $end = $1;
10601:                     if ($start == -1) { next; } # deleted from group
10602:                     if (($start!=0) && ($start>$now)) { next; }
10603:                     if (($end!=0) && ($end<$now)) {
10604:                         if ($access_end && $access_end < $now) {
10605:                             if ($access_end - $end < 86400) {
10606:                                 push(@usersgroups,$group);
10607:                             }
10608:                         }
10609:                         next;
10610:                     }
10611:                     push(@usersgroups,$group);
10612:                 }
10613:             }
10614:         }
10615:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
10616:         $grouplist = join(':',@usersgroups);
10617:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
10618:     }
10619:     return @usersgroups;
10620: }
10621: 
10622: sub devalidate_getgroups_cache {
10623:     my ($udom,$uname,$cdom,$cnum)=@_;
10624:     my $courseid = $cdom.'_'.$cnum;
10625: 
10626:     my $hashid="$udom:$uname:$courseid";
10627:     &devalidate_cache_new('getgroups',$hashid);
10628: }
10629: 
10630: # ------------------------------------------------------------------ Plain Text
10631: 
10632: sub plaintext {
10633:     my ($short,$type,$cid,$forcedefault) = @_;
10634:     if ($short =~ m{^cr/}) {
10635: 	return (split('/',$short))[-1];
10636:     }
10637:     if (!defined($cid)) {
10638:         $cid = $env{'request.course.id'};
10639:     }
10640:     my %rolenames = (
10641:                       Course    => 'std',
10642:                       Community => 'alt1',
10643:                       Placement => 'std',
10644:                     );
10645:     if ($cid ne '') {
10646:         if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
10647:             unless ($forcedefault) {
10648:                 my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
10649:                 &Apache::lonlocal::mt_escape(\$roletext);
10650:                 return &Apache::lonlocal::mt($roletext);
10651:             }
10652:         }
10653:     }
10654:     if ((defined($type)) && (defined($rolenames{$type})) &&
10655:         (defined($rolenames{$type})) && 
10656:         (defined($prp{$short}{$rolenames{$type}}))) {
10657:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
10658:     } elsif ($cid ne '') {
10659:         my $crstype = $env{'course.'.$cid.'.type'};
10660:         if (($crstype ne '') && (defined($rolenames{$crstype})) &&
10661:             (defined($prp{$short}{$rolenames{$crstype}}))) {
10662:             return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
10663:         }
10664:     }
10665:     return &Apache::lonlocal::mt($prp{$short}{'std'});
10666: }
10667: 
10668: # ----------------------------------------------------------------- Assign Role
10669: 
10670: sub assignrole {
10671:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
10672:         $context,$othdomby,$requester,$reqsec,$reqrole)=@_;
10673:     my ($mrole,$rolelogcontext);
10674:     if ($role =~ /^cr\//) {
10675:         my $cwosec=$url;
10676:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
10677:         if ((!&allowed('ccr',$cwosec)) && (!&allowed('ccr',$udom))) {
10678:             my $refused = 1;
10679:             if ($context eq 'requestcourses') {
10680:                 if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
10681:                     if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
10682:                         if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
10683:                             my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
10684:                             my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
10685:                             if ($crsenv{'internal.courseowner'} eq
10686:                                 $env{'user.name'}.':'.$env{'user.domain'}) {
10687:                                 $refused = '';
10688:                             }
10689:                         }
10690:                     }
10691:                 }
10692:             } elsif (($context eq 'course') && ($othdomby eq 'othdombyuser')) {
10693:                 my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
10694:                 my ($sec) = ($url =~ m{^/\Q$cwosec\E/(.*)$});
10695:                 my $key = "$uname:$udom:$role:$sec";
10696:                 my %queuedrolereq = &Apache::lonnet::get('nohist_othdomqueued',[$key],$cdom,$cnum);
10697:                 if ((exists($queuedrolereq{$key})) && (ref($queuedrolereq{$key}) eq 'HASH')) {
10698:                     if (($queuedrolereq{$key}{'adj'} eq 'user') && ($queuedrolereq{$key}{'requester'} eq $requester)) {
10699:                         $refused = '';
10700:                     }
10701:                 }
10702:             }
10703:             if ($refused) {
10704:                 &logthis('Refused custom assignrole: '.
10705:                          $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
10706:                          ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
10707:                 return 'refused';
10708:             }
10709:         }
10710:         $mrole='cr';
10711:     } elsif ($role =~ /^gr\//) {
10712:         my $cwogrp=$url;
10713:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
10714:         if (!&allowed('mdg',$cwogrp)) {
10715:             my $refused = 1;
10716:             if (($refused) && ($othdomby eq 'othdombyuser') && ($requester ne '') && ($reqrole ne '')) {
10717:                 my ($cdom,$cnum) = ($cwogrp =~ m{^/?($match_domain)/($match_courseid)$});
10718:                 my $key = "$uname:$udom:$reqrole:$reqsec";
10719:                 my %queuedrolereq = &Apache::lonnet::get('nohist_othdomqueued',[$key],$cdom,$cnum);
10720:                 if ((exists($queuedrolereq{$key})) && (ref($queuedrolereq{$key}) eq 'HASH')) {
10721:                     if (($queuedrolereq{$key}{'adj'} eq 'user') && ($queuedrolereq{$key}{'requester'} eq $requester)) {
10722:                         $refused = '';
10723:                     }
10724:                 }
10725:             }
10726:             if ($refused) {
10727:                 &logthis('Refused group assignrole: '.
10728:                          $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
10729:                          $env{'user.name'}.' at '.$env{'user.domain'});
10730:                 return 'refused';
10731:             }
10732:         }
10733:         $mrole='gr';
10734:     } else {
10735:         my $cwosec=$url;
10736:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
10737:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
10738:             my $refused;
10739:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
10740:                 if (!(&allowed('c'.$role,$url))) {
10741:                     $refused = 1;
10742:                 }
10743:             } else {
10744:                 $refused = 1;
10745:             }
10746:             if ($refused) {
10747:                 my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
10748:                 if (!$selfenroll && ($othdomby ne 'othdombyuser') &&
10749:                    (($context eq 'course') || ($context eq 'ltienroll' && $env{'request.lti.login'}))) {
10750:                     my %crsenv;
10751:                     if ($role eq 'cc' || $role eq 'co') {
10752:                         %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
10753:                         if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
10754:                             if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
10755:                                 if ($crsenv{'internal.courseowner'} eq 
10756:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
10757:                                     $refused = '';
10758:                                 }
10759:                             }
10760:                         } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) { 
10761:                             if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
10762:                                 if ($crsenv{'internal.courseowner'} eq 
10763:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
10764:                                     $refused = '';
10765:                                 }
10766:                             }
10767:                         }
10768:                     }
10769:                 } elsif (($selfenroll == 1) && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
10770:                     if ($role eq 'st') {
10771:                         $refused = '';
10772:                     } elsif (($context eq 'ltienroll') && ($env{'request.lti.login'})) {
10773:                         $refused = '';
10774:                     }
10775:                 } elsif ($othdomby eq 'othdombyuser') {
10776:                     my ($key,%queuedrolereq);
10777:                     if ($context eq 'course') {
10778:                         my ($sec) = ($url =~ m{^/\Q$cwosec\E/(.*)$});
10779:                         $key = "$uname:$udom:$role:$sec";
10780:                         %queuedrolereq = &Apache::lonnet::get('nohist_othdomqueued',[$key],$cdom,$cnum);
10781:                         if ((exists($queuedrolereq{$key})) && (ref($queuedrolereq{$key}) eq 'HASH')) {
10782:                             if (($queuedrolereq{$key}{'adj'} eq 'user') && ($queuedrolereq{$key}{'requester'} eq $requester)) {
10783:                                 if ((($role eq 'cc') && ($cnum !~ /^$match_community$/)) || 
10784:                                     (($role eq 'co') && ($cnum =~ /^$match_community$/))) {
10785:                                     my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
10786:                                     if ($crsenv{'internal.courseowner'} eq $requester) {
10787:                                         $refused = '';
10788:                                     }
10789:                                 } elsif ($role =~ /^(?:in|ta|ep|st)$/) {
10790:                                     $refused = '';
10791:                                 }
10792:                             }
10793:                         }
10794:                     } elsif (($context eq 'author') && ($role =~ /^ca|aa$/)) {
10795:                         my $key = "$uname:$udom:$role"; 
10796:                         my ($audom,$auname) = ($url =~ m{^/($match_domain)/($match_username)$});
10797:                         if (($audom ne '') && ($auname ne '')) {
10798:                             my %queuedrolereq = &Apache::lonnet::get('nohist_othdomqueued',[$key],$audom,$auname);
10799:                             if ((exists($queuedrolereq{$key})) && (ref($queuedrolereq{$key}) eq 'HASH')) {
10800:                                 if (($queuedrolereq{$key}{'adj'} eq 'user') && ($queuedrolereq{$key}{'requester'} eq $requester)) {
10801:                                     $refused = '';
10802:                                 }
10803:                             }
10804:                         }
10805:                     } elsif (($context eq 'domain') && ($role ne 'dc') && ($role ne 'su')) {
10806:                         my $key = "$uname:$udom:$role";
10807:                         my ($roledom) = ($url =~ m{^/($match_domain)/\Q$role\E$});
10808:                         if ($roledom ne '') {
10809:                             my $confname = $roledom.'-domainconfig';
10810:                             my %queuedrolereq = &Apache::lonnet::get('nohist_othdomqueued',[$key],$roledom,$confname);
10811:                             if ((exists($queuedrolereq{$key})) && (ref($queuedrolereq{$key}) eq 'HASH')) {
10812:                                 if (($queuedrolereq{$key}{'adj'} eq 'user') && ($queuedrolereq{$key}{'requester'} eq $requester)) {
10813:                                     $refused = '';
10814:                                 }
10815:                             }
10816:                         }
10817:                     }
10818:                 } elsif ($context eq 'requestcourses') {
10819:                     my @possroles = ('st','ta','ep','in','cc','co');
10820:                     if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
10821:                         my $wrongcc;
10822:                         if ($cnum =~ /^$match_community$/) {
10823:                             $wrongcc = 1 if ($role eq 'cc');
10824:                         } else {
10825:                             $wrongcc = 1 if ($role eq 'co');
10826:                         }
10827:                         unless ($wrongcc) {
10828:                             my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
10829:                             if ($crsenv{'internal.courseowner'} eq 
10830:                                  $env{'user.name'}.':'.$env{'user.domain'}) {
10831:                                 $refused = '';
10832:                             }
10833:                         }
10834:                     }
10835:                 } elsif ($context eq 'requestauthor') {
10836:                     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) && 
10837:                         ($url eq '/'.$udom.'/') && ($role eq 'au')) {
10838:                         if ($env{'environment.requestauthor'} eq 'automatic') {
10839:                             $refused = '';
10840:                         } else {
10841:                             my %domdefaults = &get_domain_defaults($udom);
10842:                             if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
10843:                                 my $checkbystatus;
10844:                                 if ($env{'user.adv'}) { 
10845:                                     my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
10846:                                     if ($disposition eq 'automatic') {
10847:                                         $refused = '';
10848:                                     } elsif ($disposition eq '') {
10849:                                         $checkbystatus = 1;
10850:                                     } 
10851:                                 } else {
10852:                                     $checkbystatus = 1;
10853:                                 }
10854:                                 if ($checkbystatus) {
10855:                                     if ($env{'environment.inststatus'}) {
10856:                                         my @inststatuses = split(/,/,$env{'environment.inststatus'});
10857:                                         foreach my $type (@inststatuses) {
10858:                                             if (($type ne '') &&
10859:                                                 ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
10860:                                                 $refused = '';
10861:                                             }
10862:                                         }
10863:                                     } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
10864:                                         $refused = '';
10865:                                     }
10866:                                 }
10867:                             }
10868:                         }
10869:                     }
10870:                 } elsif (($context eq 'author') && (($role eq 'ca' || $role eq 'aa'))) {
10871:                     if ($url =~ m{^/($match_domain)/($match_username)$}) {
10872:                         my ($audom,$auname) = ($1,$2);
10873:                         if ((&Apache::lonnet::allowed('v'.$role,"$audom/$auname")) &&
10874:                             ($env{"environment.internal.manager.$url"})) {
10875:                             $refused = '';
10876:                             $rolelogcontext = 'coauthor';
10877:                         }
10878:                     }
10879:                 }
10880:                 if ($refused) {
10881:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
10882:                              ' '.$role.' '.$end.' '.$start.' by '.
10883: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
10884:                     return 'refused';
10885:                 }
10886:             }
10887:         } elsif ($role eq 'au') {
10888:             if ($url ne '/'.$udom.'/') {
10889:                 &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
10890:                          ' to assign author role for '.$uname.':'.$udom.
10891:                          ' in domain: '.$url.' refused (wrong domain).');
10892:                 return 'refused';
10893:             }
10894:         }
10895:         $mrole=$role;
10896:     }
10897:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
10898:                 "$udom:$uname:$url".'_'."$mrole=$role";
10899:     if ($end) { $command.='_'.$end; }
10900:     if ($start) {
10901: 	if ($end) { 
10902:            $command.='_'.$start; 
10903:         } else {
10904:            $command.='_0_'.$start;
10905:         }
10906:     }
10907:     my $origstart = $start;
10908:     my $origend = $end;
10909:     my $delflag;
10910: # actually delete
10911:     if ($deleteflag) {
10912: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
10913: # modify command to delete the role
10914:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
10915:                 "$udom:$uname:$url".'_'."$mrole";
10916: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
10917: # set start and finish to negative values for userrolelog
10918:            $start=-1;
10919:            $end=-1;
10920:            $delflag = 1;
10921:         }
10922:     }
10923: # send command
10924:     my $answer=&reply($command,&homeserver($uname,$udom));
10925: # log new user role if status is ok
10926:     if ($answer eq 'ok') {
10927: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
10928:         if (($role eq 'cc') || ($role eq 'in') ||
10929:             ($role eq 'ep') || ($role eq 'ad') ||
10930:             ($role eq 'ta') || ($role eq 'st') ||
10931:             ($role=~/^cr/) || ($role eq 'gr') ||
10932:             ($role eq 'co')) {
10933: # for course roles, perform group memberships changes triggered by role change.
10934:             unless ($role =~ /^gr/) {
10935:                 &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
10936:                                                  $origstart,$selfenroll,$context);
10937:             }
10938:             &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
10939:                            $selfenroll,$context,$othdomby,$requester);
10940:         } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
10941:                  ($role eq 'au') || ($role eq 'dc') || ($role eq 'dh') ||
10942:                  ($role eq 'da')) {
10943:             &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
10944:                            $context,$othdomby,$requester);
10945:         } elsif (($role eq 'ca') || ($role eq 'aa')) {
10946:             if ($rolelogcontext eq '') {
10947:                 $rolelogcontext = $context;
10948:             }
10949:             &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
10950:                              $rolelogcontext,$othdomby,$requester); 
10951:         }
10952:         if ($role eq 'cc') {
10953:             &autoupdate_coowners($url,$end,$start,$uname,$udom);
10954:         }
10955:     }
10956:     return $answer;
10957: }
10958: 
10959: sub autoupdate_coowners {
10960:     my ($url,$end,$start,$uname,$udom) = @_;
10961:     my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
10962:     if (($cdom ne '') && ($cnum ne '')) {
10963:         my $now = time;
10964:         my %domdesign = &Apache::loncommon::get_domainconf($cdom);
10965:         if ($domdesign{$cdom.'.autoassign.co-owners'}) {
10966:             my %coursehash = &coursedescription($cdom.'_'.$cnum);
10967:             my $instcode = $coursehash{'internal.coursecode'};
10968:             my $xlists = $coursehash{'internal.crosslistings'};
10969:             if ($instcode ne '') {
10970:                 if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
10971:                     unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
10972:                         my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
10973:                         my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
10974:                         unless ($result eq 'valid') {
10975:                             if ($xlists ne '') {
10976:                                 foreach my $xlist (split(',',$xlists)) {
10977:                                     my ($inst_crosslist,$lcsec) = split(':',$xlist);
10978:                                     $result =
10979:                                         &auto_validate_inst_crosslist($cnum,$cdom,$instcode,
10980:                                                                       $inst_crosslist,$uname.':'.$udom);
10981:                                     last if ($result eq 'valid');
10982:                                 }
10983:                             }
10984:                         }
10985:                         if ($result eq 'valid') {
10986:                             if ($coursehash{'internal.co-owners'}) {
10987:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
10988:                                     push(@newcoowners,$coowner);
10989:                                 }
10990:                                 unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
10991:                                     push(@newcoowners,$uname.':'.$udom);
10992:                                 }
10993:                                 @newcoowners = sort(@newcoowners);
10994:                             } else {
10995:                                 push(@newcoowners,$uname.':'.$udom);
10996:                             }
10997:                         } elsif ($coursehash{'internal.co-owners'}) {
10998:                             foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
10999:                                 unless ($coowner eq $uname.':'.$udom) {
11000:                                     push(@newcoowners,$coowner);
11001:                                 }
11002:                             }
11003:                             unless (@newcoowners > 0) {
11004:                                 $delcoowners = 1;
11005:                                 $coowners = '';
11006:                             }
11007:                         }
11008:                         if (@newcoowners || $delcoowners) {
11009:                             &store_coowners($cdom,$cnum,$coursehash{'home'},
11010:                                             $delcoowners,@newcoowners);
11011:                         }
11012:                     }
11013:                 }
11014:             }
11015:         }
11016:     }
11017: }
11018: 
11019: sub store_coowners {
11020:     my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
11021:     my $cid = $cdom.'_'.$cnum;
11022:     my ($coowners,$delresult,$putresult);
11023:     if (@newcoowners) {
11024:         $coowners = join(',',@newcoowners);
11025:         my %coownershash = (
11026:                             'internal.co-owners' => $coowners,
11027:                            );
11028:         $putresult = &put('environment',\%coownershash,$cdom,$cnum);
11029:         if ($putresult eq 'ok') {
11030:             if ($env{'course.'.$cid.'.num'} eq $cnum) {
11031:                 &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
11032:             }
11033:         }
11034:     }
11035:     if ($delcoowners) {
11036:         $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
11037:         if ($delresult eq 'ok') {
11038:             if ($env{'course.'.$cid.'.internal.co-owners'}) {
11039:                 &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
11040:             }
11041:         }
11042:     }
11043:     if (($putresult eq 'ok') || ($delresult eq 'ok')) {
11044:         my %crsinfo =
11045:             &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
11046:         if (ref($crsinfo{$cid}) eq 'HASH') {
11047:             $crsinfo{$cid}{'co-owners'} = \@newcoowners;
11048:             my $cidput = &courseidput($cdom,\%crsinfo,$chome,'notime');
11049:         }
11050:     }
11051: }
11052: 
11053: # -------------------------------------------------- Modify user authentication
11054: # Overrides without validation
11055: 
11056: sub modifyuserauth {
11057:     my ($udom,$uname,$umode,$upass)=@_;
11058:     my $uhome=&homeserver($uname,$udom);
11059:     my $allowed;
11060:     if (&allowed('mau',$udom)) {
11061:         $allowed = 1;
11062:     } elsif (($umode eq 'internal') && ($udom eq $env{'user.domain'}) &&
11063:              ($env{'request.course.id'}) && (&allowed('mip',$env{'request.course.id'})) &&
11064:              (!$env{'course.'.$env{'request.course.id'}.'.internal.nopasswdchg'})) {
11065:         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
11066:         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
11067:         if (($cdom ne '') && ($cnum ne '')) {
11068:             my $is_owner = &is_course_owner($cdom,$cnum);
11069:             if ($is_owner) {
11070:                 $allowed = 1;
11071:             }
11072:         }
11073:     }
11074:     unless ($allowed) { return 'refused'; }
11075:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
11076:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
11077:              ' in domain '.$env{'request.role.domain'});  
11078:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
11079: 		     &escape($upass),$uhome);
11080:     my $ip = &get_requestor_ip();
11081:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
11082:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
11083:          '(Remote '.$ip.'): '.$reply);
11084:     &log($udom,,$uname,$uhome,
11085:         'Authentication changed by '.$env{'user.domain'}.', '.
11086:                                      $env{'user.name'}.', '.$umode.
11087:          '(Remote '.$ip.'): '.$reply);
11088:     unless ($reply eq 'ok') {
11089:         &logthis('Authentication mode error: '.$reply);
11090: 	return 'error: '.$reply;
11091:     }   
11092:     return 'ok';
11093: }
11094: 
11095: # --------------------------------------------------------------- Modify a user
11096: 
11097: sub modifyuser {
11098:     my ($udom,    $uname, $uid,
11099:         $umode,   $upass, $first,
11100:         $middle,  $last,  $gene,
11101:         $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
11102:     $udom= &LONCAPA::clean_domain($udom);
11103:     $uname=&LONCAPA::clean_username($uname);
11104:     my $showcandelete = 'none';
11105:     if (ref($candelete) eq 'ARRAY') {
11106:         if (@{$candelete} > 0) {
11107:             $showcandelete = join(', ',@{$candelete});
11108:         }
11109:     }
11110:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
11111:              $umode.', '.$first.', '.$middle.', '.
11112: 	     $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
11113:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
11114:                                      ' desiredhome not specified'). 
11115:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
11116:              ' in domain '.$env{'request.role.domain'});
11117:     my $uhome=&homeserver($uname,$udom,'true');
11118:     my $newuser;
11119:     if ($uhome eq 'no_host') {
11120:         $newuser = 1;
11121:         unless (($umode && ($upass ne '')) || ($umode eq 'localauth') ||
11122:                 ($umode eq 'lti')) {
11123:             return 'error: more information needed to create new user';
11124:         }
11125:     }
11126: # ----------------------------------------------------------------- Create User
11127:     if (($uhome eq 'no_host') && 
11128: 	(($umode && $upass) || ($umode eq 'localauth') || ($umode eq 'lti'))) {
11129:         my $unhome='';
11130:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
11131:             $unhome = $desiredhome;
11132: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
11133: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
11134:         } else { # load balancing routine for determining $unhome
11135:             my $loadm=10000000;
11136: 	    my %servers = &get_servers($udom,'library');
11137: 	    foreach my $tryserver (keys(%servers)) {
11138: 		my $answer=reply('load',$tryserver);
11139: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
11140: 		    $loadm=$answer;
11141: 		    $unhome=$tryserver;
11142: 		}
11143: 	    }
11144:         }
11145:         if (($unhome eq '') || ($unhome eq 'no_host')) {
11146: 	    return 'error: unable to find a home server for '.$uname.
11147:                    ' in domain '.$udom;
11148:         }
11149:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
11150:                          &escape($upass),$unhome);
11151: 	unless ($reply eq 'ok') {
11152:             return 'error: '.$reply;
11153:         }   
11154:         $uhome=&homeserver($uname,$udom,'true');
11155:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
11156: 	    return 'error: unable verify users home machine.';
11157:         }
11158:     }   # End of creation of new user
11159: # ---------------------------------------------------------------------- Add ID
11160:     if ($uid) {
11161:        $uid=~tr/A-Z/a-z/;
11162:        my %uidhash=&idrget($udom,$uname);
11163:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
11164:          && (!$forceid)) {
11165: 	  unless ($uid eq $uidhash{$uname}) {
11166: 	      return 'error: user id "'.$uid.'" does not match '.
11167:                   'current user id "'.$uidhash{$uname}.'".';
11168:           }
11169:        } else {
11170: 	  &idput($udom,{$uname => $uid},$uhome,'ids');
11171:        }
11172:     }
11173: # -------------------------------------------------------------- Add names, etc
11174:     my @tmp=&get('environment',
11175: 		   ['firstname','middlename','lastname','generation','id',
11176:                     'permanentemail','inststatus'],
11177: 		   $udom,$uname);
11178:     my (%names,%oldnames);
11179:     if ($tmp[0] =~ m/^error:.*/) { 
11180:         %names=(); 
11181:     } else {
11182:         %names = @tmp;
11183:         %oldnames = %names;
11184:     }
11185: #
11186: # If name, email and/or uid are blank (e.g., because an uploaded file
11187: # of users did not contain them), do not overwrite existing values
11188: # unless field is in $candelete array ref.  
11189: #
11190: 
11191:     my @fields = ('firstname','middlename','lastname','generation',
11192:                   'permanentemail','id');
11193:     my %newvalues;
11194:     if (ref($candelete) eq 'ARRAY') {
11195:         foreach my $field (@fields) {
11196:             if (grep(/^\Q$field\E$/,@{$candelete})) {
11197:                 if ($field eq 'firstname') {
11198:                     $names{$field} = $first;
11199:                 } elsif ($field eq 'middlename') {
11200:                     $names{$field} = $middle;
11201:                 } elsif ($field eq 'lastname') {
11202:                     $names{$field} = $last;
11203:                 } elsif ($field eq 'generation') { 
11204:                     $names{$field} = $gene;
11205:                 } elsif ($field eq 'permanentemail') {
11206:                     $names{$field} = $email;
11207:                 } elsif ($field eq 'id') {
11208:                     $names{$field}  = $uid;
11209:                 }
11210:             }
11211:         }
11212:     }
11213:     if ($first)  { $names{'firstname'}  = $first; }
11214:     if (defined($middle)) { $names{'middlename'} = $middle; }
11215:     if ($last)   { $names{'lastname'}   = $last; }
11216:     if (defined($gene))   { $names{'generation'} = $gene; }
11217:     if ($email) {
11218:        $email=~s/[^\w\@\.\-\,]//gs;
11219:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
11220:     }
11221:     if ($uid) { $names{'id'}  = $uid; }
11222:     if (defined($inststatus)) {
11223:         $names{'inststatus'} = '';
11224:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
11225:         if (ref($usertypes) eq 'HASH') {
11226:             my @okstatuses; 
11227:             foreach my $item (split(/:/,$inststatus)) {
11228:                 if (defined($usertypes->{$item})) {
11229:                     push(@okstatuses,$item);  
11230:                 }
11231:             }
11232:             if (@okstatuses) {
11233:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
11234:             }
11235:         }
11236:     }
11237:     my $logmsg = $udom.', '.$uname.', '.$uid.', '.
11238:                  $umode.', '.$first.', '.$middle.', '.
11239:                  $last.', '.$gene.', '.$email.', '.$inststatus;
11240:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
11241:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
11242:     } else {
11243:         $logmsg .= ' during self creation';
11244:     }
11245:     my $changed;
11246:     if ($newuser) {
11247:         $changed = 1;
11248:     } else {
11249:         foreach my $field (@fields) {
11250:             if ($names{$field} ne $oldnames{$field}) {
11251:                 $changed = 1;
11252:                 last;
11253:             }
11254:         }
11255:     }
11256:     unless ($changed) {
11257:         $logmsg = 'No changes in user information needed for: '.$logmsg;
11258:         &logthis($logmsg);
11259:         return 'ok';
11260:     }
11261:     my $reply = &put('environment', \%names, $udom,$uname);
11262:     if ($reply ne 'ok') { 
11263:         return 'error: '.$reply;
11264:     }
11265:     if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
11266:         &devalidate_cache_new('emailscache',$uname.':'.$udom);
11267:     }
11268:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
11269:     &devalidate_cache_new('namescache',$uname.':'.$udom);
11270:     $logmsg = 'Success modifying user '.$logmsg;
11271:     &logthis($logmsg);
11272:     return 'ok';
11273: }
11274: 
11275: # -------------------------------------------------------------- Modify student
11276: 
11277: sub modifystudent {
11278:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
11279:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
11280:         $selfenroll,$context,$inststatus,$credits,$instsec)=@_;
11281:     if (!$cid) {
11282: 	unless ($cid=$env{'request.course.id'}) {
11283: 	    return 'not_in_class';
11284: 	}
11285:     }
11286: # --------------------------------------------------------------- Make the user
11287:     my $reply=&modifyuser
11288: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
11289:          $desiredhome,$email,$inststatus);
11290:     unless ($reply eq 'ok') { return $reply; }
11291:     # This will cause &modify_student_enrollment to get the uid from the
11292:     # student's environment
11293:     $uid = undef if (!$forceid);
11294:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
11295:                                         $gene,$usec,$end,$start,$type,$locktype,
11296:                                         $cid,$selfenroll,$context,$credits,$instsec);
11297:     return $reply;
11298: }
11299: 
11300: sub modify_student_enrollment {
11301:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,
11302:         $locktype,$cid,$selfenroll,$context,$credits,$instsec,$othdomby,$requester) = @_;
11303:     my ($cdom,$cnum,$chome);
11304:     if (!$cid) {
11305: 	unless ($cid=$env{'request.course.id'}) {
11306: 	    return 'not_in_class';
11307: 	}
11308: 	$cdom=$env{'course.'.$cid.'.domain'};
11309: 	$cnum=$env{'course.'.$cid.'.num'};
11310:     } else {
11311: 	($cdom,$cnum)=split(/_/,$cid);
11312:     }
11313:     $chome=$env{'course.'.$cid.'.home'};
11314:     if (!$chome) {
11315: 	$chome=&homeserver($cnum,$cdom);
11316:     }
11317:     if (!$chome) { return 'unknown_course'; }
11318:     # Make sure the user exists
11319:     my $uhome=&homeserver($uname,$udom);
11320:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
11321: 	return 'error: no such user';
11322:     }
11323:     # Get student data if we were not given enough information
11324:     if (!defined($first)  || $first  eq '' || 
11325:         !defined($last)   || $last   eq '' || 
11326:         !defined($uid)    || $uid    eq '' || 
11327:         !defined($middle) || $middle eq '' || 
11328:         !defined($gene)   || $gene   eq '') {
11329:         # They did not supply us with enough data to enroll the student, so
11330:         # we need to pick up more information.
11331:         my %tmp = &get('environment',
11332:                        ['firstname','middlename','lastname', 'generation','id']
11333:                        ,$udom,$uname);
11334: 
11335:         #foreach my $key (keys(%tmp)) {
11336:         #    &logthis("key $key = ".$tmp{$key});
11337:         #}
11338:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
11339:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
11340:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
11341:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
11342:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
11343:     }
11344:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
11345:     my $user = "$uname:$udom";
11346:     my %old_entry = &get('classlist',[$user],$cdom,$cnum);
11347:     my $reply=cput('classlist',
11348: 		   {$user => 
11349: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits,$instsec) },
11350: 		   $cdom,$cnum);
11351:     if (($reply eq 'ok') || ($reply eq 'delayed')) {
11352:         &devalidate_getsection_cache($udom,$uname,$cid);
11353:     } else { 
11354: 	return 'error: '.$reply;
11355:     }
11356:     # Add student role to user
11357:     my $uurl='/'.$cid;
11358:     $uurl=~s/\_/\//g;
11359:     if ($usec) {
11360: 	$uurl.='/'.$usec;
11361:     }
11362:     my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
11363:                              $selfenroll,$context,$othdomby,$requester);
11364:     if ($result ne 'ok') {
11365:         if ($old_entry{$user} ne '') {
11366:             $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
11367:         } else {
11368:             $reply = &del('classlist',[$user],$cdom,$cnum);
11369:         }
11370:     }
11371:     return $result; 
11372: }
11373: 
11374: sub format_name {
11375:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
11376:     my $name;
11377:     if ($first ne 'lastname') {
11378: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
11379:     } else {
11380: 	if ($lastname=~/\S/) {
11381: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
11382: 	    $name=~s/\s+,/,/;
11383: 	} else {
11384: 	    $name.= $firstname.' '.$middlename.' '.$generation;
11385: 	}
11386:     }
11387:     $name=~s/^\s+//;
11388:     $name=~s/\s+$//;
11389:     $name=~s/\s+/ /g;
11390:     return $name;
11391: }
11392: 
11393: # ------------------------------------------------- Write to course preferences
11394: 
11395: sub writecoursepref {
11396:     my ($courseid,%prefs)=@_;
11397:     $courseid=~s/^\///;
11398:     $courseid=~s/\_/\//g;
11399:     my ($cdomain,$cnum)=split(/\//,$courseid);
11400:     my $chome=homeserver($cnum,$cdomain);
11401:     if (($chome eq '') || ($chome eq 'no_host')) { 
11402: 	return 'error: no such course';
11403:     }
11404:     my $cstring='';
11405:     foreach my $pref (keys(%prefs)) {
11406: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
11407:     }
11408:     $cstring=~s/\&$//;
11409:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
11410: }
11411: 
11412: # ---------------------------------------------------------- Make/modify course
11413: 
11414: sub createcourse {
11415:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
11416:         $course_owner,$crstype,$cnum,$context,$category,$callercontext)=@_;
11417:     $url=&declutter($url);
11418:     my $cid='';
11419:     if ($context eq 'requestcourses') {
11420:         my $can_create = 0;
11421:         my ($ownername,$ownerdom) = split(':',$course_owner);
11422:         if ($udom eq $ownerdom) {
11423:             my $reload;
11424:             if (($callercontext eq 'auto') &&
11425:                ($ownerdom eq $env{'user.domain'}) && ($ownername eq $env{'user.name'})) {
11426:                 $reload = 'reload';
11427:             }
11428:             if (&usertools_access($ownername,$ownerdom,$category,$reload,
11429:                                   $context)) {
11430:                 $can_create = 1;
11431:             }
11432:         } else {
11433:             my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
11434:                                            $category);
11435:             if ($userenv{'reqcrsotherdom.'.$category} ne '') {
11436:                 my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
11437:                 if (@curr > 0) {
11438:                     my @options = qw(approval validate autolimit);
11439:                     my $optregex = join('|',@options);
11440:                     if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
11441:                         $can_create = 1;
11442:                     }
11443:                 }
11444:             }
11445:         }
11446:         if ($can_create) {
11447:             unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
11448:                 unless (&allowed('ccc',$udom)) {
11449:                     return 'refused'; 
11450:                 }
11451:             }
11452:         } else {
11453:             return 'refused';
11454:         }
11455:     } elsif (!&allowed('ccc',$udom)) {
11456:         return 'refused';
11457:     }
11458: # --------------------------------------------------------------- Get Unique ID
11459:     my $uname;
11460:     if ($cnum =~ /^$match_courseid$/) {
11461:         my $chome=&homeserver($cnum,$udom,'true');
11462:         if (($chome eq '') || ($chome eq 'no_host')) {
11463:             $uname = $cnum;
11464:         } else {
11465:             $uname = &generate_coursenum($udom,$crstype);
11466:         }
11467:     } else {
11468:         $uname = &generate_coursenum($udom,$crstype);
11469:     }
11470:     return $uname if ($uname =~ /^error/);
11471: # -------------------------------------------------- Check supplied server name
11472:     if (!defined($course_server)) {
11473:         if (defined(&domain($udom,'primary'))) {
11474:             $course_server = &domain($udom,'primary');
11475:         } else {
11476:             $course_server = $env{'user.home'}; 
11477:         }
11478:     }
11479:     my %host_servers =
11480:         &get_servers($udom,'library');
11481:     unless ($host_servers{$course_server}) {
11482:         return 'error: invalid home server for course: '.$course_server;
11483:     }
11484: # ------------------------------------------------------------- Make the course
11485:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
11486:                       $course_server);
11487:     unless ($reply eq 'ok') { return 'error: '.$reply; }
11488:     my $uhome=&homeserver($uname,$udom,'true');
11489:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
11490: 	return 'error: no such course';
11491:     }
11492: # ----------------------------------------------------------------- Course made
11493: # log existence
11494:     my $now = time;
11495:     my $newcourse = {
11496:                     $udom.'_'.$uname => {
11497:                                      description => $description,
11498:                                      inst_code   => $inst_code,
11499:                                      owner       => $course_owner,
11500:                                      type        => $crstype,
11501:                                      creator     => $env{'user.name'}.':'.
11502:                                                     $env{'user.domain'},
11503:                                      created     => $now,
11504:                                      context     => $context,
11505:                                                 },
11506:                     };
11507:     &courseidput($udom,$newcourse,$uhome,'notime');
11508: # set toplevel url
11509:     my $topurl=$url;
11510:     unless ($nonstandard) {
11511: # ------------------------------------------ For standard courses, make top url
11512:         my $mapurl=&clutter($url);
11513:         if ($mapurl eq '/res/') { $mapurl=''; }
11514:         $env{'form.initmap'}=(<<ENDINITMAP);
11515: <map>
11516: <resource id="1" type="start"></resource>
11517: <resource id="2" src="$mapurl"></resource>
11518: <resource id="3" type="finish"></resource>
11519: <link index="1" from="1" to="2"></link>
11520: <link index="2" from="2" to="3"></link>
11521: </map>
11522: ENDINITMAP
11523:         $topurl=&declutter(
11524:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
11525:                           );
11526:     }
11527: # ----------------------------------------------------------- Write preferences
11528:     &writecoursepref($udom.'_'.$uname,
11529:                      ('description'              => $description,
11530:                       'url'                      => $topurl,
11531:                       'internal.creator'         => $env{'user.name'}.':'.
11532:                                                     $env{'user.domain'},
11533:                       'internal.created'         => $now,
11534:                       'internal.creationcontext' => $context)
11535:                     );
11536:     return '/'.$udom.'/'.$uname;
11537: }
11538: 
11539: # ------------------------------------------------------------------- Create ID
11540: sub generate_coursenum {
11541:     my ($udom,$crstype) = @_;
11542:     my $domdesc = &domain($udom);
11543:     return 'error: invalid domain' if ($domdesc eq '');
11544:     my $first;
11545:     if ($crstype eq 'Community') {
11546:         $first = '0';
11547:     } else {
11548:         $first = int(1+rand(9)); 
11549:     } 
11550:     my $uname=$first.
11551:         ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
11552:         substr($$.time,0,5).unpack("H8",pack("I32",time)).
11553:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
11554: # ----------------------------------------------- Make sure that does not exist
11555:     my $uhome=&homeserver($uname,$udom,'true');
11556:     unless (($uhome eq '') || ($uhome eq 'no_host')) {
11557:         if ($crstype eq 'Community') {
11558:             $first = '0';
11559:         } else {
11560:             $first = int(1+rand(9));
11561:         }
11562:         $uname=$first.
11563:                ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
11564:                substr($$.time,0,5).unpack("H8",pack("I32",time)).
11565:                unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
11566:         $uhome=&homeserver($uname,$udom,'true');
11567:         unless (($uhome eq '') || ($uhome eq 'no_host')) {
11568:             return 'error: unable to generate unique course-ID';
11569:         }
11570:     }
11571:     return $uname;
11572: }
11573: 
11574: sub is_course {
11575:     my ($cdom, $cnum) = scalar(@_) == 1 ? 
11576:          ($_[0] =~ /^($match_domain)_($match_courseid)$/)  :  @_;
11577: 
11578:     return unless (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/));
11579:     my $uhome=&homeserver($cnum,$cdom);
11580:     my $iscourse;
11581:     if (grep { $_ eq $uhome } current_machine_ids()) {
11582:         $iscourse = &LONCAPA::Lond::is_course($cdom,$cnum);
11583:     } else {
11584:         my $hashid = $cdom.':'.$cnum;
11585:         ($iscourse,my $cached) = &is_cached_new('iscourse',$hashid);
11586:         unless (defined($cached)) {
11587:             my %courses = &courseiddump($cdom, '.', 1, '.', '.',
11588:                                         $cnum,undef,undef,'.');
11589:             $iscourse = 0;
11590:             if (exists($courses{$cdom.'_'.$cnum})) {
11591:                 $iscourse = 1;
11592:             }
11593:             &do_cache_new('iscourse',$hashid,$iscourse,3600);
11594:         }
11595:     }
11596:     return unless ($iscourse);
11597:     return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
11598: }
11599: 
11600: sub store_userdata {
11601:     my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
11602:     my $result;
11603:     if ($datakey ne '') {
11604:         if (ref($storehash) eq 'HASH') {
11605:             if ($udom eq '' || $uname eq '') {
11606:                 $udom = $env{'user.domain'};
11607:                 $uname = $env{'user.name'};
11608:             }
11609:             my $uhome=&homeserver($uname,$udom);
11610:             if (($uhome eq '') || ($uhome eq 'no_host')) {
11611:                 $result = 'error: no_host';
11612:             } else {
11613:                 $storehash->{'ip'} = &get_requestor_ip();
11614:                 $storehash->{'host'} = $perlvar{'lonHostID'};
11615: 
11616:                 my $namevalue='';
11617:                 foreach my $key (keys(%{$storehash})) {
11618:                     $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
11619:                 }
11620:                 $namevalue=~s/\&$//;
11621:                 unless ($namespace eq 'courserequests') {
11622:                     $datakey = &escape($datakey);
11623:                 }
11624:                 $result =  &reply("store:$udom:$uname:$namespace:$datakey:".
11625:                                   $namevalue,$uhome);
11626:             }
11627:         } else {
11628:             $result = 'error: data to store was not a hash reference'; 
11629:         }
11630:     } else {
11631:         $result= 'error: invalid requestkey'; 
11632:     }
11633:     return $result;
11634: }
11635: 
11636: # ---------------------------------------------------------- Assign Custom Role
11637: 
11638: sub assigncustomrole {
11639:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,
11640:         $selfenroll,$context,$othdomby,$requester)=@_;
11641:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
11642:                        $end,$start,$deleteflag,$selfenroll,$context,$othdomby,
11643:                        $requester);
11644: }
11645: 
11646: # ----------------------------------------------------------------- Revoke Role
11647: 
11648: sub revokerole {
11649:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
11650:     my $now=time;
11651:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
11652: }
11653: 
11654: # ---------------------------------------------------------- Revoke Custom Role
11655: 
11656: sub revokecustomrole {
11657:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
11658:     my $now=time;
11659:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
11660:            $deleteflag,$selfenroll,$context);
11661: }
11662: 
11663: # ------------------------------------------------------------ Disk usage
11664: sub diskusage {
11665:     my ($udom,$uname,$directorypath,$getpropath)=@_;
11666:     $directorypath =~ s/\/$//;
11667:     my $listing=&reply('du2:'.&escape($directorypath).':'
11668:                        .&escape($getpropath).':'.&escape($uname).':'
11669:                        .&escape($udom),homeserver($uname,$udom));
11670:     if ($listing eq 'unknown_cmd') {
11671:         if ($getpropath) {
11672:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
11673:         }
11674:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
11675:     }
11676:     return $listing;
11677: }
11678: 
11679: sub is_locked {
11680:     my ($file_name, $domain, $user, $which) = @_;
11681:     my @check;
11682:     my $is_locked;
11683:     push (@check,$file_name);
11684:     my %locked = &get('file_permissions',\@check,
11685: 		      $env{'user.domain'},$env{'user.name'});
11686:     my ($tmp)=keys(%locked);
11687:     if ($tmp=~/^error:/) { undef(%locked); }
11688:     
11689:     if (ref($locked{$file_name}) eq 'ARRAY') {
11690:         $is_locked = 'false';
11691:         foreach my $entry (@{$locked{$file_name}}) {
11692:            if (ref($entry) eq 'ARRAY') {
11693:                $is_locked = 'true';
11694:                if (ref($which) eq 'ARRAY') {
11695:                    push(@{$which},$entry);
11696:                } else {
11697:                    last;
11698:                }
11699:            }
11700:        }
11701:     } else {
11702:         $is_locked = 'false';
11703:     }
11704:     return $is_locked;
11705: }
11706: 
11707: sub declutter_portfile {
11708:     my ($file) = @_;
11709:     $file =~ s{^(/portfolio/|portfolio/)}{/};
11710:     return $file;
11711: }
11712: 
11713: # ------------------------------------------------------------- Mark as Read Only
11714: 
11715: sub mark_as_readonly {
11716:     my ($domain,$user,$files,$what) = @_;
11717:     my %current_permissions = &dump('file_permissions',$domain,$user);
11718:     my ($tmp)=keys(%current_permissions);
11719:     if ($tmp=~/^error:/) { undef(%current_permissions); }
11720:     foreach my $file (@{$files}) {
11721: 	$file = &declutter_portfile($file);
11722:         push(@{$current_permissions{$file}},$what);
11723:     }
11724:     &put('file_permissions',\%current_permissions,$domain,$user);
11725:     return;
11726: }
11727: 
11728: # ------------------------------------------------------------Save Selected Files
11729: 
11730: sub save_selected_files {
11731:     my ($user, $path, @files) = @_;
11732:     my $filename = $user."savedfiles";
11733:     my @other_files = &files_not_in_path($user, $path);
11734:     open (OUT,'>',LONCAPA::tempdir().$filename);
11735:     foreach my $file (@files) {
11736:         print (OUT $env{'form.currentpath'}.$file."\n");
11737:     }
11738:     foreach my $file (@other_files) {
11739:         print (OUT $file."\n");
11740:     }
11741:     close (OUT);
11742:     return 'ok';
11743: }
11744: 
11745: sub clear_selected_files {
11746:     my ($user) = @_;
11747:     my $filename = $user."savedfiles";
11748:     open (OUT,'>',LONCAPA::tempdir().$filename);
11749:     print (OUT undef);
11750:     close (OUT);
11751:     return ("ok");    
11752: }
11753: 
11754: sub files_in_path {
11755:     my ($user, $path) = @_;
11756:     my $filename = $user."savedfiles";
11757:     my %return_files;
11758:     open (IN,'<',LONCAPA::tempdir().$filename);
11759:     while (my $line_in = <IN>) {
11760:         chomp ($line_in);
11761:         my @paths_and_file = split (m!/!, $line_in);
11762:         my $file_part = pop (@paths_and_file);
11763:         my $path_part = join ('/', @paths_and_file);
11764:         $path_part.='/';
11765:         my $path_and_file = $path_part.$file_part;
11766:         if ($path_part eq $path) {
11767:             $return_files{$file_part}= 'selected';
11768:         }
11769:     }
11770:     close (IN);
11771:     return (\%return_files);
11772: }
11773: 
11774: # called in portfolio select mode, to show files selected NOT in current directory
11775: sub files_not_in_path {
11776:     my ($user, $path) = @_;
11777:     my $filename = $user."savedfiles";
11778:     my @return_files;
11779:     my $path_part;
11780:     open(IN, '<',LONCAPA::tempdir().$filename);
11781:     while (my $line = <IN>) {
11782:         #ok, I know it's clunky, but I want it to work
11783:         my @paths_and_file = split(m|/|, $line);
11784:         my $file_part = pop(@paths_and_file);
11785:         chomp($file_part);
11786:         my $path_part = join('/', @paths_and_file);
11787:         $path_part .= '/';
11788:         my $path_and_file = $path_part.$file_part;
11789:         if ($path_part ne $path) {
11790:             push(@return_files, ($path_and_file));
11791:         }
11792:     }
11793:     close(OUT);
11794:     return (@return_files);
11795: }
11796: 
11797: #------------------------------Submitted/Handedback Portfolio Files Versioning
11798:  
11799: sub portfiles_versioning {
11800:     my ($symb,$domain,$stu_name,$portfiles,$versioned_portfiles) = @_;
11801:     my $portfolio_root = '/userfiles/portfolio';
11802:     return unless ((ref($portfiles) eq 'ARRAY') && (ref($versioned_portfiles) eq 'ARRAY'));
11803:     foreach my $file (@{$portfiles}) {
11804:         &unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
11805:         my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
11806:         my ($answer_name,$answer_ver,$answer_ext) = &file_name_version_ext($answer_file);
11807:         my $getpropath = 1;
11808:         my ($dir_list,$listerror) = &dirlist($portfolio_root.$directory,$domain,
11809:                                              $stu_name,$getpropath);
11810:         my $version = &get_next_version($answer_name,$answer_ext,$dir_list);
11811:         my $new_answer = 
11812:             &version_selected_portfile($domain,$stu_name,$directory,$answer_file,$version);
11813:         if ($new_answer ne 'problem getting file') {
11814:             push(@{$versioned_portfiles}, $directory.$new_answer);
11815:             &mark_as_readonly($domain,$stu_name,[$directory.$new_answer],
11816:                               [$symb,$env{'request.course.id'},'graded']);
11817:         }
11818:     }
11819: }
11820: 
11821: sub get_next_version {
11822:     my ($answer_name, $answer_ext, $dir_list) = @_;
11823:     my $version;
11824:     if (ref($dir_list) eq 'ARRAY') {
11825:         foreach my $row (@{$dir_list}) {
11826:             my ($file) = split(/\&/,$row,2);
11827:             my ($file_name,$file_version,$file_ext) =
11828:                 &file_name_version_ext($file);
11829:             if (($file_name eq $answer_name) &&
11830:                 ($file_ext eq $answer_ext)) {
11831:                      # gets here if filename and extension match,
11832:                      # regardless of version
11833:                 if ($file_version ne '') {
11834:                     # a versioned file is found  so save it for later
11835:                     if ($file_version > $version) {
11836:                         $version = $file_version;
11837:                     }
11838:                 }
11839:             }
11840:         }
11841:     }
11842:     $version ++;
11843:     return($version);
11844: }
11845: 
11846: sub version_selected_portfile {
11847:     my ($domain,$stu_name,$directory,$file_name,$version) = @_;
11848:     my ($answer_name,$answer_ver,$answer_ext) =
11849:         &file_name_version_ext($file_name);
11850:     my $new_answer;
11851:     $env{'form.copy'} =
11852:         &getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
11853:     if($env{'form.copy'} eq '-1') {
11854:         $new_answer = 'problem getting file';
11855:     } else {
11856:         $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
11857:         my $copy_result = 
11858:             &finishuserfileupload($stu_name,$domain,'copy',
11859:                                   '/portfolio'.$directory.$new_answer);
11860:     }
11861:     undef($env{'form.copy'});
11862:     return ($new_answer);
11863: }
11864: 
11865: sub file_name_version_ext {
11866:     my ($file)=@_;
11867:     my @file_parts = split(/\./, $file);
11868:     my ($name,$version,$ext);
11869:     if (@file_parts > 1) {
11870:         $ext=pop(@file_parts);
11871:         if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
11872:             $version=pop(@file_parts);
11873:         }
11874:         $name=join('.',@file_parts);
11875:     } else {
11876:         $name=join('.',@file_parts);
11877:     }
11878:     return($name,$version,$ext);
11879: }
11880: 
11881: #----------------------------------------------Get portfolio file permissions
11882: 
11883: sub get_portfile_permissions {
11884:     my ($domain,$user) = @_;
11885:     my %current_permissions = &dump('file_permissions',$domain,$user);
11886:     my ($tmp)=keys(%current_permissions);
11887:     if ($tmp=~/^error:/) { undef(%current_permissions); }
11888:     return \%current_permissions;
11889: }
11890: 
11891: #---------------------------------------------Get portfolio file access controls
11892: 
11893: sub get_access_controls {
11894:     my ($current_permissions,$group,$file) = @_;
11895:     my %access;
11896:     my $real_file = $file;
11897:     $file =~ s/\.meta$//;
11898:     if (defined($file)) {
11899:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
11900:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
11901:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
11902:             }
11903:         }
11904:     } else {
11905:         foreach my $key (keys(%{$current_permissions})) {
11906:             if ($key =~ /\0accesscontrol$/) {
11907:                 if (defined($group)) {
11908:                     if ($key !~ m-^\Q$group\E/-) {
11909:                         next;
11910:                     }
11911:                 }
11912:                 my ($fullpath) = split(/\0/,$key);
11913:                 if (ref($$current_permissions{$key}) eq 'HASH') {
11914:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
11915:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
11916:                     }
11917:                 }
11918:             }
11919:         }
11920:     }
11921:     return %access;
11922: }
11923: 
11924: sub modify_access_controls {
11925:     my ($file_name,$changes,$domain,$user)=@_;
11926:     my ($outcome,$deloutcome);
11927:     my %store_permissions;
11928:     my %new_values;
11929:     my %new_control;
11930:     my %translation;
11931:     my @deletions = ();
11932:     my $now = time;
11933:     if (exists($$changes{'activate'})) {
11934:         if (ref($$changes{'activate'}) eq 'HASH') {
11935:             my @newitems = sort(keys(%{$$changes{'activate'}}));
11936:             my $numnew = scalar(@newitems);
11937:             for (my $i=0; $i<$numnew; $i++) {
11938:                 my $newkey = $newitems[$i];
11939:                 my $newid = &Apache::loncommon::get_cgi_id();
11940:                 if ($newkey =~ /^\d+:/) { 
11941:                     $newkey =~ s/^(\d+)/$newid/;
11942:                     $translation{$1} = $newid;
11943:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
11944:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
11945:                     $translation{$1} = $newid;
11946:                 }
11947:                 $new_values{$file_name."\0".$newkey} = 
11948:                                           $$changes{'activate'}{$newitems[$i]};
11949:                 $new_control{$newkey} = $now;
11950:             }
11951:         }
11952:     }
11953:     my %todelete;
11954:     my %changed_items;
11955:     foreach my $action ('delete','update') {
11956:         if (exists($$changes{$action})) {
11957:             if (ref($$changes{$action}) eq 'HASH') {
11958:                 foreach my $key (keys(%{$$changes{$action}})) {
11959:                     my ($itemnum) = ($key =~ /^([^:]+):/);
11960:                     if ($action eq 'delete') { 
11961:                         $todelete{$itemnum} = 1;
11962:                     } else {
11963:                         $changed_items{$itemnum} = $key;
11964:                     }
11965:                 }
11966:             }
11967:         }
11968:     }
11969:     # get lock on access controls for file.
11970:     my $lockhash = {
11971:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
11972:                                                        ':'.$env{'user.domain'},
11973:                    }; 
11974:     my $tries = 0;
11975:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
11976:    
11977:     while (($gotlock ne 'ok') && $tries < 10) {
11978:         $tries ++;
11979:         sleep(0.1);
11980:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
11981:     }
11982:     if ($gotlock eq 'ok') {
11983:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
11984:         my ($tmp)=keys(%curr_permissions);
11985:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
11986:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
11987:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
11988:             if (ref($curr_controls) eq 'HASH') {
11989:                 foreach my $control_item (keys(%{$curr_controls})) {
11990:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
11991:                     if (defined($todelete{$itemnum})) {
11992:                         push(@deletions,$file_name."\0".$control_item);
11993:                     } else {
11994:                         if (defined($changed_items{$itemnum})) {
11995:                             $new_control{$changed_items{$itemnum}} = $now;
11996:                             push(@deletions,$file_name."\0".$control_item);
11997:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
11998:                         } else {
11999:                             $new_control{$control_item} = $$curr_controls{$control_item};
12000:                         }
12001:                     }
12002:                 }
12003:             }
12004:         }
12005:         my ($group);
12006:         if (&is_course($domain,$user)) {
12007:             ($group,my $file) = split(/\//,$file_name,2);
12008:         }
12009:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
12010:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
12011:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
12012:         #  remove lock
12013:         my @del_lock = ($file_name."\0".'locked_access_records');
12014:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
12015:         my $sqlresult =
12016:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
12017:                                     $group);
12018:     } else {
12019:         $outcome = "error: could not obtain lockfile\n";  
12020:     }
12021:     return ($outcome,$deloutcome,\%new_values,\%translation);
12022: }
12023: 
12024: sub make_public_indefinitely {
12025:     my (@requrl) = @_;
12026:     return &automated_portfile_access('public',\@requrl);
12027: }
12028: 
12029: sub automated_portfile_access {
12030:     my ($accesstype,$addsref,$delsref,$info) = @_;
12031:     unless (($accesstype eq 'public') || ($accesstype eq 'ip')) {
12032:         return 'invalid';
12033:     }
12034:     my %urls;
12035:     if (ref($addsref) eq 'ARRAY') {
12036:         foreach my $requrl (@{$addsref}) {
12037:             if (&is_portfolio_url($requrl)) {
12038:                 unless (exists($urls{$requrl})) {
12039:                     $urls{$requrl} = 'add';
12040:                 }
12041:             }
12042:         }
12043:     }
12044:     if (ref($delsref) eq 'ARRAY') {
12045:         foreach my $requrl (@{$delsref}) { 
12046:             if (&is_portfolio_url($requrl)) {
12047:                 unless (exists($urls{$requrl})) {
12048:                     $urls{$requrl} = 'delete'; 
12049:                 }
12050:             }
12051:         }
12052:     }
12053:     unless (keys(%urls)) {
12054:         return 'invalid';
12055:     }
12056:     my $ip;
12057:     if ($accesstype eq 'ip') {
12058:         if (ref($info) eq 'HASH') {
12059:             if ($info->{'ip'} ne '') {
12060:                 $ip = $info->{'ip'};
12061:             }
12062:         }
12063:         if ($ip eq '') {
12064:             return 'invalid';
12065:         }
12066:     }
12067:     my $errors;
12068:     my $now = time;
12069:     my %current_perms;
12070:     foreach my $requrl (sort(keys(%urls))) {
12071:         my $action;
12072:         if ($urls{$requrl} eq 'add') {
12073:             $action = 'activate';
12074:         } else {
12075:             $action = 'none';
12076:         }
12077:         my $aclnum = 0;
12078:         my (undef,$udom,$unum,$file_name,$group) =
12079:             &parse_portfolio_url($requrl);
12080:         unless (exists($current_perms{$unum.':'.$udom})) {
12081:             $current_perms{$unum.':'.$udom} = &get_portfile_permissions($udom,$unum);
12082:         }
12083:         my %access_controls = &get_access_controls($current_perms{$unum.':'.$udom},
12084:                                                    $group,$file_name);
12085:         foreach my $key (keys(%{$access_controls{$file_name}})) {
12086:             my ($num,$scope,$end,$start) = 
12087:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
12088:             if ($scope eq $accesstype) {
12089:                 if (($start <= $now) && ($end == 0)) {
12090:                     if ($accesstype eq 'ip') {
12091:                         if (ref($access_controls{$file_name}{$key}) eq 'HASH') {
12092:                             if (ref($access_controls{$file_name}{$key}{'ip'}) eq 'ARRAY') {
12093:                                 if (grep(/^\Q$ip\E$/,@{$access_controls{$file_name}{$key}{'ip'}})) {
12094:                                     if ($urls{$requrl} eq 'add') {
12095:                                         $action = 'none';
12096:                                         last;
12097:                                     } else {
12098:                                         $action = 'delete';
12099:                                         $aclnum = $num;
12100:                                         last;
12101:                                     }
12102:                                 }
12103:                             }
12104:                         }
12105:                     } elsif ($accesstype eq 'public') {
12106:                         if ($urls{$requrl} eq 'add') {
12107:                             $action = 'none';
12108:                             last;
12109:                         } else {
12110:                             $action = 'delete';
12111:                             $aclnum = $num;
12112:                             last;
12113:                         }
12114:                     }
12115:                 } elsif ($accesstype eq 'public') {
12116:                     $action = 'update';
12117:                     $aclnum = $num;
12118:                     last;
12119:                 }
12120:             }
12121:         }
12122:         if ($action eq 'none') {
12123:             next;
12124:         } else {
12125:             my %changes;
12126:             my $newend = 0;
12127:             my $newstart = $now;
12128:             my $newkey = $aclnum.':'.$accesstype.'_'.$newend.'_'.$newstart;
12129:             $changes{$action}{$newkey} = {
12130:                 type => $accesstype,
12131:                 time => {
12132:                     start => $newstart,
12133:                     end   => $newend,
12134:                 },
12135:             };
12136:             if ($accesstype eq 'ip') {
12137:                 $changes{$action}{$newkey}{'ip'} = [$ip];
12138:             }
12139:             my ($outcome,$deloutcome,$new_values,$translation) =
12140:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
12141:             unless ($outcome eq 'ok') {
12142:                 $errors .= $outcome.' ';
12143:             }
12144:         }
12145:     }
12146:     if ($errors) {
12147:         $errors =~ s/\s$//;
12148:         return $errors;
12149:     } else {
12150:         return 'ok';
12151:     }
12152: }
12153: 
12154: #------------------------------------------------------Get Marked as Read Only
12155: 
12156: sub get_marked_as_readonly {
12157:     my ($domain,$user,$what,$group) = @_;
12158:     my $current_permissions = &get_portfile_permissions($domain,$user);
12159:     my @readonly_files;
12160:     my $cmp1=$what;
12161:     if (ref($what)) { $cmp1=join('',@{$what}) };
12162:     while (my ($file_name,$value) = each(%{$current_permissions})) {
12163:         if (defined($group)) {
12164:             if ($file_name !~ m-^\Q$group\E/-) {
12165:                 next;
12166:             }
12167:         }
12168:         if (ref($value) eq "ARRAY"){
12169:             foreach my $stored_what (@{$value}) {
12170:                 my $cmp2=$stored_what;
12171:                 if (ref($stored_what) eq 'ARRAY') {
12172:                     $cmp2=join('',@{$stored_what});
12173:                 }
12174:                 if ($cmp1 eq $cmp2) {
12175:                     push(@readonly_files, $file_name);
12176:                     last;
12177:                 } elsif (!defined($what)) {
12178:                     push(@readonly_files, $file_name);
12179:                     last;
12180:                 }
12181:             }
12182:         }
12183:     }
12184:     return @readonly_files;
12185: }
12186: #-----------------------------------------------------------Get Marked as Read Only Hash
12187: 
12188: sub get_marked_as_readonly_hash {
12189:     my ($current_permissions,$group,$what) = @_;
12190:     my %readonly_files;
12191:     while (my ($file_name,$value) = each(%{$current_permissions})) {
12192:         if (defined($group)) {
12193:             if ($file_name !~ m-^\Q$group\E/-) {
12194:                 next;
12195:             }
12196:         }
12197:         if (ref($value) eq "ARRAY"){
12198:             foreach my $stored_what (@{$value}) {
12199:                 if (ref($stored_what) eq 'ARRAY') {
12200:                     foreach my $lock_descriptor(@{$stored_what}) {
12201:                         if ($lock_descriptor eq 'graded') {
12202:                             $readonly_files{$file_name} = 'graded';
12203:                         } elsif ($lock_descriptor eq 'handback') {
12204:                             $readonly_files{$file_name} = 'handback';
12205:                         } else {
12206:                             if (!exists($readonly_files{$file_name})) {
12207:                                 $readonly_files{$file_name} = 'locked';
12208:                             }
12209:                         }
12210:                     }
12211:                 } 
12212:             }
12213:         } 
12214:     }
12215:     return %readonly_files;
12216: }
12217: # ------------------------------------------------------------ Unmark as Read Only
12218: 
12219: sub unmark_as_readonly {
12220:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
12221:     # for portfolio submissions, $what contains [$symb,$crsid] 
12222:     my ($domain,$user,$what,$file_name,$group) = @_;
12223:     $file_name = &declutter_portfile($file_name);
12224:     my $symb_crs = $what;
12225:     if (ref($what)) { $symb_crs=join('',@$what); }
12226:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
12227:     my ($tmp)=keys(%current_permissions);
12228:     if ($tmp=~/^error:/) { undef(%current_permissions); }
12229:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
12230:     foreach my $file (@readonly_files) {
12231: 	my $clean_file = &declutter_portfile($file);
12232: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
12233: 	my $current_locks = $current_permissions{$file};
12234:         my @new_locks;
12235:         my @del_keys;
12236:         if (ref($current_locks) eq "ARRAY"){
12237:             foreach my $locker (@{$current_locks}) {
12238:                 my $compare=$locker;
12239:                 if (ref($locker) eq 'ARRAY') {
12240:                     $compare=join('',@{$locker});
12241:                     if ($compare ne $symb_crs) {
12242:                         push(@new_locks, $locker);
12243:                     }
12244:                 }
12245:             }
12246:             if (scalar(@new_locks) > 0) {
12247:                 $current_permissions{$file} = \@new_locks;
12248:             } else {
12249:                 push(@del_keys, $file);
12250:                 &del('file_permissions',\@del_keys, $domain, $user);
12251:                 delete($current_permissions{$file});
12252:             }
12253:         }
12254:     }
12255:     &put('file_permissions',\%current_permissions,$domain,$user);
12256:     return;
12257: }
12258: 
12259: # ------------------------------------------------------------ Directory lister
12260: 
12261: sub dirlist {
12262:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
12263:     $uri=~s/^\///;
12264:     $uri=~s/\/$//;
12265:     my ($udom, $uname);
12266:     if ($getuserdir) {
12267:         $udom = $userdomain;
12268:         $uname = $username;
12269:     } else {
12270:         (undef,$udom,$uname)=split(/\//,$uri);
12271:         if(defined($userdomain)) {
12272:             $udom = $userdomain;
12273:         }
12274:         if(defined($username)) {
12275:             $uname = $username;
12276:         }
12277:     }
12278:     my ($dirRoot,$listing,@listing_results);
12279: 
12280:     $dirRoot = $perlvar{'lonDocRoot'};
12281:     if (defined($getpropath)) {
12282:         $dirRoot = &propath($udom,$uname);
12283:         $dirRoot =~ s/\/$//;
12284:     } elsif (defined($getuserdir)) {
12285:         my $subdir=$uname.'__';
12286:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
12287:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
12288:                    ."/$udom/$subdir/$uname";
12289:     } elsif (defined($alternateRoot)) {
12290:         $dirRoot = $alternateRoot;
12291:     }
12292: 
12293:     if($udom) {
12294:         if($uname) {
12295:             my $uhome = &homeserver($uname,$udom);
12296:             if ($uhome eq 'no_host') {
12297:                 return ([],'no_host');
12298:             }
12299:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
12300:                               .$getuserdir.':'.&escape($dirRoot)
12301:                               .':'.&escape($uname).':'.&escape($udom),$uhome);
12302:             if ($listing eq 'unknown_cmd') {
12303:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
12304:             } else {
12305:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
12306:             }
12307:             if ($listing eq 'unknown_cmd') {
12308:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
12309:                 @listing_results = split(/:/,$listing);
12310:             } else {
12311:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
12312:             }
12313:             if (($listing eq 'no_such_host') || ($listing eq 'con_lost') || 
12314:                 ($listing eq 'rejected') || ($listing eq 'refused') ||
12315:                 ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
12316:                 return ([],$listing);
12317:             } else {
12318:                 return (\@listing_results);
12319:             }
12320:         } elsif(!$alternateRoot) {
12321:             my (%allusers,%listerror);
12322: 	    my %servers = &get_servers($udom,'library');
12323:  	    foreach my $tryserver (keys(%servers)) {
12324:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
12325:                                   &escape($udom),$tryserver);
12326:                 if ($listing eq 'unknown_cmd') {
12327: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
12328: 				      $udom, $tryserver);
12329:                 } else {
12330:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
12331:                 }
12332: 		if ($listing eq 'unknown_cmd') {
12333: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
12334: 				      $udom, $tryserver);
12335: 		    @listing_results = split(/:/,$listing);
12336: 		} else {
12337: 		    @listing_results =
12338: 			map { &unescape($_); } split(/:/,$listing);
12339: 		}
12340:                 if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
12341:                     ($listing eq 'rejected') || ($listing eq 'refused') ||
12342:                     ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
12343:                     $listerror{$tryserver} = $listing;
12344:                 } else {
12345: 		    foreach my $line (@listing_results) {
12346: 			my ($entry) = split(/&/,$line,2);
12347: 			$allusers{$entry} = 1;
12348: 		    }
12349: 		}
12350:             }
12351:             my @alluserslist=();
12352:             foreach my $user (sort(keys(%allusers))) {
12353:                 push(@alluserslist,$user.'&user');
12354:             }
12355: 
12356:             if (!%listerror) {
12357:                 # no errors
12358:                 return (\@alluserslist);
12359:             } elsif (scalar(keys(%servers)) == 1) {
12360:                 # one library server, one error 
12361:                 my ($key) = keys(%listerror);
12362:                 return (\@alluserslist, $listerror{$key});
12363:             } elsif ( grep { $_ eq 'con_lost' } values(%listerror) ) {
12364:                 # con_lost indicates that we might miss data from at least one
12365:                 # library server
12366:                 return (\@alluserslist, 'con_lost');
12367:             } else {
12368:                 # multiple library servers and no con_lost -> data should be
12369:                 # complete. 
12370:                 return (\@alluserslist);
12371:             }
12372: 
12373:         } else {
12374:             return ([],'missing username');
12375:         }
12376:     } elsif(!defined($getpropath)) {
12377:         my $path = $perlvar{'lonDocRoot'}.'/res/'; 
12378:         my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
12379:         return (\@all_domains);
12380:     } else {
12381:         return ([],'missing domain');
12382:     }
12383: }
12384: 
12385: # --------------------------------------------- GetFileTimestamp
12386: # This function utilizes dirlist and returns the date stamp for
12387: # when it was last modified.  It will also return an error of -1
12388: # if an error occurs
12389: 
12390: sub GetFileTimestamp {
12391:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
12392:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
12393:     $studentName   = &LONCAPA::clean_username($studentName);
12394:     my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
12395:                                     undef,$getuserdir);
12396:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
12397:         return -1;
12398:     }
12399:     if (ref($fileref) eq 'ARRAY') {
12400:         my @stats = split('&',$fileref->[0]);
12401:         # @stats contains first the filename, then the stat output
12402:         return $stats[10]; # so this is 10 instead of 9.
12403:     } else {
12404:         return -1;
12405:     }
12406: }
12407: 
12408: sub stat_file {
12409:     my ($uri) = @_;
12410:     $uri = &clutter_with_no_wrapper($uri);
12411: 
12412:     my ($udom,$uname,$file);
12413:     if ($uri =~ m-^/(uploaded|editupload)/-) {
12414: 	($udom,$uname,$file) =
12415: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
12416: 	$file = 'userfiles/'.$file;
12417:     }
12418:     if ($uri =~ m-^/res/-) {
12419: 	($udom,$uname) = 
12420: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
12421: 	$file = $uri;
12422:     }
12423: 
12424:     if (!$udom || !$uname || !$file) {
12425: 	# unable to handle the uri
12426: 	return ();
12427:     }
12428:     my $getpropath;
12429:     if ($file =~ /^userfiles\//) {
12430:         $getpropath = 1;
12431:     }
12432:     my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
12433:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
12434:         return ();
12435:     } else {
12436:         if (ref($listref) eq 'ARRAY') {
12437:             my @stats = split('&',$listref->[0]);
12438: 	    shift(@stats); #filename is first
12439: 	    return @stats;
12440:         }
12441:     }
12442:     return ();
12443: }
12444: 
12445: # --------------------------------------------------------- recursedirs
12446: # Recursive function to traverse either a specific user's Authoring Space
12447: # or corresponding Published Resource Space, and populate the hash ref:
12448: # $dirhashref with URLs of all directories, and if $filehashref hash
12449: # ref arg is provided, the URLs of any files, excluding versioned, .meta,
12450: # or .rights files in resource space, and .meta, .save, .log, .bak and
12451: # .rights files in Authoring Space.
12452: #
12453: # Inputs:
12454: #
12455: # $is_home - true if current server is home server for user's space
12456: # $recurse - if true will also traverse subdirectories recursively
12457: # $include - reference to hash containing allowed file extensions.  If provided,
12458: #             files which do not have a matching extension will be ignored.
12459: # $exclude - reference to hash containing excluded file extensions.  If provided,
12460: #             files which have a matching extension will be ignored.
12461: # $nonemptydir - if true, will only populate $fileshashref hash entry for a particular
12462: #             directory with first file found (with acceptable extension).
12463: # $addtopdir - if true, set $dirhashref->{'/'} = 1 
12464: # $toppath - Top level directory (i.e., /res/$dom/$uname or /priv/$dom/$uname
12465: # $relpath - Current path (relative to top level).
12466: # $dirhashref - reference to hash to populate with URLs of directories (Required)
12467: # $filehashref - reference to hash to populate with URLs of files (Optional)
12468: #
12469: # Returns: nothing
12470: #
12471: # Side Effects: populates $dirhashref, and $filehashref (if provided).
12472: #
12473: # Currently used by interface/londocs.pm to create linked select boxes for
12474: # directory and filename to import a Course "Author" resource into a course, and
12475: # also to create linked select boxes for Authoring Space and Directory to choose
12476: # save location for creation of a new "standard" problem from the Course Editor.
12477: #
12478: 
12479: sub recursedirs {
12480:     my ($is_home,$recurse,$include,$exclude,$nonemptydir,$addtopdir,$toppath,$relpath,$dirhashref,$filehashref) = @_;
12481:     return unless (ref($dirhashref) eq 'HASH');
12482:     my $docroot = $perlvar{'lonDocRoot'};
12483:     my $currpath = $docroot.$toppath;
12484:     if ($relpath ne '') {
12485:         $currpath .= "/$relpath";
12486:     }
12487:     my ($savefile,$checkinc,$checkexc);
12488:     if (ref($filehashref)) {
12489:         $savefile = 1;
12490:     }
12491:     if (ref($include) eq 'HASH') {
12492:         $checkinc = 1;
12493:     }
12494:     if (ref($exclude) eq 'HASH') {
12495:         $checkexc = 1;
12496:     }
12497:     if ($is_home) {
12498:         if ((-e $currpath) && (opendir(my $dirh,$currpath))) {
12499:             my $filecount = 0;
12500:             foreach my $item (sort { lc($a) cmp lc($b) } grep(!/^\.+$/,readdir($dirh))) {
12501:                 next if ($item eq '');
12502:                 if (-d "$currpath/$item") {
12503:                     my $newpath;
12504:                     if ($relpath ne '') {
12505:                         $newpath = "$relpath/$item";
12506:                     } else {
12507:                         $newpath = $item;
12508:                     }
12509:                     $dirhashref->{&Apache::lonlocal::js_escape($newpath)} = 1;
12510:                     if ($recurse) {
12511:                         &recursedirs($is_home,$recurse,$include,$exclude,$nonemptydir,$addtopdir,$toppath,$newpath,$dirhashref,$filehashref);
12512:                     }
12513:                 } elsif (($savefile) || ($relpath eq '')) {
12514:                     next if ($nonemptydir && $filecount);
12515:                     if ($checkinc || $checkexc) {
12516:                         my ($extension) = ($item =~ /\.(\w+)$/);
12517:                         if ($checkinc) {
12518:                             next unless ($extension && $include->{$extension});
12519:                         }
12520:                         if ($checkexc) {
12521:                             next if ($extension && $exclude->{$extension});
12522:                         }
12523:                     }
12524:                     if (($relpath eq '') && (!exists($dirhashref->{'/'}))) {
12525:                         $dirhashref->{'/'} = 1;
12526:                     }
12527:                     if ($savefile) {
12528:                         if ($relpath eq '') {
12529:                             $filehashref->{'/'}{$item} = 1;
12530:                         } else {
12531:                             $filehashref->{&Apache::lonlocal::js_escape($relpath)}{$item} = 1;
12532:                         }
12533:                     }
12534:                     $filecount ++;
12535:                 }
12536:             }
12537:             closedir($dirh);
12538:         }
12539:     } else {
12540:         my ($dirlistref,$listerror) =
12541:             &dirlist($toppath.$relpath);
12542:         my @dir_lines;
12543:         my $dirptr=16384;
12544:         if (ref($dirlistref) eq 'ARRAY') {
12545:             my $filecount = 0;
12546:             foreach my $dir_line (sort
12547:                               {
12548:                                   my ($afile)=split('&',$a,2);
12549:                                   my ($bfile)=split('&',$b,2);
12550:                                   return (lc($afile) cmp lc($bfile));
12551:                               } (@{$dirlistref})) {
12552:                 my ($item,$dom,undef,$testdir,undef,undef,undef,undef,$size,undef,$mtime,undef,undef,undef,$obs,undef) =
12553:                     split(/\&/,$dir_line,16);
12554:                 $item =~ s/\s+$//;
12555:                 next if (($item =~ /^\.\.?$/) || ($obs));
12556:                 if ($dirptr&$testdir) {
12557:                     my $newpath;
12558:                     if ($relpath) {
12559:                         $newpath = "$relpath/$item";
12560:                     } else {
12561:                         $newpath = $item;
12562:                     }
12563:                     $dirhashref->{&Apache::lonlocal::js_escape($newpath)} = 1;
12564:                     if ($recurse) {
12565:                         &recursedirs($is_home,$recurse,$include,$exclude,$nonemptydir,$addtopdir,$toppath,$newpath,$dirhashref,$filehashref);
12566:                     }
12567:                 } elsif (($savefile) || ($relpath eq '')) {
12568:                     next if ($nonemptydir && $filecount);
12569:                     if ($checkinc || $checkexc) {
12570:                         my $extension;
12571:                         if ($checkinc) {
12572:                             next unless ($extension && $include->{$extension});
12573:                         }
12574:                         if ($checkexc) {
12575:                             next if ($extension && $exclude->{$extension});
12576:                         }
12577:                     }
12578:                     if (($relpath eq '') && (!exists($dirhashref->{'/'}))) {
12579:                         $dirhashref->{'/'} = 1;
12580:                     }
12581:                     if ($savefile) {
12582:                         if ($relpath eq '') {
12583:                             $filehashref->{'/'}{$item} = 1;
12584:                         } else {
12585:                             $filehashref->{&Apache::lonlocal::js_escape($relpath)}{$item} = 1;
12586:                         }
12587:                     }
12588:                     $filecount ++; 
12589:                 }
12590:             }
12591:         }
12592:     }
12593:     if ($addtopdir) {
12594:         if (($relpath eq '') && (!exists($dirhashref->{'/'}))) {
12595:             $dirhashref->{'/'} = 1;
12596:         }
12597:     }
12598:     return;
12599: }
12600: 
12601: sub priv_exclude {
12602:     return {
12603:              meta => 1,
12604:              save => 1,
12605:              log => 1,
12606:              bak => 1,
12607:              rights => 1,
12608:              DS_Store => 1,
12609:            };
12610: }
12611: 
12612: # -------------------------------------------------------- Value of a Condition
12613: 
12614: # gets the value of a specific preevaluated condition
12615: #    stored in the string  $env{user.state.<cid>}
12616: # or looks up a condition reference in the bighash and if if hasn't
12617: # already been evaluated recurses into docondval to get the value of
12618: # the condition, then memoizing it to 
12619: #   $env{user.state.<cid>.<condition>}
12620: sub directcondval {
12621:     my $number=shift;
12622:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
12623: 	&Apache::lonuserstate::evalstate();
12624:     }
12625:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
12626: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
12627:     } elsif ($number =~ /^_/) {
12628: 	my $sub_condition;
12629: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
12630: 		&GDBM_READER(),0640)) {
12631: 	    $sub_condition=$bighash{'conditions'.$number};
12632: 	    untie(%bighash);
12633: 	}
12634: 	my $value = &docondval($sub_condition);
12635: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
12636: 	return $value;
12637:     }
12638:     if ($env{'user.state.'.$env{'request.course.id'}}) {
12639:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
12640:     } else {
12641:        return 2;
12642:     }
12643: }
12644: 
12645: # get the collection of conditions for this resource
12646: sub condval {
12647:     my $condidx=shift;
12648:     my $allpathcond='';
12649:     foreach my $cond (split(/\|/,$condidx)) {
12650: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
12651: 	    $allpathcond.=
12652: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
12653: 	}
12654:     }
12655:     $allpathcond=~s/\|$//;
12656:     return &docondval($allpathcond);
12657: }
12658: 
12659: #evaluates an expression of conditions
12660: sub docondval {
12661:     my ($allpathcond) = @_;
12662:     my $result=0;
12663:     if ($env{'request.course.id'}
12664: 	&& defined($allpathcond)) {
12665: 	my $operand='|';
12666: 	my @stack;
12667: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
12668: 	    if ($chunk eq '(') {
12669: 		push @stack,($operand,$result);
12670: 	    } elsif ($chunk eq ')') {
12671: 		my $before=pop @stack;
12672: 		if (pop @stack eq '&') {
12673: 		    $result=$result>$before?$before:$result;
12674: 		} else {
12675: 		    $result=$result>$before?$result:$before;
12676: 		}
12677: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
12678: 		$operand=$chunk;
12679: 	    } else {
12680: 		my $new=directcondval($chunk);
12681: 		if ($operand eq '&') {
12682: 		    $result=$result>$new?$new:$result;
12683: 		} else {
12684: 		    $result=$result>$new?$result:$new;
12685: 		}
12686: 	    }
12687: 	}
12688:     }
12689:     return $result;
12690: }
12691: 
12692: # ---------------------------------------------------- Devalidate courseresdata
12693: 
12694: sub devalidatecourseresdata {
12695:     my ($coursenum,$coursedomain)=@_;
12696:     my $hashid=$coursenum.':'.$coursedomain;
12697:     &devalidate_cache_new('courseres',$hashid);
12698: }
12699: 
12700: 
12701: # --------------------------------------------------- Course Resourcedata Query
12702: #
12703: #  Parameters:
12704: #      $coursenum    - Number of the course.
12705: #      $coursedomain - Domain at which the course was created.
12706: #  Returns:
12707: #     A hash of the course parameters along (I think) with timestamps
12708: #     and version info.
12709: 
12710: sub get_courseresdata {
12711:     my ($coursenum,$coursedomain)=@_;
12712:     my $coursehom=&homeserver($coursenum,$coursedomain);
12713:     my $hashid=$coursenum.':'.$coursedomain;
12714:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
12715:     my %dumpreply;
12716:     unless (defined($cached)) {
12717: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
12718: 	$result=\%dumpreply;
12719: 	my ($tmp) = keys(%dumpreply);
12720: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
12721: 	    &do_cache_new('courseres',$hashid,$result,600);
12722: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
12723: 	    return $tmp;
12724: 	} elsif ($tmp =~ /^(error)/) {
12725: 	    $result=undef;
12726: 	    &do_cache_new('courseres',$hashid,$result,600);
12727: 	}
12728:     }
12729:     return $result;
12730: }
12731: 
12732: sub devalidateuserresdata {
12733:     my ($uname,$udom)=@_;
12734:     my $hashid="$udom:$uname";
12735:     &devalidate_cache_new('userres',$hashid);
12736: }
12737: 
12738: sub get_userresdata {
12739:     my ($uname,$udom)=@_;
12740:     #most student don\'t have any data set, check if there is some data
12741:     if (&EXT_cache_status($udom,$uname)) { return undef; }
12742: 
12743:     my $hashid="$udom:$uname";
12744:     my ($result,$cached)=&is_cached_new('userres',$hashid);
12745:     if (!defined($cached)) {
12746: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
12747: 	$result=\%resourcedata;
12748: 	&do_cache_new('userres',$hashid,$result,600);
12749:     }
12750:     my ($tmp)=keys(%$result);
12751:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
12752: 	return $result;
12753:     }
12754:     #error 2 occurs when the .db doesn't exist
12755:     if ($tmp!~/error: 2 /) {
12756:         if ((!defined($cached)) || ($tmp ne 'con_lost')) {
12757: 	    &logthis("<font color=\"blue\">WARNING:".
12758: 		     " Trying to get resource data for ".
12759: 		     $uname." at ".$udom.": ".
12760: 		     $tmp."</font>");
12761:         }
12762:     } elsif ($tmp=~/error: 2 /) {
12763: 	#&EXT_cache_set($udom,$uname);
12764: 	&do_cache_new('userres',$hashid,undef,600);
12765: 	undef($tmp); # not really an error so don't send it back
12766:     }
12767:     return $tmp;
12768: }
12769: #----------------------------------------------- resdata - return resource data
12770: #  Purpose:
12771: #    Return resource data for either users or for a course.
12772: #  Parameters:
12773: #     $name      - Course/user name.
12774: #     $domain    - Name of the domain the user/course is registered on.
12775: #     $type      - Type of thing $name is (must be 'course' or 'user')
12776: #     $mapp      - decluttered URL of enclosing map  
12777: #     $recursed  - Ref to scalar -- set to 1, if nested maps have been recursed.
12778: #     $recurseup - Ref to array of map URLs, starting with map containing
12779: #                  $mapp up through hierarchy of nested maps to top level map.  
12780: #     $courseid  - CourseID (first part of param identifier).
12781: #     $modifier  - Middle part of param identifier.
12782: #     $what      - Last part of param identifier.
12783: #     @which     - Array of names of resources desired.
12784: #  Returns:
12785: #     The value of the first reasource in @which that is found in the
12786: #     resource hash.
12787: #  Exceptional Conditions:
12788: #     If the $type passed in is not valid (not the string 'course' or 
12789: #     'user', an undefined  reference is returned.
12790: #     If none of the resources are found, an undef is returned
12791: sub resdata {
12792:     my ($name,$domain,$type,$mapp,$recursed,$recurseup,$courseid,
12793:         $modifier,$what,@which)=@_;
12794:     my $result;
12795:     if ($type eq 'course') {
12796: 	$result=&get_courseresdata($name,$domain);
12797:     } elsif ($type eq 'user') {
12798: 	$result=&get_userresdata($name,$domain);
12799:     }
12800:     if (!ref($result)) { return $result; }    
12801:     foreach my $item (@which) {
12802:         if ($item->[1] eq 'course') {
12803:             if ((ref($recurseup) eq 'ARRAY') && (ref($recursed) eq 'SCALAR')) {
12804:                 unless ($$recursed) {
12805:                     @{$recurseup} = &get_map_hierarchy($mapp,$courseid);
12806:                     $$recursed = 1;
12807:                 }
12808:                 foreach my $item (@${recurseup}) {
12809:                     my $norecursechk=$courseid.$modifier.$item.'___(all).'.$what;
12810:                     last if (defined($result->{$norecursechk}));
12811:                     my $recursechk=$courseid.$modifier.$item.'___(rec).'.$what;
12812:                     if (defined($result->{$recursechk})) { return [$result->{$recursechk},'map']; }
12813:                 }
12814:             }
12815:         }
12816:         if (defined($result->{$item->[0]})) {
12817: 	    return [$result->{$item->[0]},$item->[1]];
12818: 	}
12819:     }
12820:     return undef;
12821: }
12822: 
12823: sub get_domain_lti {
12824:     my ($cdom,$context) = @_;
12825:     my ($name,$cachename,%lti);
12826:     if ($context eq 'consumer') {
12827:         $name = 'ltitools';
12828:     } elsif ($context eq 'provider') {
12829:         $name = 'lti';
12830:     } elsif ($context eq 'linkprot') {
12831:         $name = 'ltisec';
12832:     } else {
12833:         return %lti;
12834:     }
12835:     if ($context eq 'linkprot') {
12836:         $cachename = $context;
12837:     } else {
12838:         $cachename = $name;
12839:     }
12840:     my ($result,$cached)=&is_cached_new($cachename,$cdom);
12841:     if (defined($cached)) {
12842:         if (ref($result) eq 'HASH') {
12843:             %lti = %{$result};
12844:         }
12845:     } else {
12846:         my %domconfig = &get_dom('configuration',[$name],$cdom);
12847:         if (ref($domconfig{$name}) eq 'HASH') {
12848:             if ($context eq 'linkprot') {
12849:                 if (ref($domconfig{$name}{'linkprot'}) eq 'HASH') {
12850:                     %lti = %{$domconfig{$name}{'linkprot'}};
12851:                 }
12852:             } else {
12853:                 %lti = %{$domconfig{$name}};
12854:             }
12855:         }
12856:         my $cachetime = 24*60*60;
12857:         &do_cache_new($cachename,$cdom,\%lti,$cachetime);
12858:     }
12859:     return %lti;
12860: }
12861: 
12862: sub get_course_lti {
12863:     my ($cnum,$cdom,$context) = @_;
12864:     my ($name,$cachename,%lti);
12865:     if ($context eq 'consumer') {
12866:         $name = 'ltitools';
12867:         $cachename = 'courseltitools';
12868:     } elsif ($context eq 'provider') {
12869:         $name = 'lti';
12870:         $cachename = 'courselti';
12871:     } else {
12872:         return %lti;
12873:     }
12874:     my $hashid=$cdom.'_'.$cnum;
12875:     my ($result,$cached)=&is_cached_new($cachename,$hashid);
12876:     if (defined($cached)) {
12877:         if (ref($result) eq 'HASH') {
12878:             %lti = %{$result};
12879:         }
12880:     } else {
12881:         %lti = &dump($name,$cdom,$cnum,undef,undef,undef,1);
12882:         my $cachetime = 24*60*60;
12883:         &do_cache_new($cachename,$hashid,\%lti,$cachetime);
12884:     }
12885:     return %lti;
12886: }
12887: 
12888: sub courselti_itemid {
12889:     my ($cnum,$cdom,$url,$method,$params,$context) = @_;
12890:     my ($chome,$itemid);
12891:     $chome = &homeserver($cnum,$cdom);
12892:     return if ($chome eq 'no_host');
12893:     if (ref($params) eq 'HASH') {
12894:         my $rep;
12895:         if (grep { $_ eq $chome } current_machine_ids()) {
12896:             $rep = LONCAPA::Lond::crslti_itemid($cdom,$cnum,$url,$method,$params,$perlvar{'lonVersion'});
12897:         } else {
12898:             my $escurl = &escape($url);
12899:             my $escmethod = &escape($method);
12900:             my $items = &freeze_escape($params);
12901:             $rep = &reply("encrypt:lti:$cdom:$cnum:$context:$escurl:$escmethod:$items",$chome);
12902:         }
12903:         unless (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
12904:                 ($rep eq 'unknown_cmd')) {
12905:             $itemid = $rep;
12906:         }
12907:     }
12908:     return $itemid;
12909: }
12910: 
12911: sub domainlti_itemid {
12912:     my ($cdom,$url,$method,$params,$context) = @_;
12913:     my ($primary_id,$itemid);
12914:     $primary_id = &domain($cdom,'primary');
12915:     return if ($primary_id eq '');
12916:     if (ref($params) eq 'HASH') {
12917:         my $rep;
12918:         if (grep { $_ eq $primary_id } current_machine_ids()) {
12919:             $rep = LONCAPA::Lond::domlti_itemid($cdom,$context,$url,$method,$params,$perlvar{'lonVersion'});
12920:         } else {
12921:             my $cnum = '';
12922:             my $escurl = &escape($url);
12923:             my $escmethod = &escape($method);
12924:             my $items = &freeze_escape($params);
12925:             $rep = &reply("encrypt:lti:$cdom:$cnum:$context:$escurl:$escmethod:$items",$primary_id);
12926:         }
12927:         unless (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
12928:                 ($rep eq 'unknown_cmd')) {
12929:             $itemid = $rep;
12930:         }
12931:     }
12932:     return $itemid;
12933: }
12934: 
12935: sub get_ltitools_id {
12936:     my ($context,$cdom,$cnum,$title) = @_;
12937:     my ($lockhash,$tries,$gotlock,$id,$error);
12938: 
12939:     # get lock on ltitools db
12940:     $lockhash = {
12941:                    lock => $env{'user.name'}.
12942:                            ':'.$env{'user.domain'},
12943:                 };
12944:     $tries = 0;
12945:     if ($context eq 'domain') {
12946:         $gotlock = &newput_dom('ltitools',$lockhash,$cdom);
12947:     } else {
12948:         $gotlock = &newput('ltitools',$lockhash,$cdom,$cnum);
12949:     }
12950:     while (($gotlock ne 'ok') && ($tries<10)) {
12951:         $tries ++;
12952:         sleep (0.1);
12953:         if ($context eq 'domain') {
12954:             $gotlock = &newput_dom('ltitools',$lockhash,$cdom);
12955:         } else {
12956:             $gotlock = &newput('ltitools',$lockhash,$cdom,$cnum);
12957:         }
12958:     }
12959:     if ($gotlock eq 'ok') {
12960:         my %currids;
12961:         if ($context eq 'domain') {
12962:             %currids = &dump_dom('ltitools',$cdom);
12963:         } else {
12964:             %currids = &dump('ltitools',$cdom,$cnum);
12965:         }
12966:         if ($currids{'lock'}) {
12967:             delete($currids{'lock'});
12968:             if (keys(%currids)) {
12969:                 my @curr = sort { $a <=> $b } keys(%currids);
12970:                 if ($curr[-1] =~ /^\d+$/) {
12971:                     $id = 1 + $curr[-1];
12972:                 }
12973:             } else {
12974:                 $id = 1;
12975:             }
12976:             if ($id) {
12977:                 if ($context eq 'domain') {
12978:                     unless (&newput_dom('ltitools',{ $id => $title },$cdom) eq 'ok') {
12979:                         $error = 'nostore';
12980:                     }
12981:                 } else {
12982:                     unless (&newput('ltitools',{ $id => $title },$cdom,$cnum) eq 'ok') {
12983:                         $error = 'nostore';
12984:                     }
12985:                 }
12986:             } else {
12987:                 $error = 'nonumber';
12988:             }
12989:         }
12990:         my $dellockoutcome;
12991:         if ($context eq 'domain') {
12992:             $dellockoutcome = &del_dom('ltitools',['lock'],$cdom);
12993:         } else {
12994:             $dellockoutcome = &del('ltitools',['lock'],$cdom,$cnum);
12995:         }
12996:     } else {
12997:         $error = 'nolock';
12998:     }
12999:     return ($id,$error);
13000: }
13001: 
13002: sub count_supptools {
13003:     my ($cnum,$cdom,$ignorecache,$reload)=@_;
13004:     my $hashid=$cnum.':'.$cdom;
13005:     my ($numexttools,$cached);
13006:     unless ($ignorecache) {
13007:         ($numexttools,$cached) = &is_cached_new('supptools',$hashid);
13008:     }
13009:     unless (defined($cached)) {
13010:         my $chome=&homeserver($cnum,$cdom);
13011:         $numexttools = 0;
13012:         unless ($chome eq 'no_host') {
13013:             my ($supplemental) = &Apache::loncommon::get_supplemental($cnum,$cdom,$reload);
13014:             if (ref($supplemental) eq 'HASH') {
13015:                 if ((ref($supplemental->{'ids'}) eq 'HASH') && (ref($supplemental->{'hidden'}) eq 'HASH')) {
13016:                     foreach my $key (keys(%{$supplemental->{'ids'}})) {
13017:                         if ($key =~ m{^/adm/$cdom/$cnum/\d+/ext\.tool$}) {
13018:                             $numexttools ++;
13019:                         }
13020:                     }
13021:                 }
13022:             }
13023:         }
13024:         &do_cache_new('supptools',$hashid,$numexttools,600);
13025:     }
13026:     return $numexttools;
13027: }
13028: 
13029: sub has_unhidden_suppfiles {
13030:     my ($cnum,$cdom,$ignorecache,$possdel)=@_;
13031:     my $hashid=$cnum.':'.$cdom;
13032:     my ($showsupp,$cached);
13033:     unless ($ignorecache) {
13034:         ($showsupp,$cached) = &is_cached_new('showsupp',$hashid);
13035:     }
13036:     unless (defined($cached)) {
13037:         my $chome=&homeserver($cnum,$cdom);
13038:         unless ($chome eq 'no_host') {
13039:             my ($supplemental) = &Apache::loncommon::get_supplemental($cnum,$cdom,$ignorecache,$possdel);
13040:             if (ref($supplemental) eq 'HASH') {
13041:                 if ((ref($supplemental->{'ids'}) eq 'HASH') && (ref($supplemental->{'hidden'}) eq 'HASH')) {
13042:                     foreach my $key (keys(%{$supplemental->{'ids'}})) {
13043:                         next if ($key =~ /\.sequence$/);
13044:                         if (ref($supplemental->{'ids'}->{$key}) eq 'ARRAY') {
13045:                             foreach my $id (@{$supplemental->{'ids'}->{$key}}) {
13046:                                 unless ($supplemental->{'hidden'}->{$id}) {
13047:                                     $showsupp = 1;
13048:                                     last;
13049:                                 }
13050:                             }
13051:                         }
13052:                         last if ($showsupp);
13053:                     }
13054:                 }
13055:             }
13056:         }
13057:         &do_cache_new('showsupp',$hashid,$showsupp,600);
13058:     }
13059:     return $showsupp;
13060: }
13061: 
13062: #
13063: # EXT resource caching routines
13064: #
13065: 
13066: {
13067: # Cache (5 seconds) of map hierarchy for speedup of navmaps display
13068: #
13069: # The course for which we cache
13070: my $cachedmapkey='';
13071: # The cached recursive maps for this course
13072: my %cachedmaps=();
13073: # When this was last done
13074: my $cachedmaptime='';
13075: 
13076: sub clear_EXT_cache_status {
13077:     &delenv('cache.EXT.');
13078: }
13079: 
13080: sub EXT_cache_status {
13081:     my ($target_domain,$target_user) = @_;
13082:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
13083:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
13084:         # We know already the user has no data
13085:         return 1;
13086:     } else {
13087:         return 0;
13088:     }
13089: }
13090: 
13091: sub EXT_cache_set {
13092:     my ($target_domain,$target_user) = @_;
13093:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
13094:     #&appenv({$cachename => time});
13095: }
13096: 
13097: # --------------------------------------------------------- Value of a Variable
13098: sub EXT {
13099: 
13100:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse,$cid,$recurseupref)=@_;
13101:     unless ($varname) { return ''; }
13102:     #get real user name/domain, courseid and symb
13103:     my $courseid;
13104:     my $publicuser;
13105:     if ($symbparm) {
13106: 	$symbparm=&get_symb_from_alias($symbparm);
13107:     }
13108:     if (!($uname && $udom)) {
13109:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
13110:       if (!$symbparm) {	$symbparm=$cursymb; }
13111:     } else {
13112: 	$courseid=$env{'request.course.id'};
13113:     }
13114:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
13115:     my $rest;
13116:     if (defined($therest[0])) {
13117:        $rest=join('.',@therest);
13118:     } else {
13119:        $rest='';
13120:     }
13121: 
13122:     my $qualifierrest=$qualifier;
13123:     if ($rest) { $qualifierrest.='.'.$rest; }
13124:     my $spacequalifierrest=$space;
13125:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
13126:     if ($realm eq 'user') {
13127: # --------------------------------------------------------------- user.resource
13128: 	if ($space eq 'resource') {
13129: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
13130: 		  || defined($Apache::lonhomework::parsing_a_task))
13131: 		 &&
13132: 		 ($symbparm eq &symbread()) ) {
13133: 		# if we are in the middle of processing the resource the
13134: 		# get the value we are planning on committing
13135:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
13136:                     return $Apache::lonhomework::results{$qualifierrest};
13137:                 } else {
13138:                     return $Apache::lonhomework::history{$qualifierrest};
13139:                 }
13140: 	    } else {
13141: 		my %restored;
13142: 		if ($publicuser || $env{'request.state'} eq 'construct') {
13143: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
13144: 		} else {
13145: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
13146: 		}
13147: 		return $restored{$qualifierrest};
13148: 	    }
13149: # ----------------------------------------------------------------- user.access
13150:         } elsif ($space eq 'access') {
13151: 	    # FIXME - not supporting calls for a specific user
13152:             return &allowed($qualifier,$rest);
13153: # ------------------------------------------ user.preferences, user.environment
13154:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
13155: 	    if (($uname eq $env{'user.name'}) &&
13156: 		($udom eq $env{'user.domain'})) {
13157: 		return $env{join('.',('environment',$qualifierrest))};
13158: 	    } else {
13159: 		my %returnhash;
13160: 		if (!$publicuser) {
13161: 		    %returnhash=&userenvironment($udom,$uname,
13162: 						 $qualifierrest);
13163: 		}
13164: 		return $returnhash{$qualifierrest};
13165: 	    }
13166: # ----------------------------------------------------------------- user.course
13167:         } elsif ($space eq 'course') {
13168: 	    # FIXME - not supporting calls for a specific user
13169:             return $env{join('.',('request.course',$qualifier))};
13170: # ------------------------------------------------------------------- user.role
13171:         } elsif ($space eq 'role') {
13172: 	    # FIXME - not supporting calls for a specific user
13173:             my ($role,$where)=split(/\./,$env{'request.role'});
13174:             if ($qualifier eq 'value') {
13175: 		return $role;
13176:             } elsif ($qualifier eq 'extent') {
13177:                 return $where;
13178:             }
13179: # ----------------------------------------------------------------- user.domain
13180:         } elsif ($space eq 'domain') {
13181:             return $udom;
13182: # ------------------------------------------------------------------- user.name
13183:         } elsif ($space eq 'name') {
13184:             return $uname;
13185: # ---------------------------------------------------- Any other user namespace
13186:         } else {
13187: 	    my %reply;
13188: 	    if (!$publicuser) {
13189: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
13190: 	    }
13191: 	    return $reply{$qualifierrest};
13192:         }
13193:     } elsif ($realm eq 'query') {
13194: # ---------------------------------------------- pull stuff out of query string
13195:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
13196: 						[$spacequalifierrest]);
13197: 	return $env{'form.'.$spacequalifierrest}; 
13198:    } elsif ($realm eq 'request') {
13199: # ------------------------------------------------------------- request.browser
13200:         if ($space eq 'browser') {
13201:             return $env{'browser.'.$qualifier};
13202: # ------------------------------------------------------------ request.filename
13203:         } else {
13204:             return $env{'request.'.$spacequalifierrest};
13205:         }
13206:     } elsif ($realm eq 'course') {
13207: # ---------------------------------------------------------- course.description
13208:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
13209:     } elsif ($realm eq 'resource') {
13210: 
13211: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
13212: 	    if (!$symbparm) { $symbparm=&symbread(); }
13213: 	}
13214: 
13215:         if ($qualifier eq '') {
13216: 	    if ($space eq 'title') {
13217: 	        if (!$symbparm) { $symbparm = $env{'request.filename'}; }
13218: 	        return &gettitle($symbparm);
13219: 	    }
13220: 	
13221: 	    if ($space eq 'map') {
13222: 	        my ($map) = &decode_symb($symbparm);
13223: 	        return &symbread($map);
13224: 	    }
13225:             if ($space eq 'maptitle') {
13226:                 my ($map) = &decode_symb($symbparm);
13227:                 return &gettitle($map);
13228:             }
13229: 	    if ($space eq 'filename') {
13230: 	        if ($symbparm) {
13231: 		    return &clutter((&decode_symb($symbparm))[2]);
13232: 	        }
13233: 	        return &hreflocation('',$env{'request.filename'});
13234: 	    }
13235: 
13236:             if ((defined($courseid)) && ($courseid eq $env{'request.course.id'}) && $symbparm) {
13237:                 if ($space eq 'visibleparts') {
13238:                     my $navmap = Apache::lonnavmaps::navmap->new();
13239:                     my $item;
13240:                     if (ref($navmap)) {
13241:                         my $res = $navmap->getBySymb($symbparm);
13242:                         my $parts = $res->parts();
13243:                         if (ref($parts) eq 'ARRAY') {
13244:                             $item = join(',',@{$parts});
13245:                         }
13246:                         undef($navmap);
13247:                     }
13248:                     return $item;
13249:                 }
13250:             }
13251:         }
13252: 
13253: 	my ($section, $group, @groups, @recurseup, $recursed);
13254:         if (ref($recurseupref) eq 'ARRAY') {
13255:             @recurseup = @{$recurseupref};
13256:             $recursed = 1;
13257:         }
13258: 	my ($courselevelm,$courseleveli,$courselevel,$mapp);
13259:         if (($courseid eq '') && ($cid)) {
13260:             $courseid = $cid;
13261:         }
13262: 	if (($symbparm && $courseid) && 
13263: 	    (($courseid eq $env{'request.course.id'}) || ($courseid eq $cid)))  {
13264: 
13265: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
13266: 
13267: # ----------------------------------------------------- Cascading lookup scheme
13268: 	    my $symbp=$symbparm;
13269: 	    $mapp=&deversion((&decode_symb($symbp))[0]);
13270: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
13271:             my $recurseparm=$mapp.'___(rec).'.$spacequalifierrest;
13272: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
13273: 	    if (($env{'user.name'} eq $uname) &&
13274: 		($env{'user.domain'} eq $udom)) {
13275: 		$section=$env{'request.course.sec'};
13276:                 @groups = split(/:/,$env{'request.course.groups'});  
13277:                 @groups=&sort_course_groups($courseid,@groups); 
13278: 	    } else {
13279: 		if (! defined($usection)) {
13280: 		    $section=&getsection($udom,$uname,$courseid);
13281: 		} else {
13282: 		    $section = $usection;
13283: 		}
13284:                 @groups = &get_users_groups($udom,$uname,$courseid);
13285: 	    }
13286: 
13287: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
13288: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
13289:             my $secleveli=$courseid.'.['.$section.'].'.$recurseparm;
13290: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
13291: 
13292: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
13293: 	    my $courselevelr=$courseid.'.'.$symbparm;
13294:             $courseleveli=$courseid.'.'.$recurseparm;
13295: 	    $courselevelm=$courseid.'.'.$mapparm;
13296: 
13297: # ----------------------------------------------------------- first, check user
13298: 
13299: 	    my $userreply=&resdata($uname,$udom,'user',$mapp,\$recursed,
13300:                                    \@recurseup,$courseid,'.',$spacequalifierrest, 
13301: 				       ([$courselevelr,'resource'],
13302: 					[$courselevelm,'map'     ],
13303:                                         [$courseleveli,'map'     ],
13304: 					[$courselevel, 'course'  ]));
13305: 	    if (defined($userreply)) { return &get_reply($userreply); }
13306: 
13307: # ------------------------------------------------ second, check some of course
13308:             my $coursereply;
13309:             if (@groups > 0) {
13310:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
13311:                                        $recurseparm,$mapparm,$spacequalifierrest,
13312:                                        $mapp,\$recursed,\@recurseup);
13313:                 if (defined($coursereply)) { return &get_reply($coursereply); } 
13314:             }
13315: 
13316: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
13317: 				  $env{'course.'.$courseid.'.domain'},
13318: 				  'course',$mapp,\$recursed,\@recurseup,
13319:                                   $courseid,'.['.$section.'].',$spacequalifierrest,
13320: 				  ([$seclevelr,   'resource'],
13321: 				   [$seclevelm,   'map'     ],
13322:                                    [$secleveli,   'map'     ],
13323: 				   [$seclevel,    'course'  ],
13324: 				   [$courselevelr,'resource']));
13325: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
13326: 
13327: # ------------------------------------------------------ third, check map parms
13328: 	    my %parmhash=();
13329: 	    my $thisparm='';
13330: 	    if (tie(%parmhash,'GDBM_File',
13331: 		    $env{'request.course.fn'}.'_parms.db',
13332: 		    &GDBM_READER(),0640)) {
13333: 		$thisparm=$parmhash{$symbparm};
13334: 		untie(%parmhash);
13335: 	    }
13336: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
13337: 	}
13338: # ------------------------------------------ fourth, look in resource metadata
13339:  
13340:         my $what = $spacequalifierrest;
13341: 	$what=~s/\./\_/;
13342: 	my $filename;
13343: 	if (!$symbparm) { $symbparm=&symbread(); }
13344: 	if ($symbparm) {
13345: 	    $filename=(&decode_symb($symbparm))[2];
13346: 	} else {
13347: 	    $filename=$env{'request.filename'};
13348: 	}
13349:         my $toolsymb;
13350:         if (($filename =~ /ext\.tool$/) && ($what ne '0_gradable')) {
13351:             $toolsymb = $symbparm;
13352:         }
13353: 	my $metadata=&metadata($filename,$what,$toolsymb);
13354: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
13355: 	$metadata=&metadata($filename,'parameter_'.$what,$toolsymb);
13356: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
13357: 
13358: # ----------------------------------------------- fifth, look in rest of course
13359: 	if ($symbparm && defined($courseid) && 
13360: 	    $courseid eq $env{'request.course.id'}) {
13361: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
13362: 				     $env{'course.'.$courseid.'.domain'},
13363: 				     'course',$mapp,\$recursed,\@recurseup,
13364:                                      $courseid,'.',$spacequalifierrest,
13365: 				     ([$courselevelm,'map'   ],
13366:                                       [$courseleveli,'map'   ],
13367: 				      [$courselevel, 'course']));
13368: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
13369: 	}
13370: # ------------------------------------------------------------------ Cascade up
13371: 	unless ($space eq '0') {
13372: 	    my @parts=split(/_/,$space);
13373: 	    my $id=pop(@parts);
13374: 	    my $part=join('_',@parts);
13375: 	    if ($part eq '') { $part='0'; }
13376: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
13377: 				 $symbparm,$udom,$uname,$section,1);
13378: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
13379: 	}
13380: 	if ($recurse) { return undef; }
13381: 	my $pack_def=&packages_tab_default($filename,$varname,$toolsymb);
13382: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
13383: # ---------------------------------------------------- Any other user namespace
13384:     } elsif ($realm eq 'environment') {
13385: # ----------------------------------------------------------------- environment
13386: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
13387: 	    return $env{'environment.'.$spacequalifierrest};
13388: 	} else {
13389: 	    if ($uname eq 'anonymous' && $udom eq '') {
13390: 		return '';
13391: 	    }
13392: 	    my %returnhash=&userenvironment($udom,$uname,
13393: 					    $spacequalifierrest);
13394: 	    return $returnhash{$spacequalifierrest};
13395: 	}
13396:     } elsif ($realm eq 'system') {
13397: # ----------------------------------------------------------------- system.time
13398: 	if ($space eq 'time') {
13399: 	    return time;
13400:         }
13401:     } elsif ($realm eq 'server') {
13402: # ----------------------------------------------------------------- system.time
13403: 	if ($space eq 'name') {
13404: 	    return $ENV{'SERVER_NAME'};
13405:         }
13406:     } elsif ($realm eq 'client') {
13407:         if ($space eq 'remote_addr') {
13408:             return &get_requestor_ip();
13409:         }
13410:     }
13411:     return '';
13412: }
13413: 
13414: sub get_reply {
13415:     my ($reply_value) = @_;
13416:     if (ref($reply_value) eq 'ARRAY') {
13417:         if (wantarray) {
13418: 	    return @$reply_value;
13419:         }
13420:         return $reply_value->[0];
13421:     } else {
13422:         return $reply_value;
13423:     }
13424: }
13425: 
13426: sub check_group_parms {
13427:     my ($courseid,$groups,$symbparm,$recurseparm,$mapparm,$what,$mapp,
13428:         $recursed,$recurseupref) = @_;
13429:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$recurseparm,'map'],
13430:                   [$what,'course']);
13431:     my $coursereply;
13432:     foreach my $group (@{$groups}) {
13433:         my @groupitems = ();
13434:         foreach my $level (@levels) {
13435:              my $item = $courseid.'.['.$group.'].'.$level->[0];
13436:              push(@groupitems,[$item,$level->[1]]);
13437:         }
13438:         my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
13439:                                    $env{'course.'.$courseid.'.domain'},
13440:                                    'course',$mapp,$recursed,$recurseupref,
13441:                                    $courseid,'.['.$group.'].',$what,
13442:                                    @groupitems);
13443:         last if (defined($coursereply));
13444:     }
13445:     return $coursereply;
13446: }
13447: 
13448: sub get_map_hierarchy {
13449:     my ($mapname,$courseid) = @_;
13450:     my @recurseup = ();
13451:     if ($mapname) {
13452:         if (($cachedmapkey eq $courseid) &&
13453:             (abs($cachedmaptime-time)<5)) {
13454:             if (ref($cachedmaps{$mapname}) eq 'ARRAY') {
13455:                 return @{$cachedmaps{$mapname}};
13456:             }
13457:         }
13458:         my $navmap = Apache::lonnavmaps::navmap->new();
13459:         if (ref($navmap)) {
13460:             @recurseup = $navmap->recurseup_maps($mapname);
13461:             undef($navmap);
13462:             $cachedmaps{$mapname} = \@recurseup;
13463:             $cachedmaptime=time;
13464:             $cachedmapkey=$courseid;
13465:         }
13466:     }
13467:     return @recurseup;
13468: }
13469: 
13470: }
13471: 
13472: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
13473:     my ($courseid,@groups) = @_;
13474:     @groups = sort(@groups);
13475:     return @groups;
13476: }
13477: 
13478: sub packages_tab_default {
13479:     my ($uri,$varname,$toolsymb)=@_;
13480:     my (undef,$part,$name)=split(/\./,$varname);
13481: 
13482:     my (@extension,@specifics,$do_default);
13483:     foreach my $package (split(/,/,&metadata($uri,'packages',$toolsymb))) {
13484: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
13485: 	if ($pack_type eq 'default') {
13486: 	    $do_default=1;
13487: 	} elsif ($pack_type eq 'extension') {
13488: 	    push(@extension,[$package,$pack_type,$pack_part]);
13489: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
13490: 	    # only look at packages defaults for packages that this id is
13491: 	    push(@specifics,[$package,$pack_type,$pack_part]);
13492: 	}
13493:     }
13494:     # first look for a package that matches the requested part id
13495:     foreach my $package (@specifics) {
13496: 	my (undef,$pack_type,$pack_part)=@{$package};
13497: 	next if ($pack_part ne $part);
13498: 	if (defined($packagetab{"$pack_type&$name&default"})) {
13499: 	    return $packagetab{"$pack_type&$name&default"};
13500: 	}
13501:     }
13502:     # look for any possible matching non extension_ package
13503:     foreach my $package (@specifics) {
13504: 	my (undef,$pack_type,$pack_part)=@{$package};
13505: 	if (defined($packagetab{"$pack_type&$name&default"})) {
13506: 	    return $packagetab{"$pack_type&$name&default"};
13507: 	}
13508: 	if ($pack_type eq 'part') { $pack_part='0'; }
13509: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
13510: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
13511: 	}
13512:     }
13513:     # look for any posible extension_ match
13514:     foreach my $package (@extension) {
13515: 	my ($package,$pack_type)=@{$package};
13516: 	if (defined($packagetab{"$pack_type&$name&default"})) {
13517: 	    return $packagetab{"$pack_type&$name&default"};
13518: 	}
13519: 	if (defined($packagetab{$package."&$name&default"})) {
13520: 	    return $packagetab{$package."&$name&default"};
13521: 	}
13522:     }
13523:     # look for a global default setting
13524:     if ($do_default && defined($packagetab{"default&$name&default"})) {
13525: 	return $packagetab{"default&$name&default"};
13526:     }
13527:     return undef;
13528: }
13529: 
13530: sub add_prefix_and_part {
13531:     my ($prefix,$part)=@_;
13532:     my $keyroot;
13533:     if (defined($prefix) && $prefix !~ /^__/) {
13534: 	# prefix that has a part already
13535: 	$keyroot=$prefix;
13536:     } elsif (defined($prefix)) {
13537: 	# prefix that is missing a part
13538: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
13539:     } else {
13540: 	# no prefix at all
13541: 	if (defined($part)) { $keyroot='_'.$part; }
13542:     }
13543:     return $keyroot;
13544: }
13545: 
13546: # ---------------------------------------------------------------- Get metadata
13547: 
13548: my %metaentry;
13549: my %importedpartids;
13550: my %importedrespids;
13551: sub metadata {
13552:     my ($uri,$what,$toolsymb,$liburi,$prefix,$depthcount)=@_;
13553:     $uri=&declutter($uri);
13554:     # if it is a non metadata possible uri return quickly
13555:     if (($uri eq '') || 
13556: 	(($uri =~ m|^/*adm/|) && 
13557: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard|ext\.tool)$})) ||
13558:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
13559: 	return undef;
13560:     }
13561:     if (($uri =~ /^priv/ || $uri=~m{^home/httpd/html/priv}) 
13562: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
13563: 	return undef;
13564:     }
13565:     my $filename=$uri;
13566:     $uri=~s/\.meta$//;
13567: #
13568: # Is the metadata already cached?
13569: # Look at timestamp of caching
13570: # Everything is cached by the main uri, libraries are never directly cached
13571: #
13572:     if (!defined($liburi)) {
13573: 	my ($result,$cached)=&is_cached_new('meta',$uri);
13574: 	if (defined($cached)) { return $result->{':'.$what}; }
13575:     }
13576: 
13577: #
13578: # If the uri is for an external tool the file from
13579: # which metadata should be retrieved depends on whether
13580: # the tool had been configured to be gradable (set in the Course
13581: # Editor or Resource Editor).
13582: #
13583: # If a valid symb has been included as the third arg in the call
13584: # to &metadata() that can be used to retrieve the value of
13585: # parameter_0_gradable set for the resource, and included in the
13586: # uploaded map containing the tool. The value is retrieved via
13587: # &EXT(), if a valid symb is available.  Otherwise the value of
13588: # gradable in the exttool_$marker.db file for the tool instance
13589: # is retrieved via &get().
13590: #
13591: # When lonuserstate::traceroute() calls lonnet::EXT() for 
13592: # hiddenresource and encrypturl (during course initialization)
13593: # the map-level parameter for resource.0.gradable included in the 
13594: # uploaded map containing the tool will not yet have been stored
13595: # in the user_course_parms.db file for the user's session, so in 
13596: # this case fall back to retrieving gradable status from the
13597: # exttool_$marker.db file.
13598: #
13599: # In order to avoid an infinite loop, &metadata() will return
13600: # before a call to &EXT(), if the uri is for an external tool
13601: # and the $what for which metadata is being requested is
13602: # parameter_0_gradable or 0_gradable.
13603: #
13604: 
13605:     if ($uri =~ /ext\.tool$/) {
13606:         if (($what eq 'parameter_0_gradable') || ($what eq '0_gradable')) {
13607:             return;
13608:         } else {
13609:             my ($checked,$use_passback);
13610:             if ($toolsymb ne '') {
13611:                 (undef,undef,my $tooluri) = &decode_symb($toolsymb);
13612:                 if (($tooluri eq $uri) && (&EXT('resource.0.gradable',$toolsymb))) {
13613:                     $checked = 1;
13614:                     if (&EXT('resource.0.gradable',$toolsymb) =~ /^yes$/i) {
13615:                         $use_passback = 1;
13616:                     }
13617:                 }
13618:             }
13619:             unless ($checked) {
13620:                 my ($ignore,$cdom,$cnum,$marker) = split(m{/},$uri);
13621:                 $marker=~s/\D//g;
13622:                 if ($marker) {
13623:                     my %toolsettings=&get('exttool_'.$marker,['gradable'],$cdom,$cnum);
13624:                     $use_passback = $toolsettings{'gradable'};
13625:                 }
13626:             }
13627:             if ($use_passback) {
13628:                 $filename = '/home/httpd/html/res/lib/templates/LTIpassback.tool';
13629:             } else {
13630:                 $filename = '/home/httpd/html/res/lib/templates/LTIstandard.tool';
13631:             }
13632:         }
13633:     }
13634: 
13635:     {
13636: # Imported parts would go here
13637:         my @origfiletagids=();
13638:         my $importedparts=0;
13639: 
13640: # Imported responseids would go here
13641:         my $importedresponses=0;
13642: #
13643: # Is this a recursive call for a library?
13644: #
13645: #	if (! exists($metacache{$uri})) {
13646: #	    $metacache{$uri}={};
13647: #	}
13648: 	my $cachetime = 60*60;
13649:         if ($liburi) {
13650: 	    $liburi=&declutter($liburi);
13651:             $filename=$liburi;
13652:         } else {
13653: 	    &devalidate_cache_new('meta',$uri);
13654: 	    undef(%metaentry);
13655: 	}
13656:         my %metathesekeys=();
13657:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
13658: 	my $metastring;
13659: 	if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
13660: 	    my $which = &hreflocation('','/'.($liburi || $uri));
13661: 	    $metastring = 
13662: 		&Apache::lonnet::ssi_body($which,
13663: 					  ('grade_target' => 'meta'));
13664: 	    $cachetime = 1; # only want this cached in the child not long term
13665: 	} elsif (($uri !~ m -^(editupload)/-) && 
13666:                  ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
13667: 	    my $file=&filelocation('',&clutter($filename));
13668: 	    #push(@{$metaentry{$uri.'.file'}},$file);
13669: 	    $metastring=&getfile($file);
13670: 	}
13671:         my $parser=HTML::LCParser->new(\$metastring);
13672:         my $token;
13673:         undef %metathesekeys;
13674:         while ($token=$parser->get_token) {
13675: 	    if ($token->[0] eq 'S') {
13676: 		if (defined($token->[2]->{'package'})) {
13677: #
13678: # This is a package - get package info
13679: #
13680: 		    my $package=$token->[2]->{'package'};
13681: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
13682: 		    if (defined($token->[2]->{'id'})) { 
13683: 			$keyroot.='_'.$token->[2]->{'id'}; 
13684: 		    }
13685: 		    if ($metaentry{':packages'}) {
13686: 			$metaentry{':packages'}.=','.$package.$keyroot;
13687: 		    } else {
13688: 			$metaentry{':packages'}=$package.$keyroot;
13689: 		    }
13690: 		    foreach my $pack_entry (keys(%packagetab)) {
13691: 			my $part=$keyroot;
13692: 			$part=~s/^\_//;
13693: 			if ($pack_entry=~/^\Q$package\E\&/ || 
13694: 			    $pack_entry=~/^\Q$package\E_0\&/) {
13695: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
13696: 			    # ignore package.tab specified default values
13697:                             # here &package_tab_default() will fetch those
13698: 			    if ($subp eq 'default') { next; }
13699: 			    my $value=$packagetab{$pack_entry};
13700: 			    my $unikey;
13701: 			    if ($pack =~ /_0$/) {
13702: 				$unikey='parameter_0_'.$name;
13703: 				$part=0;
13704: 			    } else {
13705: 				$unikey='parameter'.$keyroot.'_'.$name;
13706: 			    }
13707: 			    if ($subp eq 'display') {
13708: 				$value.=' [Part: '.$part.']';
13709: 			    }
13710: 			    $metaentry{':'.$unikey.'.part'}=$part;
13711: 			    $metathesekeys{$unikey}=1;
13712: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
13713: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
13714: 			    }
13715: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
13716: 				$metaentry{':'.$unikey}=
13717: 				    $metaentry{':'.$unikey.'.default'};
13718: 			    }
13719: 			}
13720: 		    }
13721: 		} else {
13722: #
13723: # This is not a package - some other kind of start tag
13724: #
13725: 		    my $entry=$token->[1];
13726: 		    my $unikey='';
13727: 
13728: 		    if ($entry eq 'import') {
13729: #
13730: # Importing a library here
13731: #
13732:                         my $location=$parser->get_text('/import');
13733:                         my $dir=$filename;
13734:                         $dir=~s|[^/]*$||;
13735:                         $location=&filelocation($dir,$location);
13736: 
13737:                         my $importid=$token->[2]->{'id'};
13738:                         my $importmode=$token->[2]->{'importmode'};
13739: #
13740: # Check metadata for imported file to
13741: # see if it contained response items
13742: #
13743:                         my ($origfile,@libfilekeys);
13744:                         my %currmetaentry = %metaentry;
13745:                         @libfilekeys = split(/,/,&metadata($location,'keys',undef,undef,undef,
13746:                                                            $depthcount+1));
13747:                         if (grep(/^responseorder$/,@libfilekeys)) {
13748:                             my $libresponseorder = &metadata($location,'responseorder',undef,undef,
13749:                                                              undef,$depthcount+1);
13750:                             if ($libresponseorder ne '') {
13751:                                 if ($#origfiletagids<0) {
13752:                                     undef(%importedrespids);
13753:                                     undef(%importedpartids);
13754:                                 }
13755:                                 my @respids = split(/\s*,\s*/,$libresponseorder);
13756:                                 if (@respids) {
13757:                                     $importedrespids{$importid} = join(',',map { $importid.'_'.$_ } @respids);
13758:                                 }
13759:                                 if ($importedrespids{$importid} ne '') {
13760:                                     $importedresponses = 1;
13761: # We need to get the original file and the imported file to get the response order correct
13762: # Load and inspect original file
13763:                                     if ($#origfiletagids<0) {
13764:                                         my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
13765:                                         $origfile=&getfile($origfilelocation);
13766:                                         @origfiletagids=($origfile=~/<((?:\w+)response|import|part)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
13767:                                     }
13768:                                 }
13769:                             }
13770:                         }
13771: # Do not overwrite contents of %metaentry hash for resource itself with 
13772: # hash populated for imported library file
13773:                         %metaentry = %currmetaentry;
13774:                         undef(%currmetaentry);
13775:                         if ($importmode eq 'part') {
13776: # Import as part(s)
13777:                            $importedparts=1;
13778: # We need to get the original file and the imported file to get the part order correct
13779: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
13780: # Load and inspect original file if we didn't do that already
13781:                            if ($#origfiletagids<0) {
13782:                                undef(%importedrespids);
13783:                                undef(%importedpartids);
13784:                                if ($origfile eq '') {
13785:                                    my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
13786:                                    $origfile=&getfile($origfilelocation);
13787:                                    @origfiletagids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
13788:                                }
13789:                            }
13790:                            my @impfilepartids;
13791: # If <partorder> tag is included in metadata for the imported file
13792: # get the parts in the imported file from that.
13793:                            if (grep(/^partorder$/,@libfilekeys)) {
13794:                                %currmetaentry = %metaentry;
13795:                                my $libpartorder = &metadata($location,'partorder',undef,undef,undef,
13796:                                                             $depthcount+1);
13797:                                %metaentry = %currmetaentry;
13798:                                undef(%currmetaentry);
13799:                                if ($libpartorder ne '') {
13800:                                    @impfilepartids=split(/\s*,\s*/,$libpartorder);
13801:                                }
13802:                            } else {
13803: # If no <partorder> tag available, load and inspect imported file
13804:                                my $impfile=&getfile($location);
13805:                                @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
13806:                            }
13807:                            if ($#impfilepartids>=0) {
13808: # This problem had parts
13809:                                $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
13810:                            } else {
13811: # Importing by turning a single problem into a problem part
13812: # It gets the import-tags ID as part-ID
13813:                                $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
13814:                                $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
13815:                            }
13816:                         } else {
13817: # Import as problem or as normal import
13818:                             $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
13819:                             unless ($importmode eq 'problem') {
13820: # Normal import
13821:                                 if (defined($token->[2]->{'id'})) {
13822:                                     $unikey.='_'.$token->[2]->{'id'};
13823:                                 }
13824:                             }
13825: # Check metadata for imported file to
13826: # see if it contained parts
13827:                             if (grep(/^partorder$/,@libfilekeys)) {
13828:                                 %currmetaentry = %metaentry;
13829:                                 my $libpartorder = &metadata($location,'partorder',undef,undef,undef,
13830:                                                              $depthcount+1);
13831:                                 %metaentry = %currmetaentry;
13832:                                 undef(%currmetaentry);
13833:                                 if ($libpartorder ne '') {
13834:                                     $importedparts = 1;
13835:                                     $importedpartids{$token->[2]->{'id'}}=$libpartorder;
13836:                                 }
13837:                             }
13838:                         }
13839: 			if ($depthcount<20) {
13840: 			    my $metadata = 
13841: 				&metadata($uri,'keys',$toolsymb,$location,$unikey,
13842: 					  $depthcount+1);
13843: 			    foreach my $meta (split(',',$metadata)) {
13844: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
13845: 				$metathesekeys{$meta}=1;
13846: 			    }
13847:                         }
13848: 		    } else {
13849: #
13850: # Not importing, some other kind of non-package, non-library start tag
13851: # 
13852:                         $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
13853:                         if (defined($token->[2]->{'id'})) {
13854:                             $unikey.='_'.$token->[2]->{'id'};
13855:                         }
13856: 			if (defined($token->[2]->{'name'})) { 
13857: 			    $unikey.='_'.$token->[2]->{'name'}; 
13858: 			}
13859: 			$metathesekeys{$unikey}=1;
13860: 			foreach my $param (@{$token->[3]}) {
13861: 			    $metaentry{':'.$unikey.'.'.$param} =
13862: 				$token->[2]->{$param};
13863: 			}
13864: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
13865: 			my $default=$metaentry{':'.$unikey.'.default'};
13866: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
13867: 		 # only ws inside the tag, and not in default, so use default
13868: 		 # as value
13869: 			    $metaentry{':'.$unikey}=$default;
13870: 			} elsif ( $internaltext =~ /\S/ ) {
13871: 		  # something interesting inside the tag
13872: 			    $metaentry{':'.$unikey}=$internaltext;
13873: 			} else {
13874: 		  # no interesting values, don't set a default
13875: 			}
13876: # end of not-a-package not-a-library import
13877: 		    }
13878: # end of not-a-package start tag
13879: 		}
13880: # the next is the end of "start tag"
13881: 	    }
13882: 	}
13883: 	my ($extension) = ($uri =~ /\.(\w+)$/);
13884: 	$extension = lc($extension);
13885: 	if ($extension eq 'htm') { $extension='html'; }
13886: 
13887: 	foreach my $key (keys(%packagetab)) {
13888: 	    #no specific packages #how's our extension
13889: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
13890: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
13891: 					 \%metathesekeys);
13892: 	}
13893: 
13894: 	if (!exists($metaentry{':packages'})
13895: 	    || $packagetab{"import_defaults&extension_$extension"}) {
13896: 	    foreach my $key (keys(%packagetab)) {
13897: 		#no specific packages well let's get default then
13898: 		if ($key!~/^default&/) { next; }
13899: 		&metadata_create_package_def($uri,$key,'default',
13900: 					     \%metathesekeys);
13901: 	    }
13902: 	}
13903: # are there custom rights to evaluate
13904: 	if ($metaentry{':copyright'} eq 'custom') {
13905: 
13906:     #
13907:     # Importing a rights file here
13908:     #
13909: 	    unless ($depthcount) {
13910: 		my $location=$metaentry{':customdistributionfile'};
13911: 		my $dir=$filename;
13912: 		$dir=~s|[^/]*$||;
13913: 		$location=&filelocation($dir,$location);
13914: 		my $rights_metadata =
13915: 		    &metadata($uri,'keys',$toolsymb,$location,'_rights',
13916: 			      $depthcount+1);
13917: 		foreach my $rights (split(',',$rights_metadata)) {
13918: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
13919: 		    $metathesekeys{$rights}=1;
13920: 		}
13921: 	    }
13922: 	}
13923: 	# uniqifiy package listing
13924: 	my %seen;
13925: 	my @uniq_packages =
13926: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
13927: 	$metaentry{':packages'} = join(',',@uniq_packages);
13928: 
13929:         if (($importedresponses) || ($importedparts)) {
13930:             if ($importedparts) {
13931: # We had imported parts and need to rebuild partorder
13932:                 $metaentry{':partorder'}='';
13933:                 $metathesekeys{'partorder'}=1;
13934:             }
13935:             if ($importedresponses) {
13936: # We had imported responses and need to rebuil responseorder
13937:                 $metaentry{':responseorder'}='';
13938:                 $metathesekeys{'responseorder'}=1;
13939:             }
13940:             for (my $index=0;$index<$#origfiletagids;$index+=2) {
13941:                 my $origid = $origfiletagids[$index+1];
13942:                 if ($origfiletagids[$index] eq 'part') {
13943: # Original part, part of the problem
13944:                     if ($importedparts) {
13945:                         $metaentry{':partorder'}.=','.$origid;
13946:                     }
13947:                 } elsif ($origfiletagids[$index] eq 'import') {
13948:                     if ($importedparts) {
13949: # We have imported parts at this position
13950:                         if ($importedpartids{$origid} ne '') {
13951:                             $metaentry{':partorder'}.=','.$importedpartids{$origid};
13952:                         }
13953:                     }
13954:                     if ($importedresponses) {
13955: # We have imported responses at this position
13956:                         if ($importedrespids{$origid} ne '') {
13957:                             $metaentry{':responseorder'}.=','.$importedrespids{$origid};
13958:                         }
13959:                     }
13960:                 } else {
13961: # Original response item, part of the problem
13962:                     if ($importedresponses) {
13963:                         $metaentry{':responseorder'}.=','.$origid;
13964:                     }
13965:                 }
13966:             }
13967:             if ($importedparts) {
13968:                 $metaentry{':partorder'}=~s/^\,//;
13969:             }
13970:             if ($importedresponses) {
13971:                 $metaentry{':responseorder'}=~s/^\,//;
13972:             }
13973:         }
13974: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
13975: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
13976: 	$metaentry{':allpossiblekeys'}=join(',',keys(%metathesekeys));
13977:         unless ($liburi) {
13978: 	    &do_cache_new('meta',$uri,\%metaentry,$cachetime);
13979:         }
13980: # this is the end of "was not already recently cached
13981:     }
13982:     return $metaentry{':'.$what};
13983: }
13984: 
13985: sub metadata_create_package_def {
13986:     my ($uri,$key,$package,$metathesekeys)=@_;
13987:     my ($pack,$name,$subp)=split(/\&/,$key);
13988:     if ($subp eq 'default') { next; }
13989:     
13990:     if (defined($metaentry{':packages'})) {
13991: 	$metaentry{':packages'}.=','.$package;
13992:     } else {
13993: 	$metaentry{':packages'}=$package;
13994:     }
13995:     my $value=$packagetab{$key};
13996:     my $unikey;
13997:     $unikey='parameter_0_'.$name;
13998:     $metaentry{':'.$unikey.'.part'}=0;
13999:     $$metathesekeys{$unikey}=1;
14000:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
14001: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
14002:     }
14003:     if (defined($metaentry{':'.$unikey.'.default'})) {
14004: 	$metaentry{':'.$unikey}=
14005: 	    $metaentry{':'.$unikey.'.default'};
14006:     }
14007: }
14008: 
14009: sub metadata_generate_part0 {
14010:     my ($metadata,$metacache,$uri) = @_;
14011:     my %allnames;
14012:     foreach my $metakey (keys(%$metadata)) {
14013: 	if ($metakey=~/^parameter\_(.*)/) {
14014: 	  my $part=$$metacache{':'.$metakey.'.part'};
14015: 	  my $name=$$metacache{':'.$metakey.'.name'};
14016: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
14017: 	    $allnames{$name}=$part;
14018: 	  }
14019: 	}
14020:     }
14021:     foreach my $name (keys(%allnames)) {
14022:       $$metadata{"parameter_0_$name"}=1;
14023:       my $key=":parameter_0_$name";
14024:       $$metacache{"$key.part"}='0';
14025:       $$metacache{"$key.name"}=$name;
14026:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
14027: 					   $allnames{$name}.'_'.$name.
14028: 					   '.type'};
14029:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
14030: 			     '.display'};
14031:       my $expr='[Part: '.$allnames{$name}.']';
14032:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
14033:       $$metacache{"$key.display"}=$olddis;
14034:     }
14035: }
14036: 
14037: # ------------------------------------------------------ Devalidate title cache
14038: 
14039: sub devalidate_title_cache {
14040:     my ($url)=@_;
14041:     if (!$env{'request.course.id'}) { return; }
14042:     my $symb=&symbread($url);
14043:     if (!$symb) { return; }
14044:     my $key=$env{'request.course.id'}."\0".$symb;
14045:     &devalidate_cache_new('title',$key);
14046: }
14047: 
14048: # ------------------------------------------------- Get the title of a course
14049: 
14050: sub current_course_title {
14051:     return $env{ 'course.' . $env{'request.course.id'} . '.description' };
14052: }
14053: # ------------------------------------------------- Get the title of a resource
14054: 
14055: sub gettitle {
14056:     my $urlsymb=shift;
14057:     my $symb=&symbread($urlsymb);
14058:     if ($symb) {
14059: 	my $key=$env{'request.course.id'}."\0".$symb;
14060: 	my ($result,$cached)=&is_cached_new('title',$key);
14061: 	if (defined($cached)) { 
14062: 	    return $result;
14063: 	}
14064: 	my ($map,$resid,$url)=&decode_symb($symb);
14065: 	my $title='';
14066: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
14067: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
14068: 	} else {
14069: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
14070: 		    &GDBM_READER(),0640)) {
14071: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
14072: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
14073: 		untie(%bighash);
14074: 	    }
14075: 	}
14076: 	$title=~s/\&colon\;/\:/gs;
14077: 	if ($title) {
14078: # Remember both $symb and $title for dynamic metadata
14079:             $accesshash{$symb.'___crstitle'}=$title;
14080:             $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
14081: # Cache this title and then return it
14082: 	    return &do_cache_new('title',$key,$title,600);
14083: 	}
14084: 	$urlsymb=$url;
14085:     }
14086:     my $title=&metadata($urlsymb,'title');
14087:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
14088:     return $title;
14089: }
14090: 
14091: sub get_slot {
14092:     my ($which,$cnum,$cdom)=@_;
14093:     if (!$cnum || !$cdom) {
14094: 	(undef,my $courseid)=&whichuser();
14095: 	$cdom=$env{'course.'.$courseid.'.domain'};
14096: 	$cnum=$env{'course.'.$courseid.'.num'};
14097:     }
14098:     my $key=join("\0",'slots',$cdom,$cnum,$which);
14099:     my %slotinfo;
14100:     if (exists($remembered{$key})) {
14101: 	$slotinfo{$which} = $remembered{$key};
14102:     } else {
14103: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
14104: 	&Apache::lonhomework::showhash(%slotinfo);
14105: 	my ($tmp)=keys(%slotinfo);
14106: 	if ($tmp=~/^error:/) { return (); }
14107: 	$remembered{$key} = $slotinfo{$which};
14108:     }
14109:     if (ref($slotinfo{$which}) eq 'HASH') {
14110: 	return %{$slotinfo{$which}};
14111:     }
14112:     return $slotinfo{$which};
14113: }
14114: 
14115: sub get_reservable_slots {
14116:     my ($cnum,$cdom,$uname,$udom) = @_;
14117:     my $now = time;
14118:     my $reservable_info;
14119:     my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
14120:     if (exists($remembered{$key})) {
14121:         $reservable_info = $remembered{$key};
14122:     } else {
14123:         my %resv;
14124:         ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
14125:         &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
14126:         $reservable_info = \%resv;
14127:         $remembered{$key} = $reservable_info;
14128:     }
14129:     return $reservable_info;
14130: }
14131: 
14132: sub get_course_slots {
14133:     my ($cnum,$cdom) = @_;
14134:     my $hashid=$cnum.':'.$cdom;
14135:     my ($result,$cached) = &is_cached_new('allslots',$hashid);
14136:     if (defined($cached)) {
14137:         if (ref($result) eq 'HASH') {
14138:             return %{$result};
14139:         }
14140:     } else {
14141:         my %slots=&dump('slots',$cdom,$cnum);
14142:         my ($tmp) = keys(%slots);
14143:         if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
14144:             &do_cache_new('allslots',$hashid,\%slots,600);
14145:             return %slots;
14146:         }
14147:     }
14148:     return;
14149: }
14150: 
14151: sub devalidate_slots_cache {
14152:     my ($cnum,$cdom)=@_;
14153:     my $hashid=$cnum.':'.$cdom;
14154:     &devalidate_cache_new('allslots',$hashid);
14155: }
14156: 
14157: sub get_coursechange {
14158:     my ($cdom,$cnum) = @_;
14159:     if ($cdom eq '' || $cnum eq '') {
14160:         return unless ($env{'request.course.id'});
14161:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
14162:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
14163:     }
14164:     my $hashid=$cdom.'_'.$cnum;
14165:     my ($change,$cached)=&is_cached_new('crschange',$hashid);
14166:     if ((defined($cached)) && ($change ne '')) {
14167:         return $change;
14168:     } else {
14169:         my %crshash;
14170:         %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
14171:         if ($crshash{'internal.contentchange'} eq '') {
14172:             $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
14173:             if ($change eq '') {
14174:                 %crshash = &get('environment',['internal.created'],$cdom,$cnum);
14175:                 $change = $crshash{'internal.created'};
14176:             }
14177:         } else {
14178:             $change = $crshash{'internal.contentchange'};
14179:         }
14180:         my $cachetime = 600;
14181:         &do_cache_new('crschange',$hashid,$change,$cachetime);
14182:     }
14183:     return $change;
14184: }
14185: 
14186: sub devalidate_coursechange_cache {
14187:     my ($cdom,$cnum)=@_;
14188:     my $hashid=$cdom.'_'.$cnum;
14189:     &devalidate_cache_new('crschange',$hashid);
14190: }
14191: 
14192: sub get_suppchange {
14193:     my ($cdom,$cnum) = @_;
14194:     if ($cdom eq '' || $cnum eq '') {
14195:         return unless ($env{'request.course.id'});
14196:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
14197:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
14198:     }
14199:     my $hashid=$cdom.'_'.$cnum;
14200:     my ($change,$cached)=&is_cached_new('suppchange',$hashid);
14201:     if ((defined($cached)) && ($change ne '')) {
14202:         return $change;
14203:     } else {
14204:         my %crshash = &get('environment',['internal.supplementalchange'],$cdom,$cnum);
14205:         if ($crshash{'internal.supplementalchange'} eq '') {
14206:             $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
14207:             if ($change eq '') {
14208:                 %crshash = &get('environment',['internal.created'],$cdom,$cnum);
14209:                 $change = $crshash{'internal.created'};
14210:             }
14211:         } else {
14212:             $change = $crshash{'internal.supplementalchange'};
14213:         }
14214:         my $cachetime = 600;
14215:         &do_cache_new('suppchange',$hashid,$change,$cachetime);
14216:     }
14217:     return $change;
14218: }
14219: 
14220: sub devalidate_suppchange_cache {
14221:     my ($cdom,$cnum)=@_;
14222:     my $hashid=$cdom.'_'.$cnum;
14223:     &devalidate_cache_new('suppchange',$hashid);
14224: }
14225: 
14226: sub update_supp_caches {
14227:     my ($cdom,$cnum) = @_;
14228:     my %servers = &internet_dom_servers($cdom);
14229:     my @ids=&current_machine_ids();
14230:     foreach my $server (keys(%servers)) {
14231:         next if (grep(/^\Q$server\E$/,@ids));
14232:         my $hashid=$cnum.':'.$cdom;
14233:         my $cachekey = &escape('showsupp').':'.&escape($hashid);
14234:         &remote_devalidate_cache($server,[$cachekey]);
14235:     }
14236:     &has_unhidden_suppfiles($cnum,$cdom,1,1);
14237:     &count_supptools($cnum,$cdom,1);
14238:     my $now = time;
14239:     if ($env{'request.course.id'} eq $cdom.'_'.$cnum) {
14240:         &Apache::lonnet::appenv({'request.course.suppupdated' => $now});
14241:     }
14242:     &put('environment',{'internal.supplementalchange' => $now},
14243:          $cdom,$cnum);
14244:     &Apache::lonnet::appenv(
14245:         {'course.'.$cdom.'_'.$cnum.'.internal.supplementalchange' => $now});
14246:     &do_cache_new('suppchange',$cdom.'_'.$cnum,$now,600);
14247: }
14248: 
14249: # ------------------------------------------------- Update symbolic store links
14250: 
14251: sub symblist {
14252:     my ($mapname,%newhash)=@_;
14253:     $mapname=&deversion(&declutter($mapname));
14254:     my %hash;
14255:     if (($env{'request.course.fn'}) && (%newhash)) {
14256:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
14257:                       &GDBM_WRCREAT(),0640)) {
14258: 	    foreach my $url (keys(%newhash)) {
14259: 		next if ($url eq 'last_known'
14260: 			 && $env{'form.no_update_last_known'});
14261: 		$hash{declutter($url)}=&encode_symb($mapname,
14262: 						    $newhash{$url}->[1],
14263: 						    $newhash{$url}->[0]);
14264:             }
14265:             if (untie(%hash)) {
14266: 		return 'ok';
14267:             }
14268:         }
14269:     }
14270:     return 'error';
14271: }
14272: 
14273: # --------------------------------------------------------------- Verify a symb
14274: 
14275: sub symbverify {
14276:     my ($symb,$thisurl,$encstate)=@_;
14277:     my $thisfn=$thisurl;
14278:     $thisfn=&declutter($thisfn);
14279: # direct jump to resource in page or to a sequence - will construct own symbs
14280:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
14281: # check URL part
14282:     my ($map,$resid,$url)=&decode_symb($symb);
14283: 
14284:     unless ($url eq $thisfn) { return 0; }
14285: 
14286:     $symb=&symbclean($symb);
14287:     $thisurl=&deversion($thisurl);
14288:     $thisfn=&deversion($thisfn);
14289: 
14290:     my %bighash;
14291:     my $okay=0;
14292: 
14293:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
14294:                             &GDBM_READER(),0640)) {
14295:         if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
14296:             $thisurl =~ s/\?.+$//;
14297:             if ($map =~ m{^uploaded/.+\.page$}) {
14298:                 $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
14299:                 $thisurl =~ s{^\Qhttp://https://\E}{https://};
14300:             }
14301:         }
14302:         my $ids;
14303:         if ($map =~ m{^uploaded/.+\.page$}) {
14304:             $ids=$bighash{'ids_'.&clutter_with_no_wrapper($thisurl)};
14305:         } else {
14306:             $ids=$bighash{'ids_'.&clutter($thisurl)};
14307:         }
14308:         unless ($ids) {
14309:             my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;  
14310:             $ids=$bighash{$idkey};
14311:         }
14312:         if ($ids) {
14313: # ------------------------------------------------------------------- Has ID(s)
14314:             if ($thisfn =~ m{^/adm/wrapper/ext/}) {
14315:                 $symb =~ s/\?.+$//;
14316:             }
14317: 	    foreach my $id (split(/\,/,$ids)) {
14318: 	       my ($mapid,$resid)=split(/\./,$id);
14319:                if (
14320:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
14321:    eq $symb) {
14322:                    if (ref($encstate)) {
14323:                        $$encstate = $bighash{'encrypted_'.$id};
14324:                    }
14325: 		   if (($env{'request.role.adv'}) ||
14326: 		       ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
14327:                        ($thisurl eq '/adm/navmaps')) {
14328: 		       $okay=1;
14329:                        last;
14330: 		   }
14331: 	       }
14332: 	   }
14333:         }
14334: 	untie(%bighash);
14335:     }
14336:     return $okay;
14337: }
14338: 
14339: # --------------------------------------------------------------- Clean-up symb
14340: 
14341: sub symbclean {
14342:     my $symb=shift;
14343:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
14344: # remove version from map
14345:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
14346: 
14347: # remove version from URL
14348:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
14349: 
14350: # remove wrapper
14351: 
14352:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
14353:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
14354:     return $symb;
14355: }
14356: 
14357: # ---------------------------------------------- Split symb to find map and url
14358: 
14359: sub encode_symb {
14360:     my ($map,$resid,$url)=@_;
14361:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
14362: }
14363: 
14364: sub decode_symb {
14365:     my $symb=shift;
14366:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
14367:     my ($map,$resid,$url)=split(/___/,$symb);
14368:     return (&fixversion($map),$resid,&fixversion($url));
14369: }
14370: 
14371: sub fixversion {
14372:     my $fn=shift;
14373:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
14374:     my %bighash;
14375:     my $uri=&clutter($fn);
14376:     my $key=$env{'request.course.id'}.'_'.$uri;
14377: # is this cached?
14378:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
14379:     if (defined($cached)) { return $result; }
14380: # unfortunately not cached, or expired
14381:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
14382: 	    &GDBM_READER(),0640)) {
14383:  	if ($bighash{'version_'.$uri}) {
14384:  	    my $version=$bighash{'version_'.$uri};
14385:  	    unless (($version eq 'mostrecent') || 
14386: 		    ($version==&getversion($uri))) {
14387:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
14388:  	    }
14389:  	}
14390:  	untie %bighash;
14391:     }
14392:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
14393: }
14394: 
14395: sub deversion {
14396:     my $url=shift;
14397:     $url=~s/\.\d+\.(\w+)$/\.$1/;
14398:     return $url;
14399: }
14400: 
14401: # ------------------------------------------------------ Return symb list entry
14402: 
14403: sub symbread {
14404:     my ($thisfn,$donotrecurse,$ignorecachednull,$checkforblock,$possibles,
14405:         $ignoresymbdb,$noenccheck)=@_;
14406:     my $cache_str='request.symbread.cached.'.$thisfn;
14407:     if (defined($env{$cache_str})) {
14408:         unless (ref($possibles) eq 'HASH') {
14409:             if ($ignorecachednull) {
14410:                 return $env{$cache_str} unless ($env{$cache_str} eq '');
14411:             } else {
14412:                 return $env{$cache_str};
14413:             }
14414:         }
14415:     }
14416: # no filename provided? try from environment
14417:     unless ($thisfn) {
14418:         if ($env{'request.symb'}) {
14419:             return $env{$cache_str}=&symbclean($env{'request.symb'});
14420: 	}
14421: 	$thisfn=$env{'request.filename'};
14422:     }
14423:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
14424: # is that filename actually a symb? Verify, clean, and return
14425:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
14426: 	if (&symbverify($thisfn,$1)) {
14427: 	    return $env{$cache_str}=&symbclean($thisfn);
14428: 	}
14429:     }
14430:     $thisfn=declutter($thisfn);
14431:     my %hash;
14432:     my %bighash;
14433:     my $syval='';
14434:     if (($env{'request.course.fn'}) && ($thisfn)) {
14435:         unless ($ignoresymbdb) {
14436:             if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
14437:                           &GDBM_READER(),0640)) {
14438: 	        $syval=$hash{$thisfn};
14439:                 untie(%hash);
14440:             }
14441:             if ($syval && $checkforblock) {
14442:                 my @blockers = &has_comm_blocking('bre',$syval,$thisfn,$ignoresymbdb,$noenccheck);
14443:                 if (@blockers) {
14444:                     $syval='';
14445:                 }
14446:             }
14447:         }
14448: # ---------------------------------------------------------- There was an entry
14449:         if ($syval) {
14450: 	    #unless ($syval=~/\_\d+$/) {
14451: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
14452: 		    #&appenv({'request.ambiguous' => $thisfn});
14453: 		    #return $env{$cache_str}='';
14454: 		#}    
14455: 		#$syval.=$1;
14456: 	    #}
14457:         } else {
14458: # ------------------------------------------------------- Was not in symb table
14459:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
14460:                             &GDBM_READER(),0640)) {
14461: # ---------------------------------------------- Get ID(s) for current resource
14462:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
14463:               unless ($ids) { 
14464:                  $ids=$bighash{'ids_/'.$thisfn};
14465:               }
14466:               unless ($ids) {
14467: # alias?
14468: 		  $ids=$bighash{'mapalias_'.$thisfn};
14469:               }
14470:               if ($ids) {
14471: # ------------------------------------------------------------------- Has ID(s)
14472:                  my @possibilities=split(/\,/,$ids);
14473:                  if ($#possibilities==0) {
14474: # ----------------------------------------------- There is only one possibility
14475: 		     my ($mapid,$resid)=split(/\./,$ids);
14476: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
14477: 						    $resid,$thisfn);
14478:                      if (ref($possibles) eq 'HASH') {
14479:                          unless ($bighash{'randomout_'.$ids} || $env{'request.role.adv'}) {
14480:                              $possibles->{$syval} = 1;
14481:                          }
14482:                      }
14483:                      if ($checkforblock) {
14484:                          unless ($bighash{'randomout_'.$ids} || $env{'request.role.adv'}) {
14485:                              my @blockers = &has_comm_blocking('bre',$syval,$bighash{'src_'.$ids},'',$noenccheck);
14486:                              if (@blockers) {
14487:                                  $syval = '';
14488:                                  untie(%bighash);
14489:                                  return $env{$cache_str}='';
14490:                              }
14491:                          }
14492:                      }
14493:                  } elsif ((!$donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) { 
14494: # ------------------------------------------ There is more than one possibility
14495:                      my $realpossible=0;
14496:                      foreach my $id (@possibilities) {
14497: 			 my $file=$bighash{'src_'.$id};
14498:                          my $canaccess;
14499:                          if (($donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
14500:                              $canaccess = 1;
14501:                          } else { 
14502:                              $canaccess = &allowed('bre',$file);
14503:                          }
14504:                          if ($canaccess) {
14505:          		     my ($mapid,$resid)=split(/\./,$id);
14506:                              if ($bighash{'map_type_'.$mapid} ne 'page') {
14507:                                  my $poss_syval=&encode_symb($bighash{'map_id_'.$mapid},
14508: 						             $resid,$thisfn);
14509:                                  next if ($bighash{'randomout_'.$id} && !$env{'request.role.adv'});
14510:                                  next unless (($noenccheck) || ($bighash{'encrypted_'.$id} eq $env{'request.enc'}));
14511:                                  if ($checkforblock) {
14512:                                      my @blockers = &has_comm_blocking('bre',$poss_syval,$file,'',$noenccheck);
14513:                                      if (@blockers > 0) {
14514:                                          $syval = '';
14515:                                      } else {
14516:                                          $syval = $poss_syval;
14517:                                          $realpossible++;
14518:                                      }
14519:                                  } else {
14520:                                      $syval = $poss_syval;
14521:                                      $realpossible++;
14522:                                  }
14523:                                  if ($syval) {
14524:                                      if (ref($possibles) eq 'HASH') {
14525:                                          $possibles->{$syval} = 1;
14526:                                      }
14527:                                  }
14528:                              }
14529: 			 }
14530:                      }
14531: 		     if ($realpossible!=1) { $syval=''; }
14532:                  } else {
14533:                      $syval='';
14534:                  }
14535: 	      }
14536:               untie(%bighash);
14537:            }
14538:         }
14539:         if ($syval) {
14540: 	    return $env{$cache_str}=$syval;
14541:         }
14542:     }
14543:     &appenv({'request.ambiguous' => $thisfn});
14544:     return $env{$cache_str}='';
14545: }
14546: 
14547: # ---------------------------------------------------------- Return random seed
14548: 
14549: sub numval {
14550:     my $txt=shift;
14551:     $txt=~tr/A-J/0-9/;
14552:     $txt=~tr/a-j/0-9/;
14553:     $txt=~tr/K-T/0-9/;
14554:     $txt=~tr/k-t/0-9/;
14555:     $txt=~tr/U-Z/0-5/;
14556:     $txt=~tr/u-z/0-5/;
14557:     $txt=~s/\D//g;
14558:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
14559:     return int($txt);
14560: }
14561: 
14562: sub numval2 {
14563:     my $txt=shift;
14564:     $txt=~tr/A-J/0-9/;
14565:     $txt=~tr/a-j/0-9/;
14566:     $txt=~tr/K-T/0-9/;
14567:     $txt=~tr/k-t/0-9/;
14568:     $txt=~tr/U-Z/0-5/;
14569:     $txt=~tr/u-z/0-5/;
14570:     $txt=~s/\D//g;
14571:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
14572:     my $total;
14573:     foreach my $val (@txts) { $total+=$val; }
14574:     if ($_64bit) { if ($total > 2**32) { return -1; } }
14575:     return int($total);
14576: }
14577: 
14578: sub numval3 {
14579:     use integer;
14580:     my $txt=shift;
14581:     $txt=~tr/A-J/0-9/;
14582:     $txt=~tr/a-j/0-9/;
14583:     $txt=~tr/K-T/0-9/;
14584:     $txt=~tr/k-t/0-9/;
14585:     $txt=~tr/U-Z/0-5/;
14586:     $txt=~tr/u-z/0-5/;
14587:     $txt=~s/\D//g;
14588:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
14589:     my $total;
14590:     foreach my $val (@txts) { $total+=$val; }
14591:     if ($_64bit) { $total=(($total<<32)>>32); }
14592:     return $total;
14593: }
14594: 
14595: sub digest {
14596:     my ($data)=@_;
14597:     my $digest=&Digest::MD5::md5($data);
14598:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
14599:     my ($e,$f);
14600:     {
14601:         use integer;
14602:         $e=($a+$b);
14603:         $f=($c+$d);
14604:         if ($_64bit) {
14605:             $e=(($e<<32)>>32);
14606:             $f=(($f<<32)>>32);
14607:         }
14608:     }
14609:     if (wantarray) {
14610: 	return ($e,$f);
14611:     } else {
14612: 	my $g;
14613: 	{
14614: 	    use integer;
14615: 	    $g=($e+$f);
14616: 	    if ($_64bit) {
14617: 		$g=(($g<<32)>>32);
14618: 	    }
14619: 	}
14620: 	return $g;
14621:     }
14622: }
14623: 
14624: sub latest_rnd_algorithm_id {
14625:     return '64bit5';
14626: }
14627: 
14628: sub get_rand_alg {
14629:     my ($courseid)=@_;
14630:     if (!$courseid) { $courseid=(&whichuser())[1]; }
14631:     if ($courseid) {
14632: 	return $env{"course.$courseid.rndseed"};
14633:     }
14634:     return &latest_rnd_algorithm_id();
14635: }
14636: 
14637: sub validCODE {
14638:     my ($CODE)=@_;
14639:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
14640:     return 0;
14641: }
14642: 
14643: sub getCODE {
14644:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
14645:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
14646: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
14647: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
14648: 	return $Apache::lonhomework::history{'resource.CODE'};
14649:     }
14650:     return undef;
14651: }
14652: #
14653: #  Determines the random seed for a specific context:
14654: #
14655: # parameters:
14656: #   symb      - in course context the symb for the seed.
14657: #   course_id - The course id of the form domain_coursenum.
14658: #   domain    - Domain for the user.
14659: #   course    - Course for the user.
14660: #   cenv      - environment of the course.
14661: #
14662: # NOTE:
14663: #   All parameters are picked out of the environment if missing
14664: #   or not defined.
14665: #   If a symb cannot be determined the current time is used instead.
14666: #
14667: #  For a given well defined symb, courside, domain, username,
14668: #  and course environment, the seed is reproducible.
14669: #
14670: sub rndseed {
14671:     my ($symb,$courseid,$domain,$username, $cenv)=@_;
14672:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
14673:     if (!defined($symb)) {
14674: 	unless ($symb=$wsymb) { return time; }
14675:     }
14676:     if (!defined $courseid) { 
14677: 	$courseid=$wcourseid; 
14678:     }
14679:     if (!defined $domain) { $domain=$wdomain; }
14680:     if (!defined $username) { $username=$wusername }
14681: 
14682:     my $which;
14683:     if (defined($cenv->{'rndseed'})) {
14684: 	$which = $cenv->{'rndseed'};
14685:     } else {
14686: 	$which =&get_rand_alg($courseid);
14687:     }
14688:     if (defined(&getCODE())) {
14689: 
14690: 	if ($which eq '64bit5') {
14691: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
14692: 	} elsif ($which eq '64bit4') {
14693: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
14694: 	} else {
14695: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
14696: 	}
14697:     } elsif ($which eq '64bit5') {
14698: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
14699:     } elsif ($which eq '64bit4') {
14700: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
14701:     } elsif ($which eq '64bit3') {
14702: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
14703:     } elsif ($which eq '64bit2') {
14704: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
14705:     } elsif ($which eq '64bit') {
14706: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
14707:     }
14708:     return &rndseed_32bit($symb,$courseid,$domain,$username);
14709: }
14710: 
14711: sub rndseed_32bit {
14712:     my ($symb,$courseid,$domain,$username)=@_;
14713:     {
14714: 	use integer;
14715: 	my $symbchck=unpack("%32C*",$symb) << 27;
14716: 	my $symbseed=numval($symb) << 22;
14717: 	my $namechck=unpack("%32C*",$username) << 17;
14718: 	my $nameseed=numval($username) << 12;
14719: 	my $domainseed=unpack("%32C*",$domain) << 7;
14720: 	my $courseseed=unpack("%32C*",$courseid);
14721: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
14722: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
14723: 	#&logthis("rndseed :$num:$symb");
14724: 	if ($_64bit) { $num=(($num<<32)>>32); }
14725: 	return $num;
14726:     }
14727: }
14728: 
14729: sub rndseed_64bit {
14730:     my ($symb,$courseid,$domain,$username)=@_;
14731:     {
14732: 	use integer;
14733: 	my $symbchck=unpack("%32S*",$symb) << 21;
14734: 	my $symbseed=numval($symb) << 10;
14735: 	my $namechck=unpack("%32S*",$username);
14736: 	
14737: 	my $nameseed=numval($username) << 21;
14738: 	my $domainseed=unpack("%32S*",$domain) << 10;
14739: 	my $courseseed=unpack("%32S*",$courseid);
14740: 	
14741: 	my $num1=$symbchck+$symbseed+$namechck;
14742: 	my $num2=$nameseed+$domainseed+$courseseed;
14743: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
14744: 	#&logthis("rndseed :$num:$symb");
14745: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
14746: 	return "$num1,$num2";
14747:     }
14748: }
14749: 
14750: sub rndseed_64bit2 {
14751:     my ($symb,$courseid,$domain,$username)=@_;
14752:     {
14753: 	use integer;
14754: 	# strings need to be an even # of cahracters long, it it is odd the
14755:         # last characters gets thrown away
14756: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
14757: 	my $symbseed=numval($symb) << 10;
14758: 	my $namechck=unpack("%32S*",$username.' ');
14759: 	
14760: 	my $nameseed=numval($username) << 21;
14761: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
14762: 	my $courseseed=unpack("%32S*",$courseid.' ');
14763: 	
14764: 	my $num1=$symbchck+$symbseed+$namechck;
14765: 	my $num2=$nameseed+$domainseed+$courseseed;
14766: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
14767: 	#&logthis("rndseed :$num:$symb");
14768: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
14769: 	return "$num1,$num2";
14770:     }
14771: }
14772: 
14773: sub rndseed_64bit3 {
14774:     my ($symb,$courseid,$domain,$username)=@_;
14775:     {
14776: 	use integer;
14777: 	# strings need to be an even # of cahracters long, it it is odd the
14778:         # last characters gets thrown away
14779: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
14780: 	my $symbseed=numval2($symb) << 10;
14781: 	my $namechck=unpack("%32S*",$username.' ');
14782: 	
14783: 	my $nameseed=numval2($username) << 21;
14784: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
14785: 	my $courseseed=unpack("%32S*",$courseid.' ');
14786: 	
14787: 	my $num1=$symbchck+$symbseed+$namechck;
14788: 	my $num2=$nameseed+$domainseed+$courseseed;
14789: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
14790: 	#&logthis("rndseed :$num1:$num2:$_64bit");
14791: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
14792: 	
14793: 	return "$num1:$num2";
14794:     }
14795: }
14796: 
14797: sub rndseed_64bit4 {
14798:     my ($symb,$courseid,$domain,$username)=@_;
14799:     {
14800: 	use integer;
14801: 	# strings need to be an even # of cahracters long, it it is odd the
14802:         # last characters gets thrown away
14803: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
14804: 	my $symbseed=numval3($symb) << 10;
14805: 	my $namechck=unpack("%32S*",$username.' ');
14806: 	
14807: 	my $nameseed=numval3($username) << 21;
14808: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
14809: 	my $courseseed=unpack("%32S*",$courseid.' ');
14810: 	
14811: 	my $num1=$symbchck+$symbseed+$namechck;
14812: 	my $num2=$nameseed+$domainseed+$courseseed;
14813: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
14814: 	#&logthis("rndseed :$num1:$num2:$_64bit");
14815: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
14816: 	
14817: 	return "$num1:$num2";
14818:     }
14819: }
14820: 
14821: sub rndseed_64bit5 {
14822:     my ($symb,$courseid,$domain,$username)=@_;
14823:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
14824:     return "$num1:$num2";
14825: }
14826: 
14827: sub rndseed_CODE_64bit {
14828:     my ($symb,$courseid,$domain,$username)=@_;
14829:     {
14830: 	use integer;
14831: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
14832: 	my $symbseed=numval2($symb);
14833: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
14834: 	my $CODEseed=numval(&getCODE());
14835: 	my $courseseed=unpack("%32S*",$courseid.' ');
14836: 	my $num1=$symbseed+$CODEchck;
14837: 	my $num2=$CODEseed+$courseseed+$symbchck;
14838: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
14839: 	#&logthis("rndseed :$num1:$num2:$symb");
14840: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
14841: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
14842: 	return "$num1:$num2";
14843:     }
14844: }
14845: 
14846: sub rndseed_CODE_64bit4 {
14847:     my ($symb,$courseid,$domain,$username)=@_;
14848:     {
14849: 	use integer;
14850: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
14851: 	my $symbseed=numval3($symb);
14852: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
14853: 	my $CODEseed=numval3(&getCODE());
14854: 	my $courseseed=unpack("%32S*",$courseid.' ');
14855: 	my $num1=$symbseed+$CODEchck;
14856: 	my $num2=$CODEseed+$courseseed+$symbchck;
14857: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
14858: 	#&logthis("rndseed :$num1:$num2:$symb");
14859: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
14860: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
14861: 	return "$num1:$num2";
14862:     }
14863: }
14864: 
14865: sub rndseed_CODE_64bit5 {
14866:     my ($symb,$courseid,$domain,$username)=@_;
14867:     my $code = &getCODE();
14868:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
14869:     return "$num1:$num2";
14870: }
14871: 
14872: sub setup_random_from_rndseed {
14873:     my ($rndseed)=@_;
14874:     if ($rndseed =~/([,:])/) {
14875:         my ($num1,$num2) = map { abs($_); } (split(/[,:]/,$rndseed));
14876:         if ((!$num1) || (!$num2) || ($num1 > 2147483562) || ($num2 > 2147483398)) {
14877:             &Math::Random::random_set_seed_from_phrase($rndseed);
14878:         } else {
14879:             &Math::Random::random_set_seed($num1,$num2);
14880:         }
14881:     } else {
14882: 	&Math::Random::random_set_seed_from_phrase($rndseed);
14883:     }
14884: }
14885: 
14886: sub latest_receipt_algorithm_id {
14887:     return 'receipt3';
14888: }
14889: 
14890: sub recunique {
14891:     my $fucourseid=shift;
14892:     my $unique;
14893:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
14894: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
14895: 	$unique=$env{"course.$fucourseid.internal.encseed"};
14896:     } else {
14897: 	$unique=$perlvar{'lonReceipt'};
14898:     }
14899:     return unpack("%32C*",$unique);
14900: }
14901: 
14902: sub recprefix {
14903:     my $fucourseid=shift;
14904:     my $prefix;
14905:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
14906: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
14907: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
14908:     } else {
14909: 	$prefix=$perlvar{'lonHostID'};
14910:     }
14911:     return unpack("%32C*",$prefix);
14912: }
14913: 
14914: sub ireceipt {
14915:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
14916: 
14917:     my $return =&recprefix($fucourseid).'-';
14918: 
14919:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
14920: 	$env{'request.state'} eq 'construct') {
14921: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
14922: 	return $return;
14923:     }
14924: 
14925:     my $cuname=unpack("%32C*",$funame);
14926:     my $cudom=unpack("%32C*",$fudom);
14927:     my $cucourseid=unpack("%32C*",$fucourseid);
14928:     my $cusymb=unpack("%32C*",$fusymb);
14929:     my $cunique=&recunique($fucourseid);
14930:     my $cpart=unpack("%32S*",$part);
14931:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
14932: 
14933: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
14934: 			       
14935: 	$return.= ($cunique%$cuname+
14936: 		   $cunique%$cudom+
14937: 		   $cusymb%$cuname+
14938: 		   $cusymb%$cudom+
14939: 		   $cucourseid%$cuname+
14940: 		   $cucourseid%$cudom+
14941: 		   $cpart%$cuname+
14942: 		   $cpart%$cudom);
14943:     } else {
14944: 	$return.= ($cunique%$cuname+
14945: 		   $cunique%$cudom+
14946: 		   $cusymb%$cuname+
14947: 		   $cusymb%$cudom+
14948: 		   $cucourseid%$cuname+
14949: 		   $cucourseid%$cudom);
14950:     }
14951:     return $return;
14952: }
14953: 
14954: sub receipt {
14955:     my ($part)=@_;
14956:     my ($symb,$courseid,$domain,$name) = &whichuser();
14957:     return &ireceipt($name,$domain,$courseid,$symb,$part);
14958: }
14959: 
14960: sub whichuser {
14961:     my ($passedsymb)=@_;
14962:     my ($symb,$courseid,$domain,$name,$publicuser);
14963:     if (defined($env{'form.grade_symb'})) {
14964: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
14965: 	my $allowed=&allowed('vgr',$tmp_courseid);
14966: 	if (!$allowed &&
14967: 	    exists($env{'request.course.sec'}) &&
14968: 	    $env{'request.course.sec'} !~ /^\s*$/) {
14969: 	    $allowed=&allowed('vgr',$tmp_courseid.
14970: 			      '/'.$env{'request.course.sec'});
14971: 	}
14972: 	if ($allowed) {
14973: 	    ($symb)=&get_env_multiple('form.grade_symb');
14974: 	    $courseid=$tmp_courseid;
14975: 	    ($domain)=&get_env_multiple('form.grade_domain');
14976: 	    ($name)=&get_env_multiple('form.grade_username');
14977: 	    return ($symb,$courseid,$domain,$name,$publicuser);
14978: 	}
14979:     }
14980:     if (!$passedsymb) {
14981: 	$symb=&symbread();
14982:     } else {
14983: 	$symb=$passedsymb;
14984:     }
14985:     $courseid=$env{'request.course.id'};
14986:     $domain=$env{'user.domain'};
14987:     $name=$env{'user.name'};
14988:     if ($name eq 'public' && $domain eq 'public') {
14989: 	if (!defined($env{'form.username'})) {
14990: 	    $env{'form.username'}.=time.rand(10000000);
14991: 	}
14992: 	$name.=$env{'form.username'};
14993:     }
14994:     return ($symb,$courseid,$domain,$name,$publicuser);
14995: 
14996: }
14997: 
14998: # ------------------------------------------------------------ Serves up a file
14999: # returns either the contents of the file or 
15000: # -1 if the file doesn't exist
15001: #
15002: # if the target is a file that was uploaded via DOCS, 
15003: # a check will be made to see if a current copy exists on the local server,
15004: # if it does this will be served, otherwise a copy will be retrieved from
15005: # the home server for the course and stored in /home/httpd/html/userfiles on
15006: # the local server.   
15007: 
15008: sub getfile {
15009:     my ($file) = @_;
15010:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
15011:     &repcopy($file);
15012:     return &readfile($file);
15013: }
15014: 
15015: sub repcopy_userfile {
15016:     my ($file)=@_;
15017:     my $londocroot = $perlvar{'lonDocRoot'};
15018:     if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
15019:     if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
15020:     my ($cdom,$cnum,$filename) = 
15021: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
15022:     my $uri="/uploaded/$cdom/$cnum/$filename";
15023:     if (-e "$file") {
15024: # we already have a local copy, check it out
15025: 	my @fileinfo = stat($file);
15026: 	my $rtncode;
15027: 	my $info;
15028: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
15029: 	if ($lwpresp ne 'ok') {
15030: # there is no such file anymore, even though we had a local copy
15031: 	    if ($rtncode eq '404') {
15032: 		unlink($file);
15033: 	    }
15034: 	    return -1;
15035: 	}
15036: 	if ($info < $fileinfo[9]) {
15037: # nice, the file we have is up-to-date, just say okay
15038: 	    return 'ok';
15039: 	} else {
15040: # the file is outdated, get rid of it
15041: 	    unlink($file);
15042: 	}
15043:     }
15044: # one way or the other, at this point, we don't have the file
15045: # construct the correct path for the file
15046:     my @parts = ($cdom,$cnum); 
15047:     if ($filename =~ m|^(.+)/[^/]+$|) {
15048: 	push @parts, split(/\//,$1);
15049:     }
15050:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
15051:     foreach my $part (@parts) {
15052: 	$path .= '/'.$part;
15053: 	if (!-e $path) {
15054: 	    mkdir($path,0770);
15055: 	}
15056:     }
15057: # now the path exists for sure
15058: # get a user agent
15059:     my $transferfile=$file.'.in.transfer';
15060: # FIXME: this should flock
15061:     if (-e $transferfile) { return 'ok'; }
15062:     my $request;
15063:     $uri=~s/^\///;
15064:     my $homeserver = &homeserver($cnum,$cdom);
15065:     my $hostname = &hostname($homeserver);
15066:     my $protocol = $protocol{$homeserver};
15067:     $protocol = 'http' if ($protocol ne 'https');
15068:     $request=new HTTP::Request('GET',$protocol.'://'.$hostname.'/raw/'.$uri);
15069:     my $response = &LONCAPA::LWPReq::makerequest($homeserver,$request,$transferfile,\%perlvar,'',0,1);
15070: # did it work?
15071:     if ($response->is_error()) {
15072: 	unlink($transferfile);
15073: 	&logthis("Userfile repcopy failed for $uri");
15074: 	return -1;
15075:     }
15076: # worked, rename the transfer file
15077:     rename($transferfile,$file);
15078:     return 'ok';
15079: }
15080: 
15081: sub tokenwrapper {
15082:     my $uri=shift;
15083:     $uri=~s|^https?\://([^/]+)||;
15084:     $uri=~s|^/||;
15085:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
15086:     my $token=$1;
15087:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
15088:     if ($udom && $uname && $file) {
15089: 	$file=~s|(\?\.*)*$||;
15090:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
15091:         my $homeserver = &homeserver($uname,$udom);
15092:         my $hostname = &hostname($homeserver);
15093:         my $protocol = $protocol{$homeserver};
15094:         $protocol = 'http' if ($protocol ne 'https');
15095:         return $protocol.'://'.$hostname.'/'.$uri.
15096:                (($uri=~/\?/)?'&':'?').'token='.$token.
15097:                                '&tokenissued='.$perlvar{'lonHostID'};
15098:     } else {
15099:         return '/adm/notfound.html';
15100:     }
15101: }
15102: 
15103: # call with reqtype HEAD: get last modification time
15104: # call with reqtype GET: get the file contents
15105: # Do not call this with reqtype GET for large files! It loads everything into memory
15106: #
15107: sub getuploaded {
15108:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
15109:     $uri=~s/^\///;
15110:     my $homeserver = &homeserver($cnum,$cdom);
15111:     my $hostname = &hostname($homeserver);
15112:     my $protocol = $protocol{$homeserver};
15113:     $protocol = 'http' if ($protocol ne 'https');
15114:     $uri = $protocol.'://'.$hostname.'/raw/'.$uri;
15115:     my $request=new HTTP::Request($reqtype,$uri);
15116:     my $response=&LONCAPA::LWPReq::makerequest($homeserver,$request,'',\%perlvar,'',0,1);
15117:     $$rtncode = $response->code;
15118:     if (! $response->is_success()) {
15119: 	return 'failed';
15120:     }      
15121:     if ($reqtype eq 'HEAD') {
15122: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
15123:     } elsif ($reqtype eq 'GET') {
15124: 	$$info = $response->content;
15125:     }
15126:     return 'ok';
15127: }
15128: 
15129: sub readfile {
15130:     my $file = shift;
15131:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
15132:     my $fh;
15133:     open($fh,"<",$file);
15134:     my $a='';
15135:     while (my $line = <$fh>) { $a .= $line; }
15136:     return $a;
15137: }
15138: 
15139: sub filelocation {
15140:     my ($dir,$file) = @_;
15141:     my $location;
15142:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
15143: 
15144:     if ($file =~ m-^/adm/-) {
15145: 	$file=~s-^/adm/wrapper/-/-;
15146: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
15147:     }
15148: 
15149:     if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
15150:         $location = $file;
15151:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
15152:         my ($udom,$uname,$filename)=
15153:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
15154:         my $home=&homeserver($uname,$udom);
15155:         my $is_me=0;
15156:         my @ids=&current_machine_ids();
15157:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
15158:         if ($is_me) {
15159:   	    $location=propath($udom,$uname).'/userfiles/'.$filename;
15160:         } else {
15161:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
15162:   	      $udom.'/'.$uname.'/'.$filename;
15163:         }
15164:     } elsif ($file =~ m-^/adm/-) {
15165: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
15166:     } else {
15167:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
15168:         $file=~s:^/(res|priv)/:/:;
15169:         my $space=$1;
15170:         if ( !( $file =~ m:^/:) ) {
15171:             $location = $dir. '/'.$file;
15172:         } else {
15173:             $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
15174:         }
15175:     }
15176:     $location=~s://+:/:g; # remove duplicate /
15177:     while ($location=~m{/\.\./}) {
15178: 	if ($location =~ m{/[^/]+/\.\./}) {
15179: 	    $location=~ s{/[^/]+/\.\./}{/}g;
15180: 	} else {
15181: 	    $location=~ s{/\.\./}{/}g;
15182: 	}
15183:     } #remove dir/..
15184:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
15185:     return $location;
15186: }
15187: 
15188: sub hreflocation {
15189:     my ($dir,$file)=@_;
15190:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
15191: 	$file=filelocation($dir,$file);
15192:     } elsif ($file=~m-^/adm/-) {
15193: 	$file=~s-^/adm/wrapper/-/-;
15194: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
15195:     }
15196:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
15197: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
15198:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
15199: 	$file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
15200: 	        {/uploaded/$1/$2/}x;
15201:     }
15202:     if ($file=~ m{^/userfiles/}) {
15203: 	$file =~ s{^/userfiles/}{/uploaded/};
15204:     }
15205:     return $file;
15206: }
15207: 
15208: 
15209: 
15210: 
15211: 
15212: sub current_machine_domains {
15213:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
15214: }
15215: 
15216: sub machine_domains {
15217:     my ($hostname) = @_;
15218:     my @domains;
15219:     my %hostname = &all_hostnames();
15220:     while( my($id, $name) = each(%hostname)) {
15221: #	&logthis("-$id-$name-$hostname-");
15222: 	if ($hostname eq $name) {
15223: 	    push(@domains,&host_domain($id));
15224: 	}
15225:     }
15226:     return @domains;
15227: }
15228: 
15229: sub current_machine_ids {
15230:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
15231: }
15232: 
15233: sub machine_ids {
15234:     my ($hostname) = @_;
15235:     $hostname ||= &hostname($perlvar{'lonHostID'});
15236:     my @ids;
15237:     my %name_to_host = &all_names();
15238:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
15239: 	return @{ $name_to_host{$hostname} };
15240:     }
15241:     return;
15242: }
15243: 
15244: sub additional_machine_domains {
15245:     my @domains;
15246:     if (-e "$perlvar{'lonTabDir'}/expected_domains.tab") {
15247:         if (open(my $fh,"<","$perlvar{'lonTabDir'}/expected_domains.tab")) {
15248:             while (my $line = <$fh>) {
15249:                 chomp($line);           
15250:                 $line =~ s/\s//g;
15251:                 push(@domains,$line);
15252:             }
15253:             close($fh);
15254:         }
15255:     }
15256:     return @domains;
15257: }
15258: 
15259: sub default_login_domain {
15260:     my $domain = $perlvar{'lonDefDomain'};
15261:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
15262:     foreach my $posdom (&current_machine_domains(),
15263:                         &additional_machine_domains()) {
15264:         if (lc($posdom) eq lc($testdomain)) {
15265:             $domain=$posdom;
15266:             last;
15267:         }
15268:     }
15269:     return $domain;
15270: }
15271: 
15272: sub shared_institution {
15273:     my ($dom,$lonhost) = @_;
15274:     if ($lonhost eq '') {
15275:         $lonhost = $perlvar{'lonHostID'};
15276:     }
15277:     my $same_intdom;
15278:     my $hostintdom = &internet_dom($lonhost);
15279:     if ($hostintdom ne '') {
15280:         my %iphost = &get_iphost();
15281:         my $primary_id = &domain($dom,'primary');
15282:         my $primary_ip = &get_host_ip($primary_id);
15283:         if (ref($iphost{$primary_ip}) eq 'ARRAY') {
15284:             foreach my $id (@{$iphost{$primary_ip}}) {
15285:                 my $intdom = &internet_dom($id);
15286:                 if ($intdom eq $hostintdom) {
15287:                     $same_intdom = 1;
15288:                     last;
15289:                 }
15290:             }
15291:         }
15292:     }
15293:     return $same_intdom;
15294: }
15295: 
15296: sub uses_sts {
15297:     my ($ignore_cache) = @_;
15298:     my $lonhost = $perlvar{'lonHostID'};
15299:     my $hostname = &hostname($lonhost);
15300:     my $sts_on;
15301:     if ($protocol{$lonhost} eq 'https') {
15302:         my $cachetime = 12*3600;
15303:         if (!$ignore_cache) {
15304:             ($sts_on,my $cached)=&is_cached_new('stspolicy',$lonhost);
15305:             if (defined($cached)) {
15306:                 return $sts_on;
15307:             }
15308:         }
15309:         my $url = $protocol{$lonhost}.'://'.$hostname.'/index.html';
15310:         my $request=new HTTP::Request('HEAD',$url);
15311:         my $response=&LONCAPA::LWPReq::makerequest($lonhost,$request,'',\%perlvar,'','','',1);
15312:         if ($response->is_success) {
15313:             my $has_sts = $response->header('Strict-Transport-Security');
15314:             if ($has_sts eq '') {
15315:                 $sts_on = 0;
15316:             } else {
15317:                 if ($has_sts =~ /\Qmax-age=\E(\d+)/) {
15318:                     my $maxage = $1;
15319:                     if ($maxage) {
15320:                         $sts_on = 1;
15321:                     } else {
15322:                         $sts_on = 0;
15323:                     }
15324:                 } else {
15325:                     $sts_on = 0;
15326:                 }
15327:             }
15328:             return &do_cache_new('stspolicy',$lonhost,$sts_on,$cachetime);
15329:         }
15330:     }
15331:     return;
15332: }
15333: 
15334: sub waf_allssl {
15335:     my ($host_name) = @_;
15336:     my $alias = &get_proxy_alias();
15337:     if ($host_name eq '') {
15338:         $host_name = $ENV{'SERVER_NAME'};
15339:     }
15340:     if (($host_name ne '') && ($alias eq $host_name)) {
15341:         my $serverhomedom = &host_domain($perlvar{'lonHostID'});
15342:         my %defdomdefaults = &get_domain_defaults($serverhomedom);
15343:         if ($defdomdefaults{'waf_sslopt'}) {
15344:             return $defdomdefaults{'waf_sslopt'};
15345:         }
15346:     }
15347:     return;
15348: }
15349: 
15350: sub get_requestor_ip {
15351:     my ($r,$nolookup,$noproxy) = @_;
15352:     my $from_ip;
15353:     if (ref($r)) {
15354:         if ($r->can('useragent_ip')) {
15355:             if ($noproxy && $r->can('client_ip')) {
15356:                 $from_ip = $r->client_ip();
15357:             } else {
15358:                 $from_ip = $r->useragent_ip();
15359:             }
15360:         } elsif ($r->connection->can('remote_ip')) {
15361:             $from_ip = $r->connection->remote_ip();
15362:         } else {
15363:             $from_ip = $r->get_remote_host($nolookup);
15364:         }
15365:     } else {
15366:         $from_ip = $ENV{'REMOTE_ADDR'};
15367:     }
15368:     return $from_ip if ($noproxy); 
15369:     # Who controls proxy settings for server
15370:     my $dom_in_use = $Apache::lonnet::perlvar{'lonDefDomain'};
15371:     my $proxyinfo = &get_proxy_settings($dom_in_use);
15372:     if ((ref($proxyinfo) eq 'HASH') && ($from_ip)) {
15373:         if ($proxyinfo->{'vpnint'}) {
15374:             if (&ip_match($from_ip,$proxyinfo->{'vpnint'})) {
15375:                 return $from_ip;
15376:             }
15377:         }
15378:         if ($proxyinfo->{'trusted'}) {
15379:             if (&ip_match($from_ip,$proxyinfo->{'trusted'})) {
15380:                 my $ipheader = $proxyinfo->{'ipheader'};
15381:                 my ($ip,$xfor);
15382:                 if (ref($r)) {
15383:                     if ($ipheader) {
15384:                         $ip = $r->headers_in->{$ipheader};
15385:                     }
15386:                     $xfor = $r->headers_in->{'X-Forwarded-For'};
15387:                 } else {
15388:                     if ($ipheader) {
15389:                         $ip = $ENV{'HTTP_'.uc($ipheader)};
15390:                     }
15391:                     $xfor = $ENV{'HTTP_X_FORWARDED_FOR'};
15392:                 }
15393:                 if (($ip eq '') && ($xfor ne '')) {
15394:                     foreach my $poss_ip (reverse(split(/\s*,\s*/,$xfor))) {
15395:                         unless (&ip_match($poss_ip,$proxyinfo->{'trusted'})) {
15396:                             $ip = $poss_ip;
15397:                             last;
15398:                         }
15399:                     }
15400:                 }
15401:                 if ($ip ne '') {
15402:                     return $ip;
15403:                 }
15404:             }
15405:         }
15406:     }
15407:     return $from_ip;
15408: }
15409: 
15410: sub get_proxy_settings {
15411:     my ($dom_in_use) = @_;
15412:     my %domdefaults = &get_domain_defaults($dom_in_use);
15413:     my $proxyinfo = {
15414:                        ipheader => $domdefaults{'waf_ipheader'},
15415:                        trusted  => $domdefaults{'waf_trusted'},
15416:                        vpnint   => $domdefaults{'waf_vpnint'},
15417:                        vpnext   => $domdefaults{'waf_vpnext'},
15418:                        sslopt   => $domdefaults{'waf_sslopt'},
15419:                     };
15420:     return $proxyinfo;
15421: }
15422: 
15423: sub ip_match {
15424:     my ($ip,$pattern_str) = @_;
15425:     $ip=Net::CIDR::cidrvalidate($ip);
15426:     if ($ip) {
15427:         return Net::CIDR::cidrlookup($ip,split(/\s*,\s*/,$pattern_str));
15428:     }
15429:     return;
15430: }
15431: 
15432: sub get_proxy_alias {
15433:     my ($lonid) = @_;
15434:     if ($lonid eq '') {
15435:         $lonid = $perlvar{'lonHostID'};
15436:     }
15437:     if (!defined(&hostname($lonid))) {
15438:         return;
15439:     }
15440:     if ($lonid ne '') {
15441:         my ($alias,$cached) = &is_cached_new('proxyalias',$lonid);
15442:         if ($cached) {
15443:             return $alias;
15444:         }
15445:         my $dom = &host_domain($lonid);
15446:         if ($dom ne '') {
15447:             my $cachetime = 60*60*24;
15448:             my %domconfig =
15449:                 &get_dom('configuration',['wafproxy'],$dom);
15450:             if (ref($domconfig{'wafproxy'}) eq 'HASH') {
15451:                 if (ref($domconfig{'wafproxy'}{'alias'}) eq 'HASH') {
15452:                     $alias = $domconfig{'wafproxy'}{'alias'}{$lonid};
15453:                 }
15454:             }
15455:             return &do_cache_new('proxyalias',$lonid,$alias,$cachetime);
15456:         }
15457:     }
15458:     return;
15459: }
15460: 
15461: sub use_proxy_alias {
15462:     my ($r,$lonid) = @_;
15463:     my $alias = &get_proxy_alias($lonid);
15464:     if ($alias) {
15465:         my $dom = &host_domain($lonid);
15466:         if ($dom ne '') {
15467:             my $proxyinfo = &get_proxy_settings($dom);
15468:             my ($vpnint,$remote_ip);
15469:             if (ref($proxyinfo) eq 'HASH') {
15470:                 $vpnint = $proxyinfo->{'vpnint'};
15471:                 if ($vpnint) {
15472:                     $remote_ip = &get_requestor_ip($r,1,1);
15473:                 }
15474:             }
15475:             unless ($vpnint && &ip_match($remote_ip,$vpnint)) {
15476:                 return $alias;
15477:             }
15478:         }
15479:     }
15480:     return;
15481: }
15482: 
15483: sub alias_sso {
15484:     my ($lonid) = @_;
15485:     if ($lonid eq '') {
15486:         $lonid = $perlvar{'lonHostID'};
15487:     }
15488:     if (!defined(&hostname($lonid))) {
15489:         return;
15490:     }
15491:     if ($lonid ne '') {
15492:         my ($use_alias,$cached) = &is_cached_new('proxysaml',$lonid);
15493:         if ($cached) {
15494:             return $use_alias;
15495:         }
15496:         my $dom = &host_domain($lonid);
15497:         if ($dom ne '') {
15498:             my $cachetime = 60*60*24;
15499:             my %domconfig =
15500:                 &get_dom('configuration',['wafproxy'],$dom);
15501:             if (ref($domconfig{'wafproxy'}) eq 'HASH') {
15502:                 if (ref($domconfig{'wafproxy'}{'saml'}) eq 'HASH') {
15503:                     $use_alias = $domconfig{'wafproxy'}{'saml'}{$lonid};
15504:                 }
15505:             }
15506:             return &do_cache_new('proxysaml',$lonid,$use_alias,$cachetime);
15507:         }
15508:     }
15509:     return;
15510: }
15511: 
15512: sub get_saml_landing {
15513:     my ($lonid) = @_;
15514:     if ($lonid eq '') {
15515:         my $defdom = &default_login_domain();
15516:         my @hosts = &current_machine_ids();
15517:         if (@hosts > 1) {
15518:             foreach my $hostid (@hosts) {
15519:                 if (&host_domain($hostid) eq $defdom) {
15520:                     $lonid = $hostid;
15521:                     last;
15522:                 }
15523:             }
15524:         } else {
15525:             $lonid = $perlvar{'lonHostID'};
15526:         }
15527:         if ($lonid) {
15528:             unless (&host_domain($lonid) eq $defdom) {
15529:                 return;
15530:             }
15531:         } else {
15532:             return;
15533:         }
15534:     } elsif (!defined(&hostname($lonid))) {
15535:         return;
15536:     }
15537:     my ($landing,$cached) = &is_cached_new('samllanding',$lonid);
15538:     if ($cached) {
15539:         return $landing;
15540:     }
15541:     my $dom = &host_domain($lonid);
15542:     if ($dom ne '') {
15543:         my $cachetime = 60*60*24;
15544:         my %domconfig =
15545:             &get_dom('configuration',['login'],$dom);
15546:         if (ref($domconfig{'login'}) eq 'HASH') {
15547:             if (ref($domconfig{'login'}{'saml'}) eq 'HASH') {
15548:                 if (ref($domconfig{'login'}{'saml'}{$lonid}) eq 'HASH') {
15549:                     $landing = 1;
15550:                 }
15551:             }
15552:         }
15553:         return &do_cache_new('samllanding',$lonid,$landing,$cachetime);
15554:     }
15555:     return;
15556: }
15557: 
15558: # ------------------------------------------------------------- Declutters URLs
15559: 
15560: sub declutter {
15561:     my $thisfn=shift;
15562:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
15563:     unless ($thisfn=~m{^/home/httpd/html/priv/}) {
15564:         $thisfn=~s{^/home/httpd/html}{};
15565:     }
15566:     $thisfn=~s/^\///;
15567:     $thisfn=~s|^adm/wrapper/||;
15568:     $thisfn=~s|^adm/coursedocs/showdoc/||;
15569:     $thisfn=~s/^res\///;
15570:     $thisfn=~s/^priv\///;
15571:     unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
15572:         $thisfn=~s/\?.+$//;
15573:     }
15574:     return $thisfn;
15575: }
15576: 
15577: # ------------------------------------------------------------- Clutter up URLs
15578: 
15579: sub clutter {
15580:     my $thisfn='/'.&declutter(shift);
15581:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
15582: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
15583:        $thisfn='/res'.$thisfn; 
15584:     }
15585:     if ($thisfn !~m|^/adm|) {
15586: 	if ($thisfn =~ m|^/ext/|) {
15587: 	    $thisfn='/adm/wrapper'.$thisfn;
15588: 	} else {
15589: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
15590: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
15591: 	    if ($embstyle eq 'ssi'
15592: 		|| ($embstyle eq 'hdn')
15593: 		|| ($embstyle eq 'rat')
15594: 		|| ($embstyle eq 'prv')
15595: 		|| ($embstyle eq 'ign')) {
15596: 		#do nothing with these
15597: 	    } elsif (($embstyle eq 'img') 
15598: 		|| ($embstyle eq 'emb')
15599: 		|| ($embstyle eq 'wrp')) {
15600: 		$thisfn='/adm/wrapper'.$thisfn;
15601: 	    } elsif ($embstyle eq 'unk'
15602: 		     && $thisfn!~/\.(sequence|page)$/) {
15603: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
15604: 	    } else {
15605: #		&logthis("Got a blank emb style");
15606: 	    }
15607: 	}
15608:     } elsif ($thisfn =~ m{^/adm/$match_domain/$match_courseid/\d+/ext\.tool$}) {
15609:         $thisfn='/adm/wrapper'.$thisfn;
15610:     }
15611:     return $thisfn;
15612: }
15613: 
15614: sub clutter_with_no_wrapper {
15615:     my $uri = &clutter(shift);
15616:     if ($uri =~ m-^/adm/-) {
15617: 	$uri =~ s-^/adm/wrapper/-/-;
15618: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
15619:     }
15620:     return $uri;
15621: }
15622: 
15623: sub freeze_escape {
15624:     my ($value)=@_;
15625:     if (ref($value)) {
15626: 	$value=&nfreeze($value);
15627: 	return '__FROZEN__'.&escape($value);
15628:     }
15629:     return &escape($value);
15630: }
15631: 
15632: 
15633: sub thaw_unescape {
15634:     my ($value)=@_;
15635:     if ($value =~ /^__FROZEN__/) {
15636: 	substr($value,0,10,undef);
15637: 	$value=&unescape($value);
15638: 	return &thaw($value);
15639:     }
15640:     return &unescape($value);
15641: }
15642: 
15643: sub correct_line_ends {
15644:     my ($result)=@_;
15645:     $$result =~s/\r\n/\n/mg;
15646:     $$result =~s/\r/\n/mg;
15647: }
15648: # ================================================================ Main Program
15649: 
15650: sub goodbye {
15651:    &logthis("Starting Shut down");
15652: #not converted to using infrastruture and probably shouldn't be
15653:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
15654: #converted
15655: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
15656:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
15657: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
15658: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
15659: #1.1 only
15660: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
15661: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
15662: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
15663: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
15664:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
15665:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
15666:    &logthis(sprintf("%-20s is %s",'hits',$hits));
15667:    &flushcourselogs();
15668:    &logthis("Shutting down");
15669: }
15670: 
15671: sub get_dns {
15672:     my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
15673:     if (!$ignore_cache) {
15674: 	my ($content,$cached)=
15675: 	    &is_cached_new('dns',$url);
15676: 	if ($cached) {
15677: 	    &$func($content,$hashref);
15678: 	    return;
15679: 	}
15680:     }
15681: 
15682:     my %alldns;
15683:     if (open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab")) {
15684:         foreach my $dns (<$config>) {
15685: 	    next if ($dns !~ /^\^(\S*)/x);
15686:             my $line = $1;
15687:             my ($host,$protocol) = split(/:/,$line);
15688:             if ($protocol ne 'https') {
15689:                 $protocol = 'http';
15690:             }
15691: 	    $alldns{$host} = $protocol;
15692:         }
15693:         close($config);
15694:     }
15695:     while (%alldns) {
15696: 	my ($dns) = sort { $b cmp $a } keys(%alldns);
15697:         my ($contents,@content);
15698:         if ($dns eq Sys::Hostname::FQDN::fqdn()) {
15699:             my $command = (split('/',$url))[3];
15700:             my ($dir,$file) = &parse_getdns_url($command,$url);
15701:             delete($alldns{$dns});
15702:             next if (($dir eq '') || ($file eq ''));
15703:             if (open(my $config,'<',"$dir/$file")) {
15704:                 @content = <$config>;
15705:                 close($config);
15706:             }
15707:             if ($url eq '/adm/dns/loncapaCRL') {
15708:                 $contents = join('',@content);
15709:             }
15710:         } else {
15711: 	    my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
15712:             my $response = &LONCAPA::LWPReq::makerequest('',$request,'',\%perlvar,30,0);
15713:             delete($alldns{$dns});
15714: 	    next if ($response->is_error());
15715:             if ($url eq '/adm/dns/loncapaCRL') {
15716:                 $contents = $response->content;
15717:             } else {
15718:                 @content = split("\n",$response->content);
15719:             }
15720:         }
15721:         if ($url eq '/adm/dns/loncapaCRL') {
15722:             return &$func($contents);
15723:         } else {
15724: 	    unless ($nocache) {
15725: 	        &do_cache_new('dns',$url,\@content,30*24*60*60);
15726: 	    }
15727: 	    &$func(\@content,$hashref);
15728:             return;
15729:         }
15730:     }
15731:     my $which = (split('/',$url,4))[3];
15732:     if ($which eq 'loncapaCRL') {
15733:         my $diskfile = "$perlvar{'lonCertificateDirectory'}/$perlvar{'lonnetCertRevocationList'}";
15734:         if (-e $diskfile) {
15735:             &logthis("unable to contact DNS, on disk file $diskfile not updated");
15736:         } else {
15737:             &logthis("unable to contact DNS, no on disk file $diskfile available");
15738:         }
15739:     } else {
15740:         &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
15741:         if (open(my $config,"<","$perlvar{'lonTabDir'}/dns_$which.tab")) {
15742:             my @content = <$config>;
15743:             close($config);
15744:             &$func(\@content,$hashref);
15745:         }
15746:     }
15747:     return;
15748: }
15749: 
15750: # ------------------------------------------------------Get DNS checksums file
15751: sub parse_dns_checksums_tab {
15752:     my ($lines,$hashref) = @_;
15753:     my $lonhost = $perlvar{'lonHostID'};
15754:     my $machine_dom = &host_domain($lonhost);
15755:     my $loncaparev = &get_server_loncaparev($machine_dom);
15756:     my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
15757:     my $webconfdir = '/etc/httpd/conf';
15758:     if ($distro =~ /^(ubuntu|debian)(\d+)$/) {
15759:         $webconfdir = '/etc/apache2';
15760:     } elsif ($distro =~ /^sles(\d+)$/) {
15761:         if ($1 >= 10) {
15762:             $webconfdir = '/etc/apache2';
15763:         }
15764:     } elsif ($distro =~ /^suse(\d+\.\d+)$/) {
15765:         if ($1 >= 10.0) {
15766:             $webconfdir = '/etc/apache2';
15767:         }
15768:     }
15769:     my ($release,$timestamp) = split(/\-/,$loncaparev);
15770:     my (%chksum,%revnum);
15771:     if (ref($lines) eq 'ARRAY') {
15772:         chomp(@{$lines});
15773:         my $version = shift(@{$lines});
15774:         if ($version eq $release) {  
15775:             foreach my $line (@{$lines}) {
15776:                 my ($file,$version,$shasum) = split(/,/,$line);
15777:                 if ($file =~ m{^/etc/httpd/conf}) {
15778:                     if ($webconfdir eq '/etc/apache2') {
15779:                         $file =~ s{^\Q/etc/httpd/conf/\E}{$webconfdir/};
15780:                     }
15781:                 }
15782:                 $chksum{$file} = $shasum;
15783:                 $revnum{$file} = $version;
15784:             }
15785:             if (ref($hashref) eq 'HASH') {
15786:                 %{$hashref} = (
15787:                                 sums     => \%chksum,
15788:                                 versions => \%revnum,
15789:                               );
15790:             }
15791:         }
15792:     }
15793:     return;
15794: }
15795: 
15796: sub fetch_dns_checksums {
15797:     my %checksums;
15798:     my $machine_dom = &host_domain($perlvar{'lonHostID'});
15799:     my $loncaparev = &get_server_loncaparev($machine_dom,$perlvar{'lonHostID'});
15800:     my ($release,$timestamp) = split(/\-/,$loncaparev);
15801:     &get_dns("/adm/dns/checksums/$release",\&parse_dns_checksums_tab,1,1,
15802:              \%checksums);
15803:     return \%checksums;
15804: }
15805: 
15806: sub fetch_crl_pemfile {
15807:     return &get_dns("/adm/dns/loncapaCRL",\&save_crl_pem,1,1);
15808: }
15809: 
15810: sub save_crl_pem {
15811:     my ($content) = @_;
15812:     my ($msg,$hadchanges);
15813:     if ($content ne '') {
15814:         my $now = time;
15815:         my $lonca = $perlvar{'lonCertificateDirectory'}.'/'.$perlvar{'lonnetCertificateAuthority'};
15816:         my $tmpcrl = $tmpdir.'/'.$perlvar{'lonnetCertRevocationList'}.'_'.$now.'.'.$$.'.tmp';
15817:         if (open(my $fh,'>',"$tmpcrl")) {
15818:             print $fh $content;
15819:             close($fh);
15820:             if (-e $lonca) {
15821:                 if (open(PIPE,"openssl crl -in $tmpcrl -inform pem -CAfile $lonca -noout 2>&1 |")) {
15822:                     my $check = <PIPE>;
15823:                     close(PIPE);
15824:                     chomp($check);
15825:                     if ($check eq 'verify OK') {
15826:                         my $dest = "$perlvar{'lonCertificateDirectory'}/$perlvar{'lonnetCertRevocationList'}";
15827:                         my $backup;
15828:                         if (-e $dest) {
15829:                             if (&File::Copy::move($dest,"$dest.bak")) {
15830:                                 $backup = 'ok';
15831:                             }
15832:                         }
15833:                         if (&File::Copy::move($tmpcrl,$dest)) {
15834:                             $msg = 'ok';
15835:                             if ($backup) {
15836:                                 my (%oldnums,%newnums);
15837:                                 if (open(PIPE, "openssl crl -inform PEM -text -noout -in $dest.bak |grep 'Serial Number' |")) {
15838:                                     while (<PIPE>) {
15839:                                         $oldnums{(split(/:/))[1]} = 1;
15840:                                     }
15841:                                     close(PIPE);
15842:                                 }
15843:                                 if (open(PIPE, "openssl crl -inform PEM -text -noout -in $dest |grep 'Serial Number' |")) {
15844:                                     while(<PIPE>) {
15845:                                         $newnums{(split(/:/))[1]} = 1;
15846:                                     }
15847:                                     close(PIPE);
15848:                                 }
15849:                                 foreach my $key (sort {$b <=> $a } (keys(%newnums))) {
15850:                                     unless (exists($oldnums{$key})) {
15851:                                         $hadchanges = 1;
15852:                                         last;
15853:                                     }
15854:                                 }
15855:                                 unless ($hadchanges) {
15856:                                     foreach my $key (sort {$b <=> $a } (keys(%oldnums))) {
15857:                                         unless (exists($newnums{$key})) {
15858:                                             $hadchanges = 1;
15859:                                             last;
15860:                                         }
15861:                                     }
15862:                                 }
15863:                             }
15864:                         }
15865:                     } else {
15866:                         unlink($tmpcrl);
15867:                     }
15868:                 } else {
15869:                     unlink($tmpcrl);
15870:                 }
15871:             } else {
15872:                 unlink($tmpcrl);
15873:             }
15874:         }
15875:     }
15876:     return ($msg,$hadchanges);
15877: }
15878: 
15879: sub parse_getdns_url {
15880:     my ($command,$url) = @_;
15881:     my $dir = $perlvar{'lonTabDir'};
15882:     my $file;
15883:     if ($command eq 'hosts') {
15884:         $file = 'dns_hosts.tab';
15885:     } elsif ($command eq 'domain') {
15886:         $file = 'dns_domain.tab';
15887:     } elsif ($command eq 'checksums') {
15888:         my $version = (split('/',$url))[4];
15889:         $file = "dns_checksums/$version.tab",
15890:     } elsif ($command eq 'loncapaCRL') {
15891:         $dir = $perlvar{'lonCertificateDirectory'};
15892:         $file = $perlvar{'lonnetCertRevocationList'};
15893:     }
15894:     return ($dir,$file);
15895: }
15896: 
15897: # ------------------------------------------------------------ Read domain file
15898: {
15899:     my $loaded;
15900:     my %domain;
15901: 
15902:     sub parse_domain_tab {
15903: 	my ($lines) = @_;
15904: 	foreach my $line (@$lines) {
15905: 	    next if ($line =~ /^(\#|\s*$ )/x);
15906: 
15907: 	    chomp($line);
15908: 	    my ($name,@elements) = split(/:/,$line,9);
15909: 	    my %this_domain;
15910: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
15911: 			       'lang_def', 'city', 'longi', 'lati',
15912: 			       'primary') {
15913: 		$this_domain{$field} = shift(@elements);
15914: 	    }
15915: 	    $domain{$name} = \%this_domain;
15916: 	}
15917:     }
15918: 
15919:     sub reset_domain_info {
15920: 	undef($loaded);
15921: 	undef(%domain);
15922:     }
15923: 
15924:     sub load_domain_tab {
15925: 	my ($ignore_cache,$nocache) = @_;
15926: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache,$nocache);
15927: 	my $fh;
15928: 	if (open($fh,"<",$perlvar{'lonTabDir'}.'/domain.tab')) {
15929: 	    my @lines = <$fh>;
15930: 	    &parse_domain_tab(\@lines);
15931: 	}
15932: 	close($fh);
15933: 	$loaded = 1;
15934:     }
15935: 
15936:     sub domain {
15937: 	&load_domain_tab() if (!$loaded);
15938: 
15939: 	my ($name,$what) = @_;
15940: 	return if ( !exists($domain{$name}) );
15941: 
15942: 	if (!$what) {
15943: 	    return $domain{$name}{'description'};
15944: 	}
15945: 	return $domain{$name}{$what};
15946:     }
15947: 
15948:     sub domain_info {
15949:         &load_domain_tab() if (!$loaded);
15950:         return %domain;
15951:     }
15952: 
15953: }
15954: 
15955: 
15956: # ------------------------------------------------------------- Read hosts file
15957: {
15958:     my %hostname;
15959:     my %hostdom;
15960:     my %libserv;
15961:     my $loaded;
15962:     my %name_to_host;
15963:     my %internetdom;
15964:     my %LC_dns_serv;
15965: 
15966:     sub parse_hosts_tab {
15967: 	my ($file) = @_;
15968: 	foreach my $configline (@$file) {
15969: 	    next if ($configline =~ /^(\#|\s*$ )/x);
15970:             chomp($configline);
15971: 	    if ($configline =~ /^\^/) {
15972:                 if ($configline =~ /^\^([\w.\-]+)/) {
15973:                     $LC_dns_serv{$1} = 1;
15974:                 }
15975:                 next;
15976:             }
15977: 	    my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
15978: 	    $name=~s/\s//g;
15979: 	    if ($id && $domain && $role && $name) {
15980:                 if ((exists($hostname{$id})) && ($hostname{$id} ne '')) {
15981:                     my $curr = $hostname{$id};
15982:                     my $skip;
15983:                     if (ref($name_to_host{$curr}) eq 'ARRAY') {
15984:                         if (($curr eq $name) && (@{$name_to_host{$curr}} == 1)) {
15985:                             $skip = 1;
15986:                         } else {
15987:                             @{$name_to_host{$curr}} = grep { $_ ne $id } @{$name_to_host{$curr}};
15988:                         }
15989:                     }
15990:                     unless ($skip) {
15991:                         push(@{$name_to_host{$name}},$id);
15992:                     }
15993:                 } else {
15994:                     push(@{$name_to_host{$name}},$id);
15995:                 }
15996: 		$hostname{$id}=$name;
15997: 		$hostdom{$id}=$domain;
15998: 		if ($role eq 'library') { $libserv{$id}=$name; }
15999:                 if (defined($protocol)) {
16000:                     if ($protocol eq 'https') {
16001:                         $protocol{$id} = $protocol;
16002:                     } else {
16003:                         $protocol{$id} = 'http'; 
16004:                     }
16005:                 } else {
16006:                     $protocol{$id} = 'http';
16007:                 }
16008:                 if (defined($intdom)) {
16009:                     $internetdom{$id} = $intdom;
16010:                 }
16011: 	    }
16012: 	}
16013:     }
16014:     
16015:     sub reset_hosts_info {
16016: 	&purge_remembered();
16017: 	&reset_domain_info();
16018: 	&reset_hosts_ip_info();
16019:         undef(%internetdom);
16020: 	undef(%name_to_host);
16021: 	undef(%hostname);
16022: 	undef(%hostdom);
16023: 	undef(%libserv);
16024: 	undef($loaded);
16025:     }
16026: 
16027:     sub load_hosts_tab {
16028: 	my ($ignore_cache,$nocache) = @_;
16029: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache,$nocache);
16030: 	open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab");
16031: 	my @config = <$config>;
16032: 	&parse_hosts_tab(\@config);
16033: 	close($config);
16034: 	$loaded=1;
16035:     }
16036: 
16037:     sub hostname {
16038: 	&load_hosts_tab() if (!$loaded);
16039: 
16040: 	my ($lonid) = @_;
16041: 	return $hostname{$lonid};
16042:     }
16043: 
16044:     sub all_hostnames {
16045: 	&load_hosts_tab() if (!$loaded);
16046: 
16047: 	return %hostname;
16048:     }
16049: 
16050:     sub all_names {
16051:         my ($ignore_cache,$nocache) = @_;
16052: 	&load_hosts_tab($ignore_cache,$nocache) if (!$loaded);
16053: 
16054: 	return %name_to_host;
16055:     }
16056: 
16057:     sub all_host_domain {
16058:         &load_hosts_tab() if (!$loaded);
16059:         return %hostdom;
16060:     }
16061: 
16062:     sub all_host_intdom {
16063:         &load_hosts_tab() if (!$loaded);
16064:         return %internetdom;
16065:     }
16066: 
16067:     sub is_library {
16068: 	&load_hosts_tab() if (!$loaded);
16069: 
16070: 	return exists($libserv{$_[0]});
16071:     }
16072: 
16073:     sub all_library {
16074: 	&load_hosts_tab() if (!$loaded);
16075: 
16076: 	return %libserv;
16077:     }
16078: 
16079:     sub unique_library {
16080: 	#2x reverse removes all hostnames that appear more than once
16081:         my %unique = reverse &all_library();
16082:         return reverse %unique;
16083:     }
16084: 
16085:     sub get_servers {
16086: 	&load_hosts_tab() if (!$loaded);
16087: 
16088: 	my ($domain,$type) = @_;
16089: 	my %possible_hosts = ($type eq 'library') ? %libserv
16090: 	                                          : %hostname;
16091: 	my %result;
16092: 	if (ref($domain) eq 'ARRAY') {
16093: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
16094: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
16095: 		    $result{$host} = $hostname;
16096: 		}
16097: 	    }
16098: 	} else {
16099: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
16100: 		if ($hostdom{$host} eq $domain) {
16101: 		    $result{$host} = $hostname;
16102: 		}
16103: 	    }
16104: 	}
16105: 	return %result;
16106:     }
16107: 
16108:     sub get_unique_servers {
16109:         my %unique = reverse &get_servers(@_);
16110: 	return reverse %unique;
16111:     }
16112: 
16113:     sub host_domain {
16114: 	&load_hosts_tab() if (!$loaded);
16115: 
16116: 	my ($lonid) = @_;
16117: 	return $hostdom{$lonid};
16118:     }
16119: 
16120:     sub all_domains {
16121: 	&load_hosts_tab() if (!$loaded);
16122: 
16123: 	my %seen;
16124: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
16125: 	return @uniq;
16126:     }
16127: 
16128:     sub internet_dom {
16129:         &load_hosts_tab() if (!$loaded);
16130: 
16131:         my ($lonid) = @_;
16132:         return $internetdom{$lonid};
16133:     }
16134: 
16135:     sub is_LC_dns {
16136:         &load_hosts_tab() if (!$loaded);
16137: 
16138:         my ($hostname) = @_;
16139:         return exists($LC_dns_serv{$hostname});
16140:     }
16141: 
16142: }
16143: 
16144: { 
16145:     my %iphost;
16146:     my %name_to_ip;
16147:     my %lonid_to_ip;
16148: 
16149:     sub get_hosts_from_ip {
16150: 	my ($ip) = @_;
16151: 	my %iphosts = &get_iphost();
16152: 	if (ref($iphosts{$ip})) {
16153: 	    return @{$iphosts{$ip}};
16154: 	}
16155: 	return;
16156:     }
16157:     
16158:     sub reset_hosts_ip_info {
16159: 	undef(%iphost);
16160: 	undef(%name_to_ip);
16161: 	undef(%lonid_to_ip);
16162:     }
16163: 
16164:     sub get_host_ip {
16165: 	my ($lonid) = @_;
16166: 	if (exists($lonid_to_ip{$lonid})) {
16167: 	    return $lonid_to_ip{$lonid};
16168: 	}
16169: 	my $name=&hostname($lonid);
16170:    	my $ip = gethostbyname($name);
16171: 	return if (!$ip || length($ip) ne 4);
16172: 	$ip=inet_ntoa($ip);
16173: 	$name_to_ip{$name}   = $ip;
16174: 	$lonid_to_ip{$lonid} = $ip;
16175: 	return $ip;
16176:     }
16177:     
16178:     sub get_iphost {
16179: 	my ($ignore_cache,$nocache) = @_;
16180: 
16181: 	if (!$ignore_cache) {
16182: 	    if (%iphost) {
16183: 		return %iphost;
16184: 	    }
16185: 	    my ($ip_info,$cached)=
16186: 		&is_cached_new('iphost','iphost');
16187: 	    if ($cached) {
16188: 		%iphost      = %{$ip_info->[0]};
16189: 		%name_to_ip  = %{$ip_info->[1]};
16190: 		%lonid_to_ip = %{$ip_info->[2]};
16191: 		return %iphost;
16192: 	    }
16193: 	}
16194: 
16195: 	# get yesterday's info for fallback
16196: 	my %old_name_to_ip;
16197: 	my ($ip_info,$cached)=
16198: 	    &is_cached_new('iphost','iphost');
16199: 	if ($cached) {
16200: 	    %old_name_to_ip = %{$ip_info->[1]};
16201: 	}
16202: 
16203: 	my %name_to_host = &all_names($ignore_cache,$nocache);
16204: 	foreach my $name (keys(%name_to_host)) {
16205: 	    my $ip;
16206: 	    if (!exists($name_to_ip{$name})) {
16207: 		$ip = gethostbyname($name);
16208: 		if (!$ip || length($ip) ne 4) {
16209: 		    if (defined($old_name_to_ip{$name})) {
16210: 			$ip = $old_name_to_ip{$name};
16211: 			&logthis("Can't find $name defaulting to old $ip");
16212: 		    } else {
16213: 			&logthis("Name $name no IP found");
16214: 			next;
16215: 		    }
16216: 		} else {
16217: 		    $ip=inet_ntoa($ip);
16218: 		}
16219: 		$name_to_ip{$name} = $ip;
16220: 	    } else {
16221: 		$ip = $name_to_ip{$name};
16222: 	    }
16223: 	    foreach my $id (@{ $name_to_host{$name} }) {
16224: 		$lonid_to_ip{$id} = $ip;
16225: 	    }
16226: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
16227: 	}
16228:         unless ($nocache) {
16229: 	    &do_cache_new('iphost','iphost',
16230: 		          [\%iphost,\%name_to_ip,\%lonid_to_ip],
16231: 		          48*60*60);
16232:         }
16233: 
16234: 	return %iphost;
16235:     }
16236: 
16237:     #
16238:     #  Given a DNS returns the loncapa host name for that DNS 
16239:     # 
16240:     sub host_from_dns {
16241:         my ($dns) = @_;
16242:         my @hosts;
16243:         my $ip;
16244: 
16245:         if (exists($name_to_ip{$dns})) {
16246:             $ip = $name_to_ip{$dns};
16247:         }
16248:         if (!$ip) {
16249:             $ip = gethostbyname($dns); # Initial translation to IP is in net order.
16250:             if (length($ip) == 4) { 
16251: 	        $ip   = &IO::Socket::inet_ntoa($ip);
16252:             }
16253:         }
16254:         if ($ip) {
16255: 	    @hosts = get_hosts_from_ip($ip);
16256: 	    return $hosts[0];
16257:         }
16258:         return undef;
16259:     }
16260: 
16261:     sub get_internet_names {
16262:         my ($lonid) = @_;
16263:         return if ($lonid eq '');
16264:         my ($idnref,$cached)=
16265:             &is_cached_new('internetnames',$lonid);
16266:         if ($cached) {
16267:             return $idnref;
16268:         }
16269:         my $ip = &get_host_ip($lonid);
16270:         my @hosts = &get_hosts_from_ip($ip);
16271:         my %iphost = &get_iphost();
16272:         my (@idns,%seen);
16273:         foreach my $id (@hosts) {
16274:             my $dom = &host_domain($id);
16275:             my $prim_id = &domain($dom,'primary');
16276:             my $prim_ip = &get_host_ip($prim_id);
16277:             next if ($seen{$prim_ip});
16278:             if (ref($iphost{$prim_ip}) eq 'ARRAY') {
16279:                 foreach my $id (@{$iphost{$prim_ip}}) {
16280:                     my $intdom = &internet_dom($id);
16281:                     unless (grep(/^\Q$intdom\E$/,@idns)) {
16282:                         push(@idns,$intdom);
16283:                     }
16284:                 }
16285:             }
16286:             $seen{$prim_ip} = 1;
16287:         }
16288:         return &do_cache_new('internetnames',$lonid,\@idns,12*60*60);
16289:     }
16290: 
16291: }
16292: 
16293: sub all_loncaparevs {
16294:     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);
16295: }
16296: 
16297: # ---------------------------------------------------------- Read loncaparev table
16298: {
16299:     sub load_loncaparevs { 
16300:         if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
16301:             if (open(my $config,"<","$perlvar{'lonTabDir'}/loncaparevs.tab")) {
16302:                 while (my $configline=<$config>) {
16303:                     chomp($configline);
16304:                     my ($hostid,$loncaparev)=split(/:/,$configline);
16305:                     $loncaparevs{$hostid}=$loncaparev;
16306:                 }
16307:                 close($config);
16308:             }
16309:         }
16310:     }
16311: }
16312: 
16313: # ---------------------------------------------------------- Read serverhostID table
16314: {
16315:     sub load_serverhomeIDs {
16316:         if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
16317:             if (open(my $config,"<","$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
16318:                 while (my $configline=<$config>) {
16319:                     chomp($configline);
16320:                     my ($name,$id)=split(/:/,$configline);
16321:                     $serverhomeIDs{$name}=$id;
16322:                 }
16323:                 close($config);
16324:             }
16325:         }
16326:     }
16327: }
16328: 
16329: 
16330: BEGIN {
16331: 
16332: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
16333:     unless ($readit) {
16334: {
16335:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
16336:     %perlvar = (%perlvar,%{$configvars});
16337: }
16338: 
16339: 
16340: # ------------------------------------------------------ Read spare server file
16341: {
16342:     open(my $config,"<","$perlvar{'lonTabDir'}/spare.tab");
16343: 
16344:     while (my $configline=<$config>) {
16345:        chomp($configline);
16346:        if ($configline) {
16347: 	   my ($host,$type) = split(':',$configline,2);
16348: 	   if (!defined($type) || $type eq '') { $type = 'default' };
16349: 	   push(@{ $spareid{$type} }, $host);
16350:        }
16351:     }
16352:     close($config);
16353: }
16354: # ------------------------------------------------------------ Read permissions
16355: {
16356:     open(my $config,"<","$perlvar{'lonTabDir'}/roles.tab");
16357: 
16358:     while (my $configline=<$config>) {
16359: 	chomp($configline);
16360: 	if ($configline) {
16361: 	    my ($role,$perm)=split(/ /,$configline);
16362: 	    if ($perm ne '') { $pr{$role}=$perm; }
16363: 	}
16364:     }
16365:     close($config);
16366: }
16367: 
16368: # -------------------------------------------- Read plain texts for permissions
16369: {
16370:     open(my $config,"<","$perlvar{'lonTabDir'}/rolesplain.tab");
16371: 
16372:     while (my $configline=<$config>) {
16373: 	chomp($configline);
16374: 	if ($configline) {
16375: 	    my ($short,@plain)=split(/:/,$configline);
16376:             %{$prp{$short}} = ();
16377: 	    if (@plain > 0) {
16378:                 $prp{$short}{'std'} = $plain[0];
16379:                 for (my $i=1; $i<@plain; $i++) {
16380:                     $prp{$short}{'alt'.$i} = $plain[$i];  
16381:                 }
16382:             }
16383: 	}
16384:     }
16385:     close($config);
16386: }
16387: 
16388: # ---------------------------------------------------------- Read package table
16389: {
16390:     open(my $config,"<","$perlvar{'lonTabDir'}/packages.tab");
16391: 
16392:     while (my $configline=<$config>) {
16393: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
16394: 	chomp($configline);
16395: 	my ($short,$plain)=split(/:/,$configline);
16396: 	my ($pack,$name)=split(/\&/,$short);
16397: 	if ($plain ne '') {
16398: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
16399: 	    $packagetab{$short}=$plain; 
16400: 	}
16401:     }
16402:     close($config);
16403: }
16404: 
16405: # ---------------------------------------------------------- Read loncaparev table
16406: 
16407: &load_loncaparevs();
16408: 
16409: # ---------------------------------------------------------- Read serverhostID table
16410: 
16411: &load_serverhomeIDs();
16412: 
16413: # ---------------------------------------------------------- Read releaseslist XML
16414: {
16415:     my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
16416:     if (-e $file) {
16417:         my $parser = HTML::LCParser->new($file);
16418:         while (my $token = $parser->get_token()) {
16419:             if ($token->[0] eq 'S') {
16420:                 my $item = $token->[1];
16421:                 my $name = $token->[2]{'name'};
16422:                 my $value = $token->[2]{'value'};
16423:                 my $valuematch = $token->[2]{'valuematch'};
16424:                 my $namematch = $token->[2]{'namematch'};
16425:                 if ($item eq 'parameter') {
16426:                     if (($namematch ne '') || (($name ne '') && ($value ne '' || $valuematch ne ''))) {
16427:                         my $release = $parser->get_text();
16428:                         $release =~ s/(^\s*|\s*$ )//gx;
16429:                         $needsrelease{$item.':'.$name.':'.$value.':'.$valuematch.':'.$namematch} = $release;
16430:                     }
16431:                 } elsif ($item ne '' && $name ne '') {
16432:                     my $release = $parser->get_text();
16433:                     $release =~ s/(^\s*|\s*$ )//gx;
16434:                     $needsrelease{$item.':'.$name.':'.$value} = $release;
16435:                 }
16436:             }
16437:         }
16438:     }
16439: }
16440: 
16441: # ---------------------------------------------------------- Read managers table
16442: {
16443:     if (-e "$perlvar{'lonTabDir'}/managers.tab") {
16444:         if (open(my $config,"<","$perlvar{'lonTabDir'}/managers.tab")) {
16445:             while (my $configline=<$config>) {
16446:                 chomp($configline);
16447:                 next if ($configline =~ /^\#/);
16448:                 if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
16449:                     $managerstab{$configline} = 1;
16450:                 }
16451:             }
16452:             close($config);
16453:         }
16454:     }
16455: }
16456: 
16457: # ------------- set up temporary directory
16458: {
16459:     $tmpdir = LONCAPA::tempdir();
16460: 
16461: }
16462: 
16463: # ------------- set default texengine (domain default overrides this)
16464: {
16465:     $deftex = LONCAPA::texengine();
16466: }
16467: 
16468: # ------------- set default minimum length for passwords for internal auth users
16469: {
16470:     $passwdmin = LONCAPA::passwd_min();
16471: }
16472: 
16473: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
16474: 				'compress_threshold'=> 20_000,
16475:  			        });
16476: 
16477: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
16478: $dumpcount=0;
16479: $locknum=0;
16480: 
16481: &logtouch();
16482: &logthis('<font color="yellow">INFO: Read configuration</font>');
16483: $readit=1;
16484:     {
16485: 	use integer;
16486: 	my $test=(2**32)+1;
16487: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
16488: 	&logthis(" Detected 64bit platform ($_64bit)");
16489:     }
16490: }
16491: }
16492: 
16493: 1;
16494: __END__
16495: 
16496: =pod
16497: 
16498: =head1 NAME
16499: 
16500: Apache::lonnet - Subroutines to ask questions about things in the network.
16501: 
16502: =head1 SYNOPSIS
16503: 
16504: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
16505: 
16506:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
16507: 
16508: Common parameters:
16509: 
16510: =over 4
16511: 
16512: =item *
16513: 
16514: $uname : an internal username (if $cname expecting a course Id specifically)
16515: 
16516: =item *
16517: 
16518: $udom : a domain (if $cdom expecting a course's domain specifically)
16519: 
16520: =item *
16521: 
16522: $symb : a resource instance identifier
16523: 
16524: =item *
16525: 
16526: $namespace : the name of a .db file that contains the data needed or
16527: being set.
16528: 
16529: =back
16530: 
16531: =head1 OVERVIEW
16532: 
16533: lonnet provides subroutines which interact with the
16534: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
16535: about classes, users, and resources.
16536: 
16537: For many of these objects you can also use this to store data about
16538: them or modify them in various ways.
16539: 
16540: =head2 Symbs
16541: 
16542: To identify a specific instance of a resource, LON-CAPA uses symbols
16543: or "symbs"X<symb>. These identifiers are built from the URL of the
16544: map, the resource number of the resource in the map, and the URL of
16545: the resource itself. The latter is somewhat redundant, but might help
16546: if maps change.
16547: 
16548: An example is
16549: 
16550:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
16551: 
16552: The respective map entry is
16553: 
16554:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
16555:   title="Problem 2">
16556:  </resource>
16557: 
16558: Symbs are used by the random number generator, as well as to store and
16559: restore data specific to a certain instance of for example a problem.
16560: 
16561: =head2 Storing And Retrieving Data
16562: 
16563: X<store()>X<cstore()>X<restore()>Three of the most important functions
16564: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
16565: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
16566: is is the non-critical message twin of cstore. These functions are for
16567: handlers to store a perl hash to a user's permanent data space in an
16568: easy manner, and to retrieve it again on another call. It is expected
16569: that a handler would use this once at the beginning to retrieve data,
16570: and then again once at the end to send only the new data back.
16571: 
16572: The data is stored in the user's data directory on the user's
16573: homeserver under the ID of the course.
16574: 
16575: The hash that is returned by restore will have all of the previous
16576: value for all of the elements of the hash.
16577: 
16578: Example:
16579: 
16580:  #creating a hash
16581:  my %hash;
16582:  $hash{'foo'}='bar';
16583: 
16584:  #storing it
16585:  &Apache::lonnet::cstore(\%hash);
16586: 
16587:  #changing a value
16588:  $hash{'foo'}='notbar';
16589: 
16590:  #adding a new value
16591:  $hash{'bar'}='foo';
16592:  &Apache::lonnet::cstore(\%hash);
16593: 
16594:  #retrieving the hash
16595:  my %history=&Apache::lonnet::restore();
16596: 
16597:  #print the hash
16598:  foreach my $key (sort(keys(%history))) {
16599:    print("\%history{$key} = $history{$key}");
16600:  }
16601: 
16602: Will print out:
16603: 
16604:  %history{1:foo} = bar
16605:  %history{1:keys} = foo:timestamp
16606:  %history{1:timestamp} = 990455579
16607:  %history{2:bar} = foo
16608:  %history{2:foo} = notbar
16609:  %history{2:keys} = foo:bar:timestamp
16610:  %history{2:timestamp} = 990455580
16611:  %history{bar} = foo
16612:  %history{foo} = notbar
16613:  %history{timestamp} = 990455580
16614:  %history{version} = 2
16615: 
16616: Note that the special hash entries C<keys>, C<version> and
16617: C<timestamp> were added to the hash. C<version> will be equal to the
16618: total number of versions of the data that have been stored. The
16619: C<timestamp> attribute will be the UNIX time the hash was
16620: stored. C<keys> is available in every historical section to list which
16621: keys were added or changed at a specific historical revision of a
16622: hash.
16623: 
16624: B<Warning>: do not store the hash that restore returns directly. This
16625: will cause a mess since it will restore the historical keys as if the
16626: were new keys. I.E. 1:foo will become 1:1:foo etc.
16627: 
16628: Calling convention:
16629: 
16630:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname);
16631:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$laststore);
16632: 
16633: For more detailed information, see lonnet specific documentation.
16634: 
16635: =head1 RETURN MESSAGES
16636: 
16637: =over 4
16638: 
16639: =item * B<con_lost>: unable to contact remote host
16640: 
16641: =item * B<con_delayed>: unable to contact remote host, message will be delivered
16642: when the connection is brought back up
16643: 
16644: =item * B<con_failed>: unable to contact remote host and unable to save message
16645: for later delivery
16646: 
16647: =item * B<error:>: an error a occurred, a description of the error follows the :
16648: 
16649: =item * B<no_such_host>: unable to fund a host associated with the user/domain
16650: that was requested
16651: 
16652: =back
16653: 
16654: =head1 PUBLIC SUBROUTINES
16655: 
16656: =head2 Session Environment Functions
16657: 
16658: =over 4
16659: 
16660: =item * 
16661: X<appenv()>
16662: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
16663: the user envirnoment file, and will be restored for each access this
16664: user makes during this session, also modifies the %env for the current
16665: process. Optional rolesarrayref - if defined contains a reference to an array
16666: of roles which are exempt from the restriction on modifying user.role entries 
16667: in the user's environment.db and in %env.    
16668: 
16669: =item *
16670: X<delenv()>
16671: B<delenv($delthis,$regexp)>: removes all items from the session
16672: environment file that begin with $delthis. If the 
16673: optional second arg - $regexp - is true, $delthis is treated as a 
16674: regular expression, otherwise \Q$delthis\E is used. 
16675: The values are also deleted from the current processes %env.
16676: 
16677: =item * get_env_multiple($name) 
16678: 
16679: gets $name from the %env hash, it seemlessly handles the cases where multiple
16680: values may be defined and end up as an array ref.
16681: 
16682: returns an array of values
16683: 
16684: =back
16685: 
16686: =head2 User Information
16687: 
16688: =over 4
16689: 
16690: =item *
16691: X<queryauthenticate()>
16692: B<queryauthenticate($uname,$udom)>: try to determine user's current 
16693: authentication scheme
16694: 
16695: =item *
16696: X<authenticate()>
16697: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
16698: authenticate user from domain's lib servers (first use the current
16699: one). C<$upass> should be the users password.
16700: $checkdefauth is optional (value is 1 if a check should be made to
16701:    authenticate user using default authentication method, and allow
16702:    account creation if username does not have account in the domain).
16703: $clientcancheckhost is optional (value is 1 if checking whether the
16704:    server can host will occur on the client side in lonauth.pm).   
16705: 
16706: =item *
16707: X<homeserver()>
16708: B<homeserver($uname,$udom)>: find the server which has
16709: the user's directory and files (there must be only one), this caches
16710: the answer, and also caches if there is a borken connection.
16711: 
16712: =item *
16713: X<idget()>
16714: B<idget($udom,$idsref,$namespace)>: find the usernames behind either 
16715: a list of student/employee IDs or clicker IDs
16716: (student/employee IDs are a unique resource in a domain, there must be 
16717: only 1 ID per username, and only 1 username per ID in a specific domain).
16718: clickerIDs are not necessarily unique, as students might share clickers.
16719: (returns hash: id=>name,id=>name)
16720: 
16721: =item *
16722: X<idrget()>
16723: B<idrget($udom,@unames)>: find the IDs behind a list of
16724: usernames (returns hash: name=>id,name=>id)
16725: 
16726: =item *
16727: X<idput()>
16728: B<idput($udom,$idsref,$uhome,$namespace)>: store away a list of 
16729: names and associated student/employee IDs or clicker IDs.
16730: 
16731: =item *
16732: X<iddel()>
16733: B<iddel($udom,$idshashref,$uhome,$namespace)>: delete unwanted 
16734: student/employee ID or clicker ID username look-ups from domain.
16735: The homeserver ($uhome) and namespace ($namespace) are optional.
16736: If no $uhome is provided, it will be determined usig &homeserver()
16737: for each user.  If no $namespace is provided, the default is ids.
16738: 
16739: =item *
16740: X<updateclickers()>
16741: B<updateclickers($udom,$action,$idshashref,$uhome,$critical)>: update 
16742: clicker ID-to-username look-ups in clickers.db on library server.
16743: Permitted actions are add or del (i.e., add or delete). The 
16744: clickers.db contains clickerID as keys (escaped), and each corresponding
16745: value is an escaped comma-separated list of usernames (for whom the
16746: library server is the homeserver), who registered that particular ID.
16747: If $critical is true, the update will be sent via &critical, otherwise
16748: &reply() will be used.
16749: 
16750: =item *
16751: X<rolesinit()>
16752: B<rolesinit($udom,$username)>: get user privileges.
16753: returns user role, first access and timer interval hashes
16754: 
16755: =item *
16756: X<privileged()>
16757: B<privileged($username,$domain)>: returns a true if user has a
16758: privileged and active role (i.e. su or dc), false otherwise.
16759: 
16760: =item *
16761: X<getsection()>
16762: B<getsection($udom,$uname,$cname)>: finds the section of student in the
16763: course $cname, return section name/number or '' for "not in course"
16764: and '-1' for "no section"
16765: 
16766: =item *
16767: X<userenvironment()>
16768: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
16769: passed in @what from the requested user's environment, returns a hash
16770: 
16771: =item * 
16772: X<userlog_query()>
16773: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
16774: activity.log file. %filters defines filters applied when parsing the
16775: log file. These can be start or end timestamps, or the type of action
16776: - log to look for Login or Logout events, check for Checkin or
16777: Checkout, role for role selection. The response is in the form
16778: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
16779: escaped strings of the action recorded in the activity.log file.
16780: 
16781: =back
16782: 
16783: =head2 User Roles
16784: 
16785: =over 4
16786: 
16787: =item *
16788: 
16789: allowed($priv,$uri,$symb,$role,$clientip,$noblockcheck) : check for a user privilege; 
16790: returns codes for allowed actions.
16791: 
16792: The first argument is required, all others are optional.
16793: 
16794: $priv is the privilege being checked.
16795: $uri contains additional information about what is being checked for access (e.g.,
16796: URL, course ID etc.). 
16797: $symb is the unique resource instance identifier in a course; if needed,
16798: but not provided, it will be retrieved via a call to &symbread(). 
16799: $role is the role for which a priv is being checked (only used if priv is evb). 
16800: $clientip is the user's IP address (only used when checking for access to portfolio 
16801: files).
16802: $noblockcheck, if true, skips calls to &has_comm_blocking() for the bre priv. This 
16803: prevents recursive calls to &allowed.
16804: 
16805:  F: full access
16806:  U,I,K: authentication modes (cxx only)
16807:  '': forbidden
16808:  1: user needs to choose course
16809:  2: browse allowed
16810:  A: passphrase authentication needed
16811:  B: access temporarily blocked because of a blocking event in a course.
16812:  D: access blocked because access is required via session initiated via deep-link 
16813: 
16814: =item *
16815: 
16816: constructaccess($url,$setpriv) : check for access to construction space URL
16817: 
16818: See if the owner domain and name in the URL match those in the
16819: expected environment.  If so, return three element list
16820: ($ownername,$ownerdomain,$ownerhome).
16821: 
16822: Otherwise return the null string.
16823: 
16824: If second argument 'setpriv' is true, it assigns the privileges,
16825: and returns the same three element list, unless the owner has
16826: blocked "ad hoc" Domain Coordinator access to the Author Space,
16827: in which case the null string is returned.
16828: 
16829: =item *
16830: 
16831: definerole($rolename,$sysrole,$domrole,$courole,$uname,$udom) : define role;
16832: define a custom role rolename set privileges in format of lonTabs/roles.tab
16833: for system, domain, and course level. $uname and $udom are optional (current
16834: user's username and domain will be used when either of $uname or $udom are absent.
16835: 
16836: =item *
16837: 
16838: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
16839: (rolesplain.tab); plain text explanation of a user role term.
16840: $type is Course (default) or Community.
16841: If $forcedefault evaluates to true, text returned will be default 
16842: text for $type. Otherwise, if this is a course, the text returned 
16843: will be a custom name for the role (if defined in the course's 
16844: environment).  If no custom name is defined the default is returned.
16845:    
16846: =item *
16847: 
16848: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv) :
16849: All arguments are optional. Returns a hash of a roles, either for
16850: co-author/assistant author roles for a user's Construction Space
16851: (default), or if $context is 'userroles', roles for the user himself,
16852: In the hash, keys are set to colon-separated $uname,$udom,$role, and
16853: (optionally) if $withsec is true, a fourth colon-separated item - $section.
16854: For each key, value is set to colon-separated start and end times for
16855: the role.  If no username and domain are specified, will default to
16856: current user/domain. Types, roles, and roledoms are references to arrays
16857: of role statuses (active, future or previous), roles 
16858: (e.g., cc,in, st etc.) and domains of the roles which can be used
16859: to restrict the list of roles reported. If no array ref is 
16860: provided for types, will default to return only active roles.
16861: 
16862: =item *
16863: 
16864: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
16865: user: $uname:$udom has a role in the course: $cdom_$cnum. 
16866: 
16867: Additional optional arguments are: $type (if role checking is to be restricted 
16868: to certain user status types -- previous (expired roles), active (currently
16869: available roles) or future (roles available in the future), and
16870: $hideprivileged -- if true will not report course roles for users who
16871: have active Domain Coordinator role in course's domain or in additional
16872: domains (specified in 'Domains to check for privileged users' in course
16873: environment -- set via:  Course Settings -> Classlists and staff listing).
16874: 
16875: =item *
16876: 
16877: privileged($username,$domain,$possdomains,$possroles) : returns 1 if user
16878: $username:$domain is a privileged user (e.g., Domain Coordinator or Super User)
16879: $possdomains and $possroles are optional array refs -- to domains to check and
16880: roles to check.  If $possdomains is not specified, a dump will be done of the
16881: users' roles.db to check for a dc or su role in any domain. This can be
16882: time consuming if &privileged is called repeatedly (e.g., when displaying a
16883: classlist), so in such cases, supplying a $possdomains array is preferred, as
16884: this then allows &privileged_by_domain() to be used, which caches the identity
16885: of privileged users, eliminating the need for repeated calls to &dump().
16886: 
16887: =item *
16888: 
16889: privileged_by_domain($possdomains,$roles) : returns a hash of a hash of a hash,
16890: where the outer hash keys are domains specified in the $possdomains array ref,
16891: next inner hash keys are privileged roles specified in the $roles array ref,
16892: and the innermost hash contains key = value pairs for username:domain = end:start
16893: for active or future "privileged" users with that role in that domain. To avoid
16894: repeated dumps of domain roles -- via &get_domain_roles() -- contents of the
16895: innerhash are cached using priv_$role and $dom as the identifiers.
16896: 
16897: =back
16898: 
16899: =head2 User Modification
16900: 
16901: =over 4
16902: 
16903: =item *
16904: 
16905: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
16906: user for the level given by URL.  Optional start and end dates (leave empty
16907: string or zero for "no date")
16908: 
16909: =item *
16910: 
16911: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
16912: change a users, password, possible return values are: ok,
16913: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
16914: refused
16915: 
16916: =item *
16917: 
16918: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
16919: 
16920: =item *
16921: 
16922: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
16923:            $forceid,$desiredhome,$email,$inststatus,$candelete) :
16924: 
16925: will update user information (firstname,middlename,lastname,generation,
16926: permanentemail), and if forceid is true, student/employee ID also.
16927: A user's institutional affiliation(s) can also be updated.
16928: User information fields will not be overwritten with empty entries 
16929: unless the field is included in the $candelete array reference.
16930: This array is included when a single user is modified via "Manage Users",
16931: or when Autoupdate.pl is run by cron in a domain.
16932: 
16933: =item *
16934: 
16935: modifystudent
16936: 
16937: modify a student's enrollment and identification information.
16938: The course id is resolved based on the current user's environment.  
16939: This means the invoking user must be a course coordinator or otherwise
16940: associated with a course.
16941: 
16942: This call is essentially a wrapper for lonnet::modifyuser and
16943: lonnet::modify_student_enrollment
16944: 
16945: Inputs: 
16946: 
16947: =over 4
16948: 
16949: =item B<$udom> Student's loncapa domain
16950: 
16951: =item B<$uname> Student's loncapa login name
16952: 
16953: =item B<$uid> Student/Employee ID
16954: 
16955: =item B<$umode> Student's authentication mode
16956: 
16957: =item B<$upass> Student's password
16958: 
16959: =item B<$first> Student's first name
16960: 
16961: =item B<$middle> Student's middle name
16962: 
16963: =item B<$last> Student's last name
16964: 
16965: =item B<$gene> Student's generation
16966: 
16967: =item B<$usec> Student's section in course
16968: 
16969: =item B<$end> Unix time of the roles expiration
16970: 
16971: =item B<$start> Unix time of the roles start date
16972: 
16973: =item B<$forceid> If defined, allow $uid to be changed
16974: 
16975: =item B<$desiredhome> server to use as home server for student
16976: 
16977: =item B<$email> Student's permanent e-mail address
16978: 
16979: =item B<$type> Type of enrollment (auto or manual)
16980: 
16981: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
16982: 
16983: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
16984: 
16985: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
16986: 
16987: =item B<$context> role change context (shown in User Management Logs display in a course)
16988: 
16989: =item B<$inststatus> institutional status of user - : separated string of escaped status types
16990: 
16991: =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.
16992: 
16993: =back
16994: 
16995: =item *
16996: 
16997: modify_student_enrollment
16998: 
16999: Change a student's enrollment status in a class.  The environment variable
17000: 'role.request.course' must be defined for this function to proceed.
17001: 
17002: Inputs:
17003: 
17004: =over 4
17005: 
17006: =item $udom, student's domain
17007: 
17008: =item $uname, student's name
17009: 
17010: =item $uid, student's user id
17011: 
17012: =item $first, student's first name
17013: 
17014: =item $middle
17015: 
17016: =item $last
17017: 
17018: =item $gene
17019: 
17020: =item $usec
17021: 
17022: =item $end
17023: 
17024: =item $start
17025: 
17026: =item $type
17027: 
17028: =item $locktype
17029: 
17030: =item $cid
17031: 
17032: =item $selfenroll
17033: 
17034: =item $context
17035: 
17036: =item $credits, number of credits student will earn from this class
17037: 
17038: =item $instsec, institutional course section code for student
17039: 
17040: =back
17041: 
17042: 
17043: =item *
17044: 
17045: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
17046: custom role; give a custom role to a user for the level given by URL.  Specify
17047: name and domain of role author, and role name
17048: 
17049: =item *
17050: 
17051: revokerole($udom,$uname,$url,$role) : revoke a role for url
17052: 
17053: =item *
17054: 
17055: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
17056: 
17057: =back
17058: 
17059: =head2 Course Infomation
17060: 
17061: =over 4
17062: 
17063: =item *
17064: 
17065: coursedescription($courseid,$options) : returns a hash of information about the
17066: specified course id, including all environment settings for the
17067: course, the description of the course will be in the hash under the
17068: key 'description'
17069: 
17070: $options is an optional parameter that if supplied is a hash reference that controls
17071: what how this function works.  It has the following key/values:
17072: 
17073: =over 4
17074: 
17075: =item freshen_cache
17076: 
17077: If defined, and the environment cache for the course is valid, it is 
17078: returned in the returned hash.
17079: 
17080: =item one_time
17081: 
17082: If defined, the last cache time is set to _now_
17083: 
17084: =item user
17085: 
17086: If defined, the supplied username is used instead of the current user.
17087: 
17088: 
17089: =back
17090: 
17091: =item *
17092: 
17093: resdata($name,$domain,$type,@which) : request for current parameter
17094: setting for a specific $type, where $type is either 'course' or 'user',
17095: @what should be a list of parameters to ask about. This routine caches
17096: answers for 10 minutes.
17097: 
17098: =item *
17099: 
17100: get_courseresdata($courseid, $domain) : dump the entire course resource
17101: data base, returning a hash that is keyed by the resource name and has
17102: values that are the resource value.  I believe that the timestamps and
17103: versions are also returned.
17104: 
17105: =back
17106: 
17107: =head2 Course Modification
17108: 
17109: =over 4
17110: 
17111: =item *
17112: 
17113: writecoursepref($courseid,%prefs) : write preferences (environment
17114: database) for a course
17115: 
17116: =item *
17117: 
17118: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
17119: 
17120: =item *
17121: 
17122: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
17123: 
17124: =item *
17125: 
17126: is_course($courseid), is_course($cdom, $cnum)
17127: 
17128: Accepts either a combined $courseid (in the form of domain_courseid) or the
17129: two component version $cdom, $cnum. It checks if the specified course exists.
17130: 
17131: Returns:
17132:     undef if the course doesn't exist, otherwise
17133:     in scalar context the combined courseid.
17134:     in list context the two components of the course identifier, domain and 
17135:     courseid.    
17136: 
17137: =back
17138: 
17139: =head2 Bubblesheet Configuration
17140: 
17141: =over 4
17142: 
17143: =item *
17144: 
17145: get_scantron_config($which)
17146: 
17147: $which - the name of the configuration to parse from the file.
17148: 
17149: Parses and returns the bubblesheet configuration line selected as a
17150: hash of configuration file fields.
17151: 
17152: 
17153: Returns:
17154:     If the named configuration is not in the file, an empty
17155:     hash is returned.
17156: 
17157:     a hash with the fields
17158:       name         - internal name for the this configuration setup
17159:       description  - text to display to operator that describes this config
17160:       CODElocation - if 0 or the string 'none'
17161:                           - no CODE exists for this config
17162:                      if -1 || the string 'letter'
17163:                           - a CODE exists for this config and is
17164:                             a string of letters
17165:                      Unsupported value (but planned for future support)
17166:                           if a positive integer
17167:                                - The CODE exists as the first n items from
17168:                                  the question section of the form
17169:                           if the string 'number'
17170:                                - The CODE exists for this config and is
17171:                                  a string of numbers
17172:       CODEstart   - (only matter if a CODE exists) column in the line where
17173:                      the CODE starts
17174:       CODElength  - length of the CODE
17175:       IDstart     - column where the student/employee ID starts
17176:       IDlength    - length of the student/employee ID info
17177:       Qstart      - column where the information from the bubbled
17178:                     'questions' start
17179:       Qlength     - number of columns comprising a single bubble line from
17180:                     the sheet. (usually either 1 or 10)
17181:       Qon         - either a single character representing the character used
17182:                     to signal a bubble was chosen in the positional setup, or
17183:                     the string 'letter' if the letter of the chosen bubble is
17184:                     in the final, or 'number' if a number representing the
17185:                     chosen bubble is in the file (1->A 0->J)
17186:       Qoff        - the character used to represent that a bubble was
17187:                     left blank
17188:       PaperID     - if the scanning process generates a unique number for each
17189:                     sheet scanned the column that this ID number starts in
17190:       PaperIDlength - number of columns that comprise the unique ID number
17191:                       for the sheet of paper
17192:       FirstName   - column that the first name starts in
17193:       FirstNameLength - number of columns that the first name spans
17194:       LastName    - column that the last name starts in
17195:       LastNameLength - number of columns that the last name spans
17196:       BubblesPerRow - number of bubbles available in each row used to
17197:                       bubble an answer. (If not specified, 10 assumed).
17198: 
17199: 
17200: =item *
17201: 
17202: get_scantronformat_file($cdom)
17203: 
17204: $cdom - the course's domain (optional); if not supplied, uses
17205: domain for current $env{'request.course.id'}.
17206: 
17207: Returns an array containing lines from the scantron format file for
17208: the domain of the course.
17209: 
17210: If a url for a custom.tab file is listed in domain's configuration.db,
17211: lines are from this file.
17212: 
17213: Otherwise, if a default.tab has been published in RES space by the
17214: domainconfig user, lines are from this file.
17215: 
17216: Otherwise, fall back to getting lines from the legacy file on the
17217: local server:  /home/httpd/lonTabs/default_scantronformat.tab
17218: 
17219: =back
17220: 
17221: =head2 Resource Subroutines
17222: 
17223: =over 4
17224: 
17225: =item *
17226: 
17227: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
17228: 
17229: =item *
17230: 
17231: repcopy($filename) : subscribes to the requested file, and attempts to
17232: replicate from the owning library server, Might return
17233: 'unavailable', 'not_found', 'forbidden', 'ok', or
17234: 'bad_request', also attempts to grab the metadata for the
17235: resource. Expects the local filesystem pathname
17236: (/home/httpd/html/res/....)
17237: 
17238: =back
17239: 
17240: =head2 Resource Information
17241: 
17242: =over 4
17243: 
17244: =item *
17245: 
17246: EXT($varname,$symb,$udom,$uname,$usection,$recurse,$cid) : evaluates 
17247: and returns the value of a variety of different possible values,
17248: $varname should be a request string, and the other parameters can be
17249: used to specify who and what one is asking about. Ordinarily, $cid 
17250: does not need to be specified, as it is retrived from 
17251: $env{'request.course.id'}, but &Apache::lonnet::EXT() is called
17252: within lonuserstate::loadmap() when initializing a course, before
17253: $env{'request.course.id'} has been set, so it needs to be provided
17254: in that one case.
17255: 
17256: Possible values for $varname are environment.lastname (or other item
17257: from the envirnment hash), user.name (or someother aspect about the
17258: user), resource.0.maxtries (or some other part and parameter of a
17259: resource)
17260: 
17261: =item *
17262: 
17263: directcondval($number) : get current value of a condition; reads from a state
17264: string
17265: 
17266: =item *
17267: 
17268: condval($condidx) : value of condition index based on state
17269: 
17270: =item *
17271: 
17272: metadata($uri,$what,$toolsymb,$liburi,$prefix,$depthcount) : request a
17273: resource's metadata, $what should be either a specific key, or either
17274: 'keys' (to get a list of possible keys) or 'packages' to get a list of
17275: packages that this resource currently uses, the last 3 arguments are 
17276: only used internally for recursive metadata.
17277: 
17278: the toolsymb is only used where the uri is for an external tool (for which
17279: the uri as well as the symb are guaranteed to be unique).
17280: 
17281: this function automatically caches all requests except any made recursively
17282: to retrieve a list of metadata keys for an imported library file ($liburi is 
17283: defined).
17284: 
17285: =item *
17286: 
17287: metadata_query($query,$custom,$customshow) : make a metadata query against the
17288: network of library servers; returns file handle of where SQL and regex results
17289: will be stored for query
17290: 
17291: =item *
17292: 
17293: symbread($filename,$donotrecurse,$ignorecachednull,$checkforblock,$possibles) : 
17294: return symbolic list entry (all arguments optional). 
17295: 
17296: Args: filename is the filename (including path) for the file for which a symb 
17297: is required; donotrecurse, if true will prevent calls to allowed() being made 
17298: to check access status if more than one resource was found in the bighash 
17299: (see rev. 1.249) to avoid an infinite loop if an ambiguous resource is part of 
17300: a randompick); ignorecachednull, if true will prevent a symb of '' being 
17301: returned if $env{$cache_str} is defined as ''; checkforblock if true will
17302: cause possible symbs to be checked to determine if they are subject to content
17303: blocking, if so they will not be included as possible symbs; possibles is a
17304: ref to a hash, which, as a side effect, will be populated with all possible 
17305: symbs (content blocking not tested).
17306:  
17307: returns the data handle
17308: 
17309: =item *
17310: 
17311: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
17312: and is a possible symb for the URL in $thisfn, and if is an encrypted
17313: resource that the user accessed using /enc/ returns a 1 on success, 0
17314: on failure, user must be in a course, as it assumes the existence of
17315: the course initial hash, and uses $env('request.course.id'}.  The third
17316: arg is an optional reference to a scalar.  If this arg is passed in the 
17317: call to symbverify, it will be set to 1 if the symb has been set to be 
17318: encrypted; otherwise it will be null.  
17319: 
17320: =item *
17321: 
17322: symbclean($symb) : removes versions numbers from a symb, returns the
17323: cleaned symb
17324: 
17325: =item *
17326: 
17327: is_on_map($uri) : checks if the $uri is somewhere on the current
17328: course map, user must be in a course for it to work.
17329: 
17330: =item *
17331: 
17332: numval($salt) : return random seed value (addend for rndseed)
17333: 
17334: =item *
17335: 
17336: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
17337: a random seed, all arguments are optional, if they aren't sent it uses the
17338: environment to derive them. Note: if symb isn't sent and it can't get one
17339: from &symbread it will use the current time as its return value
17340: 
17341: =item *
17342: 
17343: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
17344: unfakeable, receipt
17345: 
17346: =item *
17347: 
17348: receipt() : API to ireceipt working off of env values; given out to users
17349: 
17350: =item *
17351: 
17352: countacc($url) : count the number of accesses to a given URL
17353: 
17354: =item *
17355: 
17356: 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
17357: 
17358: =item *
17359: 
17360: 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)
17361: 
17362: =item *
17363: 
17364: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
17365: 
17366: =item *
17367: 
17368: devalidate($symb) : devalidate temporary spreadsheet calculations,
17369: forcing spreadsheet to reevaluate the resource scores next time.
17370: 
17371: =item * 
17372: 
17373: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
17374: when viewing in course context.
17375: 
17376:  input: six args -- filename (decluttered), course number, course domain,
17377:                     url, symb (if registered) and group (if this is a 
17378:                     group item -- e.g., bulletin board, group page etc.).
17379: 
17380:  output: array of five scalars --
17381:          $cfile -- url for file editing if editable on current server
17382:          $home -- homeserver of resource (i.e., for author if published,
17383:                                           or course if uploaded.).
17384:          $switchserver --  1 if server switch will be needed.
17385:          $forceedit -- 1 if icon/link should be to go to edit mode 
17386:          $forceview -- 1 if icon/link should be to go to view mode
17387: 
17388: =item *
17389: 
17390: is_course_upload($file,$cnum,$cdom)
17391: 
17392: Used in course context to determine if current file was uploaded to 
17393: the course (i.e., would be found in /userfiles/docs on the course's 
17394: homeserver.
17395: 
17396:   input: 3 args -- filename (decluttered), course number and course domain.
17397:   output: boolean -- 1 if file was uploaded.
17398: 
17399: =back
17400: 
17401: =head2 Storing/Retreiving Data
17402: 
17403: =over 4
17404: 
17405: =item *
17406: 
17407: store($storehash,$symb,$namespace,$udom,$uname,$laststore) : stores hash
17408: permanently for this url; hashref needs to be given and should be a \%hashname;
17409: the remaining args aren't required and if they aren't passed or are '' they will
17410: be derived from the env (with the exception of $laststore, which is an 
17411: optional arg used when a user's submission is stored in grading).
17412: $laststore is $version=$timestamp, where $version is the most recent version
17413: number retrieved for the corresponding $symb in the $namespace db file, and
17414: $timestamp is the timestamp for that transaction (UNIX time).
17415: $laststore is currently only passed when cstore() is called by 
17416: structuretags::finalize_storage().
17417: 
17418: =item *
17419: 
17420: cstore($storehash,$symb,$namespace,$udom,$uname,$laststore) : same as store
17421: but uses critical subroutine
17422: 
17423: =item *
17424: 
17425: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
17426: all args are optional
17427: 
17428: =item *
17429: 
17430: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
17431: dumps the complete (or key matching regexp) namespace into a hash
17432: ($udom, $uname, $regexp, $range are optional) for a namespace that is
17433: normally &store()ed into
17434: 
17435: $range should be either an integer '100' (give me the first 100
17436:                                            matching records)
17437:               or be  two integers sperated by a - with no spaces
17438:                  '30-50' (give me the 30th through the 50th matching
17439:                           records)
17440: 
17441: 
17442: =item *
17443: 
17444: putstore($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog) :
17445: replaces a &store() version of data with a replacement set of data
17446: for a particular resource in a namespace passed in the $storehash hash 
17447: reference. If $tolog is true, the transaction is logged in the courselog
17448: with an action=PUTSTORE.
17449: 
17450: =item *
17451: 
17452: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
17453: works very similar to store/cstore, but all data is stored in a
17454: temporary location and can be reset using tmpreset, $storehash should
17455: be a hash reference, returns nothing on success
17456: 
17457: =item *
17458: 
17459: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
17460: similar to restore, but all data is stored in a temporary location and
17461: can be reset using tmpreset. Returns a hash of values on success,
17462: error string otherwise.
17463: 
17464: =item *
17465: 
17466: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
17467: deltes all keys for $symb form the temporary storage hash.
17468: 
17469: =item *
17470: 
17471: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
17472: reference filled in from namesp ($udom and $uname are optional)
17473: 
17474: =item *
17475: 
17476: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
17477: namesp ($udom and $uname are optional)
17478: 
17479: =item *
17480: 
17481: dump($namespace,$udom,$uname,$regexp,$range) : 
17482: dumps the complete (or key matching regexp) namespace into a hash
17483: ($udom, $uname, $regexp, $range are optional)
17484: 
17485: $range should be either an integer '100' (give me the first 100
17486:                                            matching records)
17487:               or be  two integers sperated by a - with no spaces
17488:                  '30-50' (give me the 30th through the 50th matching
17489:                           records)
17490: =item *
17491: 
17492: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
17493: $store can be a scalar, an array reference, or if the amount to be 
17494: incremented is > 1, a hash reference.
17495: 
17496: ($udom and $uname are optional)
17497: 
17498: =item *
17499: 
17500: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
17501: ($udom and $uname are optional)
17502: 
17503: =item *
17504: 
17505: cput($namespace,$storehash,$udom,$uname) : critical put
17506: ($udom and $uname are optional)
17507: 
17508: =item *
17509: 
17510: newput($namespace,$storehash,$udom,$uname) :
17511: 
17512: Attempts to store the items in the $storehash, but only if they don't
17513: currently exist, if this succeeds you can be certain that you have 
17514: successfully created a new key value pair in the $namespace db.
17515: 
17516: 
17517: Args:
17518:  $namespace: name of database to store values to
17519:  $storehash: hashref to store to the db
17520:  $udom: (optional) domain of user containing the db
17521:  $uname: (optional) name of user caontaining the db
17522: 
17523: Returns:
17524:  'ok' -> succeeded in storing all keys of $storehash
17525:  'key_exists: <key>' -> failed to anything out of $storehash, as at
17526:                         least <key> already existed in the db (other
17527:                         requested keys may also already exist)
17528:  'error: <msg>' -> unable to tie the DB or other error occurred
17529:  'con_lost' -> unable to contact request server
17530:  'refused' -> action was not allowed by remote machine
17531: 
17532: 
17533: =item *
17534: 
17535: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
17536: reference filled in from namesp (encrypts the return communication)
17537: ($udom and $uname are optional)
17538: 
17539: =item *
17540: 
17541: log($udom,$name,$home,$message) : write to permanent log for user; use
17542: critical subroutine
17543: 
17544: =item *
17545: 
17546: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
17547: array reference filled in from namespace found in domain level on either
17548: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
17549: 
17550: =item *
17551: 
17552: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
17553: domain level either on specified domain server ($uhome) or primary domain 
17554: server ($udom and $uhome are optional)
17555: 
17556: =item * 
17557: 
17558: get_domain_defaults($target_domain,$ignore_cache) : returns hash with defaults 
17559: for: authentication, language, quotas, timezone, date locale, and portal URL in
17560: the target domain.
17561: 
17562: May also include additional key => value pairs for the following groups:
17563: 
17564: =over
17565: 
17566: =item
17567: disk quotas (MB allocated by default to portfolios and authoring spaces).
17568: 
17569: =over
17570: 
17571: =item defaultquota, authorquota
17572: 
17573: =back
17574: 
17575: =item
17576: tools (availability of aboutme page, blog, webDAV access for authoring spaces,
17577: portfolio for users).
17578: 
17579: =over
17580: 
17581: =item
17582: aboutme, blog, webdav, portfolio
17583: 
17584: =back
17585: 
17586: =item
17587: requestcourses: ability to request courses, and how requests are processed.
17588: 
17589: =over
17590: 
17591: =item
17592: official, unofficial, community, textbook, placement
17593: 
17594: =back
17595: 
17596: =item
17597: inststatus: types of institutional affiliation, and order in which they are displayed.
17598: 
17599: =over
17600: 
17601: =item
17602: inststatustypes, inststatusorder, inststatusguest
17603: 
17604: =back
17605: 
17606: =item
17607: coursedefaults: can PDF forms can be created, default credits for courses, default quotas (MB)
17608: for course's uploaded content.
17609: 
17610: =over
17611: 
17612: =item
17613: canuse_pdfforms, officialcredits, unofficialcredits, textbookcredits, officialquota, unofficialquota, 
17614: communityquota, textbookquota, placementquota
17615: 
17616: =back
17617: 
17618: =item
17619: usersessions: set options for hosting of your users in other domains, and hosting of users from other domains
17620: on your servers.
17621: 
17622: =over
17623: 
17624: =item 
17625: remotesessions, hostedsessions
17626: 
17627: =back
17628: 
17629: =back
17630: 
17631: In cases where a domain coordinator has never used the "Set Domain Configuration"
17632: utility to create a configuration.db file on a domain's primary library server 
17633: only the following domain defaults: auth_def, auth_arg_def, lang_def
17634: -- corresponding values are authentication type (internal, krb4, krb5,
17635: or localauth), initial password or a kerberos realm, language (e.g., en-us) -- 
17636: will be available. Values are retrieved from cache (if current), unless the
17637: optional $ignore_cache arg is true, or from domain's configuration.db (if available),
17638: or lastly from values in lonTabs/dns_domain,tab, or lonTabs/domain.tab.
17639: 
17640: Typical usage:
17641: 
17642: %domdefaults = &get_domain_defaults($target_domain);
17643: 
17644: =back
17645: 
17646: =head2 Network Status Functions
17647: 
17648: =over 4
17649: 
17650: =item *
17651: 
17652: dirlist() : return directory list based on URI (first arg).
17653: 
17654: Inputs: 1 required, 5 optional.
17655: 
17656: =over
17657: 
17658: =item 
17659: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
17660: 
17661: =item
17662: $userdomain - domain of user/course to be listed. Extracted from $uri if absent. 
17663: 
17664: =item
17665: $username -  username of user/course to be listed. Extracted from $uri if absent. 
17666: 
17667: =item
17668: $getpropath - boolean: 1 if prepend path using &propath(). 
17669: 
17670: =item
17671: $getuserdir - boolean: 1 if prepend path for "userfiles".
17672: 
17673: =item 
17674: $alternateRoot - path to prepend in place of path from $uri.
17675: 
17676: =back
17677: 
17678: Returns: Array of up to two items.
17679: 
17680: =over
17681: 
17682: a reference to an array of files/subdirectories
17683: 
17684: =over
17685: 
17686: Each element in the array of files/subdirectories is a & separated list of
17687: item name and the result of running stat on the item.  If dirlist was requested
17688: for a file instead of a directory, the item name will be ''. For a directory 
17689: listing, if the item is a metadata file, the element will end &N&M 
17690: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
17691: default copyright set (1).  
17692: 
17693: =back
17694: 
17695: a scalar containing error condition (if encountered).
17696: 
17697: =over
17698: 
17699: =item 
17700: no_host (no homeserver identified for $username:$domain).
17701: 
17702: =item 
17703: no_such_host (server contacted for listing not identified as valid host).
17704: 
17705: =item 
17706: con_lost (connection to remote server failed).
17707: 
17708: =item 
17709: refused (invalid $username:$domain received on lond side).
17710: 
17711: =item 
17712: no_such_dir (directory at specified path on lond side does not exist). 
17713: 
17714: =item 
17715: empty (directory at specified path on lond side is empty).
17716: 
17717: =over
17718: 
17719: This is currently not encountered because the &ls3, &ls2, 
17720: &ls (_handler) routines on the lond side do not filter out
17721: . and .. from a directory listing. 
17722: 
17723: =back
17724: 
17725: =back
17726: 
17727: =back
17728: 
17729: =item *
17730: 
17731: spareserver() : find server with least workload from spare.tab
17732: 
17733: 
17734: =item *
17735: 
17736: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
17737: if there is no corresponding loncapa host.
17738: 
17739: =back
17740: 
17741: 
17742: =head2 Apache Request
17743: 
17744: =over 4
17745: 
17746: =item *
17747: 
17748: ssi($url,%hash) : server side include, does a complete request cycle on url to
17749: localhost, posts hash
17750: 
17751: =back
17752: 
17753: =head2 Data to String to Data
17754: 
17755: =over 4
17756: 
17757: =item *
17758: 
17759: hash2str(%hash) : convert a hash into a string complete with escaping and '='
17760: and '&' separators, supports elements that are arrayrefs and hashrefs
17761: 
17762: =item *
17763: 
17764: hashref2str($hashref) : convert a hashref into a string complete with
17765: escaping and '=' and '&' separators, supports elements that are
17766: arrayrefs and hashrefs
17767: 
17768: =item *
17769: 
17770: arrayref2str($arrayref) : convert an arrayref into a string complete
17771: with escaping and '&' separators, supports elements that are arrayrefs
17772: and hashrefs
17773: 
17774: =item *
17775: 
17776: str2hash($string) : convert string to hash using unescaping and
17777: splitting on '=' and '&', supports elements that are arrayrefs and
17778: hashrefs
17779: 
17780: =item *
17781: 
17782: str2array($string) : convert string to hash using unescaping and
17783: splitting on '&', supports elements that are arrayrefs and hashrefs
17784: 
17785: =back
17786: 
17787: =head2 Logging Routines
17788: 
17789: 
17790: These routines allow one to make log messages in the lonnet.log and
17791: lonnet.perm logfiles.
17792: 
17793: =over 4
17794: 
17795: =item *
17796: 
17797: logtouch() : make sure the logfile, lonnet.log, exists
17798: 
17799: =item *
17800: 
17801: logthis() : append message to the normal lonnet.log file, it gets
17802: preiodically rolled over and deleted.
17803: 
17804: =item *
17805: 
17806: logperm() : append a permanent message to lonnet.perm.log, this log
17807: file never gets deleted by any automated portion of the system, only
17808: messages of critical importance should go in here.
17809: 
17810: 
17811: =back
17812: 
17813: =head2 General File Helper Routines
17814: 
17815: =over 4
17816: 
17817: =item *
17818: 
17819: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
17820: (a) files in /uploaded
17821:   (i) If a local copy of the file exists - 
17822:       compares modification date of local copy with last-modified date for 
17823:       definitive version stored on home server for course. If local copy is 
17824:       stale, requests a new version from the home server and stores it. 
17825:       If the original has been removed from the home server, then local copy 
17826:       is unlinked.
17827:   (ii) If local copy does not exist -
17828:       requests the file from the home server and stores it. 
17829:   
17830:   If $caller is 'uploadrep':  
17831:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
17832:     for request for files originally uploaded via DOCS. 
17833:      - returns 'ok' if fresh local copy now available, -1 otherwise.
17834:   
17835:   Otherwise:
17836:      This indicates a call from the content generation phase of the request.
17837:      -  returns the entire contents of the file or -1.
17838:      
17839: (b) files in /res
17840:    - returns the entire contents of a file or -1; 
17841:    it properly subscribes to and replicates the file if neccessary.
17842: 
17843: 
17844: =item *
17845: 
17846: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
17847:                   reference
17848: 
17849: returns either a stat() list of data about the file or an empty list
17850: if the file doesn't exist or couldn't find out about it (connection
17851: problems or user unknown)
17852: 
17853: =item *
17854: 
17855: filelocation($dir,$file) : returns file system location of a file
17856: based on URI; meant to be "fairly clean" absolute reference, $dir is a
17857: directory that relative $file lookups are to looked in ($dir of /a/dir
17858: and a file of ../bob will become /a/bob)
17859: 
17860: =item *
17861: 
17862: hreflocation($dir,$file) : returns file system location or a URL; same as
17863: filelocation except for hrefs
17864: 
17865: =item *
17866: 
17867: declutter() : declutters URLs -- remove beginning slashes, 'res' etc.
17868: also removes beginning /home/httpd/html unless /priv/ follows it.
17869: 
17870: =back
17871: 
17872: =head2 Usererfile file routines (/uploaded*)
17873: 
17874: =over 4
17875: 
17876: =item *
17877: 
17878: userfileupload(): main rotine for putting a file in a user or course's
17879:                   filespace, arguments are,
17880: 
17881:  formname - required - this is the name of the element in $env where the
17882:            filename, and the contents of the file to create/modifed exist
17883:            the filename is in $env{'form.'.$formname.'.filename'} and the
17884:            contents of the file is located in $env{'form.'.$formname}
17885:  context - if coursedoc, store the file in the course of the active role
17886:              of the current user; 
17887:            if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
17888:            if 'canceloverwrite': delete file in tmp/overwrites directory
17889:  subdir - required - subdirectory to put the file in under ../userfiles/
17890:          if undefined, it will be placed in "unknown"
17891: 
17892:  (This routine calls clean_filename() to remove any dangerous
17893:  characters from the filename, and then calls finuserfileupload() to
17894:  complete the transaction)
17895: 
17896:  returns either the url of the uploaded file (/uploaded/....) if successful
17897:  and /adm/notfound.html if unsuccessful
17898: 
17899: =item *
17900: 
17901: clean_filename(): routine for cleaing a filename up for storage in
17902:                  userfile space, argument is:
17903: 
17904:  filename - proposed filename
17905: 
17906: returns: the new clean filename
17907: 
17908: =item *
17909: 
17910: finishuserfileupload(): routine that creates and sends the file to
17911: userspace, probably shouldn't be called directly
17912: 
17913:   docuname: username or courseid of destination for the file
17914:   docudom: domain of user/course of destination for the file
17915:   formname: same as for userfileupload()
17916:   fname: filename (including subdirectories) for the file
17917:   parser: if 'parse', will parse (html) file to extract references to objects, links etc.
17918:           if hashref, and context is scantron, will convert csv format to standard format
17919:   allfiles: reference to hash used to store objects found by parser
17920:   codebase: reference to hash used for codebases of java objects found by parser
17921:   thumbwidth: width (pixels) of thumbnail to be created for uploaded image
17922:   thumbheight: height (pixels) of thumbnail to be created for uploaded image
17923:   resizewidth: width to be used to resize image using resizeImage from ImageMagick
17924:   resizeheight: height to be used to resize image using resizeImage from ImageMagick
17925:   context: if 'overwrite', will move the uploaded file from its temporary location to
17926:             userfiles to facilitate overwriting a previously uploaded file with same name.
17927:   mimetype: reference to scalar to accommodate mime type determined
17928:             from File::MMagic if $parser = parse.
17929: 
17930:  returns either the url of the uploaded file (/uploaded/....) if successful
17931:  and /adm/notfound.html if unsuccessful (or an error message if context 
17932:  was 'overwrite').
17933:  
17934: 
17935: =item *
17936: 
17937: renameuserfile(): renames an existing userfile to a new name
17938: 
17939:   Args:
17940:    docuname: username or courseid of destination for the file
17941:    docudom: domain of user/course of destination for the file
17942:    old: current file name (including any subdirs under userfiles)
17943:    new: desired file name (including any subdirs under userfiles)
17944: 
17945: =item *
17946: 
17947: mkdiruserfile(): creates a directory is a userfiles dir
17948: 
17949:   Args:
17950:    docuname: username or courseid of destination for the file
17951:    docudom: domain of user/course of destination for the file
17952:    dir: dir to create (including any subdirs under userfiles)
17953: 
17954: =item *
17955: 
17956: removeuserfile(): removes a file that exists in userfiles
17957: 
17958:   Args:
17959:    docuname: username or courseid of destination for the file
17960:    docudom: domain of user/course of destination for the file
17961:    fname: filname to delete (including any subdirs under userfiles)
17962: 
17963: =item *
17964: 
17965: removeuploadedurl(): convience function for removeuserfile()
17966: 
17967:   Args:
17968:    url:  a full /uploaded/... url to delete
17969: 
17970: =item * 
17971: 
17972: get_portfile_permissions():
17973:   Args:
17974:     domain: domain of user or course contain the portfolio files
17975:     user: name of user or num of course contain the portfolio files
17976:   Returns:
17977:     hashref of a dump of the proper file_permissions.db
17978:    
17979: 
17980: =item * 
17981: 
17982: get_access_controls():
17983: 
17984: Args:
17985:   current_permissions: the hash ref returned from get_portfile_permissions()
17986:   group: (optional) the group you want the files associated with
17987:   file: (optional) the file you want access info on
17988: 
17989: Returns:
17990:     a hash (keys are file names) of hashes containing
17991:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
17992:         values are XML containing access control settings (see below) 
17993: 
17994: Internal notes:
17995: 
17996:  access controls are stored in file_permissions.db as key=value pairs.
17997:     key -> path to file/file_name\0uniqueID:scope_end_start
17998:         where scope -> public,guest,course,group,domains or users.
17999:               end -> UNIX time for end of access (0 -> no end date)
18000:               start -> UNIX time for start of access
18001: 
18002:     value -> XML description of access control
18003:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
18004:             <start></start>
18005:             <end></end>
18006: 
18007:             <password></password>  for scope type = guest
18008: 
18009:             <domain></domain>     for scope type = course or group
18010:             <number></number>
18011:             <roles id="">
18012:              <role></role>
18013:              <access></access>
18014:              <section></section>
18015:              <group></group>
18016:             </roles>
18017: 
18018:             <dom></dom>         for scope type = domains
18019: 
18020:             <users>             for scope type = users
18021:              <user>
18022:               <uname></uname>
18023:               <udom></udom>
18024:              </user>
18025:             </users>
18026:            </scope> 
18027:               
18028:  Access data is also aggregated for each file in an additional key=value pair:
18029:  key -> path to file/file_name\0accesscontrol 
18030:  value -> reference to hash
18031:           hash contains key = value pairs
18032:           where key = uniqueID:scope_end_start
18033:                 value = UNIX time record was last updated
18034: 
18035:           Used to improve speed of look-ups of access controls for each file.  
18036:  
18037:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
18038: 
18039: =item *
18040: 
18041: modify_access_controls():
18042: 
18043: Modifies access controls for a portfolio file
18044: Args
18045: 1. file name
18046: 2. reference to hash of required changes,
18047: 3. domain
18048: 4. username
18049:   where domain,username are the domain of the portfolio owner 
18050:   (either a user or a course) 
18051: 
18052: Returns:
18053: 1. result of additions or updates ('ok' or 'error', with error message). 
18054: 2. result of deletions ('ok' or 'error', with error message).
18055: 3. reference to hash of any new or updated access controls.
18056: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
18057:    key = integer (inbound ID)
18058:    value = uniqueID
18059: 
18060: =item *
18061: 
18062: get_timebased_id():
18063: 
18064: Attempts to get a unique timestamp-based suffix for use with items added to a 
18065: course via the Course Editor (e.g., folders, composite pages, 
18066: group bulletin boards).
18067: 
18068: Args: (first three required; six others optional)
18069: 
18070: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
18071:    docssequence, or name of group
18072: 
18073: 2. keyid (alphanumeric): name of temporary locking key in hash,
18074:    e.g., num, boardids
18075: 
18076: 3. namespace: name of gdbm file used to store suffixes already assigned;  
18077:    file will be named nohist_namespace.db
18078: 
18079: 4. cdom: domain of course; default is current course domain from %env
18080: 
18081: 5. cnum: course number; default is current course number from %env
18082: 
18083: 6. idtype: set to concat if an additional digit is to be appended to the 
18084:    unix timestamp to form the suffix, if the plain timestamp is already
18085:    in use.  Default is to not do this, but simply increment the unix 
18086:    timestamp by 1 until a unique key is obtained.
18087: 
18088: 7. who: holder of locking key; defaults to user:domain for user.
18089: 
18090: 8. locktries: number of attempts to obtain a lock (sleep of 1s before 
18091:    retrying); default is 3.
18092: 
18093: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.  
18094: 
18095: Returns:
18096: 
18097: 1. suffix obtained (numeric)
18098: 
18099: 2. result of deleting locking key (ok if deleted, or lock never obtained)
18100: 
18101: 3. error: contains (localized) error message if an error occurred.
18102: 
18103: 
18104: =back
18105: 
18106: =head2 HTTP Helper Routines
18107: 
18108: =over 4
18109: 
18110: =item *
18111: 
18112: escape() : unpack non-word characters into CGI-compatible hex codes
18113: 
18114: =item *
18115: 
18116: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
18117: 
18118: =back
18119: 
18120: =head1 PRIVATE SUBROUTINES
18121: 
18122: =head2 Underlying communication routines (Shouldn't call)
18123: 
18124: =over 4
18125: 
18126: =item *
18127: 
18128: subreply() : tries to pass a message to lonc, returns con_lost if incapable
18129: 
18130: =item *
18131: 
18132: reply() : uses subreply to send a message to remote machine, logs all failures
18133: 
18134: =item *
18135: 
18136: critical() : passes a critical message to another server; if cannot
18137: get through then place message in connection buffer directory and
18138: returns con_delayed, if incapable of saving message, returns
18139: con_failed
18140: 
18141: =item *
18142: 
18143: reconlonc() : tries to reconnect lonc client processes.
18144: 
18145: =back
18146: 
18147: =head2 Resource Access Logging
18148: 
18149: =over 4
18150: 
18151: =item *
18152: 
18153: flushcourselogs() : flush (save) buffer logs and access logs
18154: 
18155: =item *
18156: 
18157: courselog($what) : save message for course in hash
18158: 
18159: =item *
18160: 
18161: courseacclog($what) : save message for course using &courselog().  Perform
18162: special processing for specific resource types (problems, exams, quizzes, etc).
18163: 
18164: =item *
18165: 
18166: goodbye() : flush course logs and log shutting down; it is called in srm.conf
18167: as a PerlChildExitHandler
18168: 
18169: =back
18170: 
18171: =head2 Other
18172: 
18173: =over 4
18174: 
18175: =item *
18176: 
18177: symblist($mapname,%newhash) : update symbolic storage links
18178: 
18179: =back
18180: 
18181: =cut
18182: 

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