File:  [LON-CAPA] / loncom / lonnet / perl / lonnet.pm
Revision 1.1520: download - view: text, annotated - select for diffs
Sat Dec 23 02:17:39 2023 UTC (6 months, 3 weeks ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Availability of "Course Authoring Space" set in Course Community defaults
  in domain (by container type), can be overridden for specific course(s).
- Add some help files for Course Editor and View/modify a course/community
- Add icons for use of Course Authoring Space.

    1: # The LearningOnline Network
    2: # TCP networking package
    3: #
    4: # $Id: lonnet.pm,v 1.1520 2023/12/23 02:17:39 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');
 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) = @_;
 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 ($public,$guest,@domains,@users,@courses,@groups,@ips);
 8001:     my $now = time;
 8002:     if (ref($access_hash) eq 'HASH') {
 8003:         foreach my $key (keys(%{$access_hash})) {
 8004:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
 8005:             if ($start > $now) {
 8006:                 next;
 8007:             }
 8008:             if ($end && $end<$now) {
 8009:                 next;
 8010:             }
 8011:             if ($scope eq 'public') {
 8012:                 $public = $key;
 8013:                 last;
 8014:             } elsif ($scope eq 'guest') {
 8015:                 $guest = $key;
 8016:             } elsif ($scope eq 'domains') {
 8017:                 push(@domains,$key);
 8018:             } elsif ($scope eq 'users') {
 8019:                 push(@users,$key);
 8020:             } elsif ($scope eq 'course') {
 8021:                 push(@courses,$key);
 8022:             } elsif ($scope eq 'group') {
 8023:                 push(@groups,$key);
 8024:             } elsif ($scope eq 'ip') {
 8025:                 push(@ips,$key);
 8026:             }
 8027:         }
 8028:         if ($public) {
 8029:             return 'ok';
 8030:         } elsif (@ips > 0) {
 8031:             my $allowed;
 8032:             foreach my $ipkey (@ips) {
 8033:                 if (ref($access_hash->{$ipkey}{'ip'}) eq 'ARRAY') {
 8034:                     if (&Apache::loncommon::check_ip_acc(join(',',@{$access_hash->{$ipkey}{'ip'}}),$clientip)) {
 8035:                         $allowed = 1;
 8036:                         last; 
 8037:                     }
 8038:                 }
 8039:             }
 8040:             if ($allowed) {
 8041:                 return 'ok';
 8042:             }
 8043:         }
 8044:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 8045:             if ($guest) {
 8046:                 return $guest;
 8047:             }
 8048:         } else {
 8049:             if (@domains > 0) {
 8050:                 foreach my $domkey (@domains) {
 8051:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
 8052:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
 8053:                             return 'ok';
 8054:                         }
 8055:                     }
 8056:                 }
 8057:             }
 8058:             if (@users > 0) {
 8059:                 foreach my $userkey (@users) {
 8060:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
 8061:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
 8062:                             if (ref($item) eq 'HASH') {
 8063:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
 8064:                                     ($item->{'udom'} eq $env{'user.domain'})) {
 8065:                                     return 'ok';
 8066:                                 }
 8067:                             }
 8068:                         }
 8069:                     } 
 8070:                 }
 8071:             }
 8072:             my %roleshash;
 8073:             my @courses_and_groups = @courses;
 8074:             push(@courses_and_groups,@groups); 
 8075:             if (@courses_and_groups > 0) {
 8076:                 my (%allgroups,%allroles); 
 8077:                 my ($start,$end,$role,$sec,$group);
 8078:                 foreach my $envkey (%env) {
 8079:                     if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
 8080:                         my $cid = $2.'_'.$3; 
 8081:                         if ($1 eq 'gr') {
 8082:                             $group = $4;
 8083:                             $allgroups{$cid}{$group} = $env{$envkey};
 8084:                         } else {
 8085:                             if ($4 eq '') {
 8086:                                 $sec = 'none';
 8087:                             } else {
 8088:                                 $sec = $4;
 8089:                             }
 8090:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
 8091:                         }
 8092:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
 8093:                         my $cid = $2.'_'.$3;
 8094:                         if ($4 eq '') {
 8095:                             $sec = 'none';
 8096:                         } else {
 8097:                             $sec = $4;
 8098:                         }
 8099:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
 8100:                     }
 8101:                 }
 8102:                 if (keys(%allroles) == 0) {
 8103:                     return;
 8104:                 }
 8105:                 foreach my $key (@courses_and_groups) {
 8106:                     my %content = %{$$access_hash{$key}};
 8107:                     my $cnum = $content{'number'};
 8108:                     my $cdom = $content{'domain'};
 8109:                     my $cid = $cdom.'_'.$cnum;
 8110:                     if (!exists($allroles{$cid})) {
 8111:                         next;
 8112:                     }    
 8113:                     foreach my $role_id (keys(%{$content{'roles'}})) {
 8114:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
 8115:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
 8116:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
 8117:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
 8118:                         foreach my $role (keys(%{$allroles{$cid}})) {
 8119:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
 8120:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
 8121:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
 8122:                                         if (grep/^all$/,@sections) {
 8123:                                             return 'ok';
 8124:                                         } else {
 8125:                                             if (grep/^$sec$/,@sections) {
 8126:                                                 return 'ok';
 8127:                                             }
 8128:                                         }
 8129:                                     }
 8130:                                 }
 8131:                                 if (keys(%{$allgroups{$cid}}) == 0) {
 8132:                                     if (grep/^none$/,@groups) {
 8133:                                         return 'ok';
 8134:                                     }
 8135:                                 } else {
 8136:                                     if (grep/^all$/,@groups) {
 8137:                                         return 'ok';
 8138:                                     } 
 8139:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
 8140:                                         if (grep/^$group$/,@groups) {
 8141:                                             return 'ok';
 8142:                                         }
 8143:                                     }
 8144:                                 } 
 8145:                             }
 8146:                         }
 8147:                     }
 8148:                 }
 8149:             }
 8150:             if ($guest) {
 8151:                 return $guest;
 8152:             }
 8153:         }
 8154:     }
 8155:     return;
 8156: }
 8157: 
 8158: sub course_group_datechecker {
 8159:     my ($dates,$now,$status) = @_;
 8160:     my ($start,$end) = split(/\./,$dates);
 8161:     if (!$start && !$end) {
 8162:         return 'ok';
 8163:     }
 8164:     if (grep/^active$/,@{$status}) {
 8165:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
 8166:             return 'ok';
 8167:         }
 8168:     }
 8169:     if (grep/^previous$/,@{$status}) {
 8170:         if ($end > $now ) {
 8171:             return 'ok';
 8172:         }
 8173:     }
 8174:     if (grep/^future$/,@{$status}) {
 8175:         if ($start > $now) {
 8176:             return 'ok';
 8177:         }
 8178:     }
 8179:     return; 
 8180: }
 8181: 
 8182: sub parse_portfolio_url {
 8183:     my ($url) = @_;
 8184: 
 8185:     my ($type,$udom,$unum,$group,$file_name);
 8186:     
 8187:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
 8188: 	$type = 1;
 8189:         $udom = $1;
 8190:         $unum = $2;
 8191:         $file_name = $3;
 8192:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
 8193: 	$type = 2;
 8194:         $udom = $1;
 8195:         $unum = $2;
 8196:         $group = $3;
 8197:         $file_name = $3.'/'.$4;
 8198:     }
 8199:     if (wantarray) {
 8200: 	return ($type,$udom,$unum,$file_name,$group);
 8201:     }
 8202:     return $type;
 8203: }
 8204: 
 8205: sub is_portfolio_url {
 8206:     my ($url) = @_;
 8207:     return scalar(&parse_portfolio_url($url));
 8208: }
 8209: 
 8210: sub is_portfolio_file {
 8211:     my ($file) = @_;
 8212:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
 8213:         return 1;
 8214:     }
 8215:     return;
 8216: }
 8217: 
 8218: sub is_coursetool_logo {
 8219:     my ($uri) = @_;
 8220:     if ($env{'request.course.id'}) {
 8221:         my $courseurl = &courseid_to_courseurl($env{'request.course.id'});
 8222:         if ($uri =~ m{^/*uploaded\Q$courseurl\E/toollogo/\d+/[^/]+$}) {
 8223:             return 1;
 8224:         }
 8225:     }
 8226:     return;
 8227: }
 8228: 
 8229: sub usertools_access {
 8230:     my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
 8231:     my ($access,%tools);
 8232:     if ($context eq '') {
 8233:         $context = 'tools';
 8234:     }
 8235:     if ($context eq 'requestcourses') {
 8236:         %tools = (
 8237:                       official   => 1,
 8238:                       unofficial => 1,
 8239:                       community  => 1,
 8240:                       textbook   => 1,
 8241:                       placement  => 1,
 8242:                       lti        => 1,
 8243:                  );
 8244:     } elsif ($context eq 'requestauthor') {
 8245:         %tools = (
 8246:                       requestauthor => 1,
 8247:                  );
 8248:     } elsif ($context eq 'authordefaults') {
 8249:         %tools = (
 8250:                       webdav    => 1,
 8251:                  );
 8252:     } else {
 8253:         %tools = (
 8254:                       aboutme   => 1,
 8255:                       blog      => 1,
 8256:                       portfolio => 1,
 8257:                       portaccess => 1,
 8258:                       timezone  => 1,
 8259:                  );
 8260:     }
 8261:     return if (!defined($tools{$tool}));
 8262: 
 8263:     if (($udom eq '') || ($uname eq '')) {
 8264:         $udom = $env{'user.domain'};
 8265:         $uname = $env{'user.name'};
 8266:     }
 8267: 
 8268:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 8269:         if ($action ne 'reload') {
 8270:             if ($context eq 'requestcourses') {
 8271:                 return $env{'environment.canrequest.'.$tool};
 8272:             } elsif ($context eq 'requestauthor') {
 8273:                 return $env{'environment.canrequest.author'};
 8274:             } elsif ($context eq 'authordefaults') {
 8275:                 if ($tool eq 'webdav') {
 8276:                     return $env{'environment.availabletools.'.$tool};
 8277:                 }
 8278:             } else {
 8279:                 return $env{'environment.availabletools.'.$tool};
 8280:             }
 8281:         }
 8282:     }
 8283: 
 8284:     my ($toolstatus,$inststatus,$envkey);
 8285:     if ($context eq 'requestauthor') {
 8286:         $envkey = $context;
 8287:     } elsif ($context eq 'authordefaults') {
 8288:         if ($tool eq 'webdav') {
 8289:             $envkey = 'tools.'.$tool;
 8290:         }
 8291:     } else {
 8292:         $envkey = $context.'.'.$tool;
 8293:     }
 8294: 
 8295:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
 8296:          ($action ne 'reload')) {
 8297:         $toolstatus = $env{'environment.'.$envkey};
 8298:         $inststatus = $env{'environment.inststatus'};
 8299:     } else {
 8300:         if (ref($userenvref) eq 'HASH') {
 8301:             $toolstatus = $userenvref->{$envkey};
 8302:             $inststatus = $userenvref->{'inststatus'};
 8303:         } else {
 8304:             my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
 8305:             $toolstatus = $userenv{$envkey};
 8306:             $inststatus = $userenv{'inststatus'};
 8307:         }
 8308:     }
 8309: 
 8310:     if ($toolstatus ne '') {
 8311:         if ($toolstatus) {
 8312:             $access = 1;
 8313:         } else {
 8314:             $access = 0;
 8315:         }
 8316:         return $access;
 8317:     }
 8318: 
 8319:     my ($is_adv,%domdef);
 8320:     if (ref($is_advref) eq 'HASH') {
 8321:         $is_adv = $is_advref->{'is_adv'};
 8322:     } else {
 8323:         $is_adv = &is_advanced_user($udom,$uname);
 8324:     }
 8325:     if (ref($domdefref) eq 'HASH') {
 8326:         %domdef = %{$domdefref};
 8327:     } else {
 8328:         %domdef = &get_domain_defaults($udom);
 8329:     }
 8330:     if (ref($domdef{$tool}) eq 'HASH') {
 8331:         if ($is_adv) {
 8332:             if ($domdef{$tool}{'_LC_adv'} ne '') {
 8333:                 if ($domdef{$tool}{'_LC_adv'}) { 
 8334:                     $access = 1;
 8335:                 } else {
 8336:                     $access = 0;
 8337:                 }
 8338:                 return $access;
 8339:             }
 8340:         }
 8341:         if ($inststatus ne '') {
 8342:             my ($hasaccess,$hasnoaccess);
 8343:             foreach my $affiliation (split(/:/,$inststatus)) {
 8344:                 if ($domdef{$tool}{$affiliation} ne '') { 
 8345:                     if ($domdef{$tool}{$affiliation}) {
 8346:                         $hasaccess = 1;
 8347:                     } else {
 8348:                         $hasnoaccess = 1;
 8349:                     }
 8350:                 }
 8351:             }
 8352:             if ($hasaccess || $hasnoaccess) {
 8353:                 if ($hasaccess) {
 8354:                     $access = 1;
 8355:                 } elsif ($hasnoaccess) {
 8356:                     $access = 0; 
 8357:                 }
 8358:                 return $access;
 8359:             }
 8360:         } else {
 8361:             if ($domdef{$tool}{'default'} ne '') {
 8362:                 if ($domdef{$tool}{'default'}) {
 8363:                     $access = 1;
 8364:                 } elsif ($domdef{$tool}{'default'} == 0) {
 8365:                     $access = 0;
 8366:                 }
 8367:                 return $access;
 8368:             }
 8369:         }
 8370:     } else {
 8371:         if (($context eq 'tools') && ($tool ne 'webdav')) {
 8372:             $access = 1;
 8373:         } else {
 8374:             $access = 0;
 8375:         }
 8376:         return $access;
 8377:     }
 8378: }
 8379: 
 8380: sub is_course_owner {
 8381:     my ($cdom,$cnum,$udom,$uname) = @_;
 8382:     if (($udom eq '') || ($uname eq '')) {
 8383:         $udom = $env{'user.domain'};
 8384:         $uname = $env{'user.name'};
 8385:     }
 8386:     unless (($udom eq '') || ($uname eq '')) {
 8387:         if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
 8388:             if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
 8389:                 return 1;
 8390:             } else {
 8391:                 my %courseinfo = &coursedescription($cdom.'/'.$cnum);
 8392:                 if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
 8393:                     return 1;
 8394:                 }
 8395:             }
 8396:         }
 8397:     }
 8398:     return;
 8399: }
 8400: 
 8401: sub is_advanced_user {
 8402:     my ($udom,$uname,$nocache) = @_;
 8403:     my ($is_adv,$is_author,$use_cache,$hashid);
 8404:     if ($udom ne '' && $uname ne '') {
 8405:         if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 8406:             if (wantarray) {
 8407:                 return ($env{'user.adv'},$env{'user.author'});
 8408:             } else {
 8409:                 return $env{'user.adv'};
 8410:             }
 8411:         } elsif (!$nocache) {
 8412:             $use_cache = 1;
 8413:             $hashid = "$udom:$uname";  
 8414:             my ($info,$cached)=&is_cached_new('isadvau',$hashid);
 8415:             if ($cached) {
 8416:                 ($is_adv,$is_author) = split(/:/,$info);
 8417:                 if (wantarray) {
 8418:                     return ($is_adv,$is_author);
 8419:                 }
 8420:                 return $is_adv; 
 8421:             }
 8422:         }
 8423:     }
 8424:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
 8425:     my %allroles;
 8426:     foreach my $role (keys(%roleshash)) {
 8427:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
 8428:         my $area = '/'.$tdomain.'/'.$trest;
 8429:         if ($sec ne '') {
 8430:             $area .= '/'.$sec;
 8431:         }
 8432:         if (($area ne '') && ($trole ne '')) {
 8433:             my $spec=$trole.'.'.$area;
 8434:             if ($trole =~ /^cr\//) {
 8435:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
 8436:             } elsif ($trole ne 'gr') {
 8437:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
 8438:             }
 8439:             if ($trole eq 'au') {
 8440:                 $is_author = 1;
 8441:             }
 8442:         }
 8443:     }
 8444:     foreach my $role (keys(%allroles)) {
 8445:         last if ($is_adv);
 8446:         foreach my $item (split(/:/,$allroles{$role})) {
 8447:             if ($item ne '') {
 8448:                 my ($privilege,$restrictions)=split(/&/,$item);
 8449:                 if ($privilege eq 'adv') {
 8450:                     $is_adv = 1;
 8451:                     last;
 8452:                 }
 8453:             }
 8454:         }
 8455:     }
 8456:     if ($use_cache) {
 8457:         my $cachetime = 600;
 8458:         &do_cache_new('isadvau',$hashid,$is_adv.':'.$is_author,$cachetime);
 8459:     }
 8460:     if (wantarray) {
 8461:         return ($is_adv,$is_author);
 8462:     }
 8463:     return $is_adv;
 8464: }
 8465: 
 8466: sub check_can_request {
 8467:     my ($dom,$can_request,$request_domains,$uname,$udom) = @_;
 8468:     my $canreq = 0;
 8469:     if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
 8470:         $uname = $env{'user.name'};
 8471:         $udom = $env{'user.domain'};
 8472:     }
 8473:     my ($types,$typename) = &Apache::loncommon::course_types();
 8474:     my @options = ('approval','validate','autolimit');
 8475:     my $optregex = join('|',@options);
 8476:     if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
 8477:         my %willtrust;
 8478:         foreach my $type (@{$types}) {
 8479:             if (&usertools_access($uname,$udom,$type,undef,
 8480:                                   'requestcourses')) {
 8481:                 $canreq ++;
 8482:                 if (ref($request_domains) eq 'HASH') {
 8483:                     push(@{$request_domains->{$type}},$udom);
 8484:                 }
 8485:                 if ($dom eq $udom) {
 8486:                     $can_request->{$type} = 1;
 8487:                 }
 8488:             }
 8489:             if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '') &&
 8490:                 ($env{'environment.reqcrsotherdom.'.$type} ne '')) {
 8491:                 my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
 8492:                 if (@curr > 0) {
 8493:                     foreach my $item (@curr) {
 8494:                         if (ref($request_domains) eq 'HASH') {
 8495:                             my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
 8496:                             if ($otherdom ne '') {
 8497:                                 unless (exists($willtrust{$otherdom})) {
 8498:                                     $willtrust{$otherdom} = &will_trust('reqcrs',$env{'user.domain'},$otherdom);
 8499:                                 }
 8500:                                 if ($willtrust{$otherdom}) {
 8501:                                     if (ref($request_domains->{$type}) eq 'ARRAY') {
 8502:                                         unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
 8503:                                             push(@{$request_domains->{$type}},$otherdom);
 8504:                                         }
 8505:                                     } else {
 8506:                                         push(@{$request_domains->{$type}},$otherdom);
 8507:                                     }
 8508:                                 }
 8509:                             }
 8510:                         }
 8511:                     }
 8512:                     unless ($dom eq $env{'user.domain'}) {
 8513:                         $canreq ++;
 8514:                         if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
 8515:                             $can_request->{$type} = 1;
 8516:                         }
 8517:                     }
 8518:                 }
 8519:             }
 8520:         }
 8521:     }
 8522:     return $canreq;
 8523: }
 8524: 
 8525: # ---------------------------------------------- Custom access rule evaluation
 8526: 
 8527: sub customaccess {
 8528:     my ($priv,$uri)=@_;
 8529:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
 8530:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
 8531:     $udom = &LONCAPA::clean_domain($udom);
 8532:     $ucrs = &LONCAPA::clean_username($ucrs);
 8533:     my $access=0;
 8534:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
 8535: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
 8536: 	if ($type eq 'user') {
 8537: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
 8538: 		my ($tdom,$tuname)=split(m{/},$scope);
 8539: 		if ($tdom) {
 8540: 		    if ($tdom ne $env{'user.domain'}) { next; }
 8541: 		}
 8542: 		if ($tuname) {
 8543: 		    if ($tuname ne $env{'user.name'}) { next; }
 8544: 		}
 8545: 		$access=($effect eq 'allow');
 8546: 		last;
 8547: 	    }
 8548: 	} else {
 8549: 	    if ($role) {
 8550: 		if ($role ne $urole) { next; }
 8551: 	    }
 8552: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
 8553: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
 8554: 		if ($tdom) {
 8555: 		    if ($tdom ne $udom) { next; }
 8556: 		}
 8557: 		if ($tcrs) {
 8558: 		    if ($tcrs ne $ucrs) { next; }
 8559: 		}
 8560: 		if ($tsec) {
 8561: 		    if ($tsec ne $usec) { next; }
 8562: 		}
 8563: 		$access=($effect eq 'allow');
 8564: 		last;
 8565: 	    }
 8566: 	    if ($realm eq '' && $role eq '') {
 8567: 		$access=($effect eq 'allow');
 8568: 	    }
 8569: 	}
 8570:     }
 8571:     return $access;
 8572: }
 8573: 
 8574: # ------------------------------------------------- Check for a user privilege
 8575: 
 8576: sub allowed {
 8577:     my ($priv,$uri,$symb,$role,$clientip,$noblockcheck,$ignorecache,$nodeeplinkcheck,$nodeeplinkout)=@_;
 8578:     my $ver_orguri=$uri;
 8579:     $uri=&deversion($uri);
 8580:     my $orguri=$uri;
 8581:     $uri=&declutter($uri);
 8582: 
 8583:     if ($priv eq 'evb') {
 8584: # Evade communication block restrictions for specified role in a course or domain
 8585:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
 8586:             return $1;
 8587:         } else {
 8588:             return;
 8589:         }
 8590:     }
 8591: 
 8592:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
 8593: # Free bre access to adm and meta resources
 8594:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard|viewclasslist|aboutme|ext\.tool)$})) 
 8595: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
 8596: 	&& ($priv eq 'bre')) {
 8597: 	return 'F';
 8598:     }
 8599: 
 8600: # Free bre access to user's own portfolio contents
 8601:     my ($space,$domain,$name,@dir)=split('/',$uri);
 8602:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
 8603: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
 8604:         my %setters;
 8605:         my ($startblock,$endblock,$triggerblock,$by_ip,$blockdom) = 
 8606:             &Apache::loncommon::blockcheck(\%setters,'port',$clientip);
 8607:         if (($startblock && $endblock) || ($by_ip)) {
 8608:             return 'B';
 8609:         } else {
 8610:             return 'F';
 8611:         }
 8612:     }
 8613: 
 8614: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
 8615:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
 8616:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
 8617:         if (exists($env{'request.course.id'})) {
 8618:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 8619:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 8620:             if (($domain eq $cdom) && ($name eq $cnum)) {
 8621:                 my $courseprivid=$env{'request.course.id'};
 8622:                 $courseprivid=~s/\_/\//;
 8623:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
 8624:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
 8625:                     return $1; 
 8626:                 } else {
 8627:                     if ($env{'request.course.sec'}) {
 8628:                         $courseprivid.='/'.$env{'request.course.sec'};
 8629:                     }
 8630:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
 8631:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
 8632:                         return $2;
 8633:                     }
 8634:                 }
 8635:             }
 8636:         }
 8637:     }
 8638: 
 8639: # Free bre to public access
 8640: 
 8641:     if ($priv eq 'bre') {
 8642:         my $copyright;
 8643:         unless ($uri =~ /ext\.tool/) {
 8644:             $copyright=&metadata($uri,'copyright');
 8645:         }
 8646: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
 8647:            return 'F'; 
 8648:         }
 8649:         if ($copyright eq 'priv') {
 8650:             $uri=~/([^\/]+)\/([^\/]+)\//;
 8651: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
 8652: 		return '';
 8653:             }
 8654:         }
 8655:         if ($copyright eq 'domain') {
 8656:             $uri=~/([^\/]+)\/([^\/]+)\//;
 8657: 	    unless (($env{'user.domain'} eq $1) ||
 8658:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
 8659: 		return '';
 8660:             }
 8661:         }
 8662:         if ($env{'request.role'}=~ /li\.\//) {
 8663:             # Library role, so allow browsing of resources in this domain.
 8664:             return 'F';
 8665:         }
 8666:         if ($copyright eq 'custom') {
 8667: 	    unless (&customaccess($priv,$uri)) { return ''; }
 8668:         }
 8669:     }
 8670:     # Domain coordinator is trying to create a course
 8671:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
 8672:         # uri is the requested domain in this case.
 8673:         # comparison to 'request.role.domain' shows if the user has selected
 8674:         # a role of dc for the domain in question.
 8675:         return 'F' if ($uri eq $env{'request.role.domain'});
 8676:     }
 8677: 
 8678:     my $thisallowed='';
 8679:     my $statecond=0;
 8680:     my $courseprivid='';
 8681: 
 8682:     my $ownaccess;
 8683:     # Community Coordinator or Assistant Co-author browsing resource space.
 8684:     if (($priv eq 'bro') && ($env{'user.author'})) {
 8685:         if ($uri eq '') {
 8686:             $ownaccess = 1;
 8687:         } else {
 8688:             if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
 8689:                 my $udom = $env{'user.domain'};
 8690:                 my $uname = $env{'user.name'};
 8691:                 if ($uri =~ m{^\Q$udom\E/?$}) {
 8692:                     $ownaccess = 1;
 8693:                 } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
 8694:                     unless ($uri =~ m{\.\./}) {
 8695:                         $ownaccess = 1;
 8696:                     }
 8697:                 } elsif (($udom ne 'public') && ($uname ne 'public')) {
 8698:                     my $now = time;
 8699:                     if ($uri =~ m{^([^/]+)/?$}) {
 8700:                         my $adom = $1;
 8701:                         foreach my $key (keys(%env)) {
 8702:                             if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
 8703:                                 my ($start,$end) = split(/\./,$env{$key});
 8704:                                 if (($now >= $start) && (!$end || $end > $now)) {
 8705:                                     $ownaccess = 1;
 8706:                                     last;
 8707:                                 }
 8708:                             }
 8709:                         }
 8710:                     } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
 8711:                         my $adom = $1;
 8712:                         my $aname = $2;
 8713:                         foreach my $role ('ca','aa') { 
 8714:                             if ($env{"user.role.$role./$adom/$aname"}) {
 8715:                                 my ($start,$end) =
 8716:                                     split(/\./,$env{"user.role.$role./$adom/$aname"});
 8717:                                 if (($now >= $start) && (!$end || $end > $now)) {
 8718:                                     $ownaccess = 1;
 8719:                                     last;
 8720:                                 }
 8721:                             }
 8722:                         }
 8723:                     }
 8724:                 }
 8725:             }
 8726:         }
 8727:     }
 8728: 
 8729: # Course
 8730: 
 8731:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
 8732:         unless (($priv eq 'bro') && (!$ownaccess)) {
 8733:             $thisallowed.=$1;
 8734:         }
 8735:     }
 8736: 
 8737: # Domain
 8738: 
 8739:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
 8740:        =~/\Q$priv\E\&([^\:]*)/) {
 8741:         unless (($priv eq 'bro') && (!$ownaccess)) {
 8742:             $thisallowed.=$1;
 8743:         }
 8744:     }
 8745: 
 8746: # User who is not author or co-author might still be able to edit
 8747: # resource of an author in the domain (e.g., if Domain Coordinator).
 8748:     if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
 8749:         (&allowed('mdc',$env{'request.course.id'}))) {
 8750:         if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
 8751:             $thisallowed.=$1;
 8752:         }
 8753:     }
 8754: 
 8755: # Course: uri itself is a course
 8756:     my $courseuri=$uri;
 8757:     $courseuri=~s/\_(\d)/\/$1/;
 8758:     $courseuri=~s/^([^\/])/\/$1/;
 8759: 
 8760:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
 8761:        =~/\Q$priv\E\&([^\:]*)/) {
 8762:         if ($priv eq 'mip') {
 8763:             my $rem = $1;
 8764:             if (($uri ne '') && ($env{'request.course.id'} eq $uri) &&
 8765:                 ($env{'course.'.$env{'request.course.id'}.'.internal.courseowner'} eq $env{'user.name'}.':'.$env{'user.domain'})) {
 8766:                 my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 8767:                 if ($cdom ne '') {
 8768:                     my %passwdconf = &get_passwdconf($cdom);
 8769:                     if (ref($passwdconf{'crsownerchg'}) eq 'HASH') {
 8770:                         if (ref($passwdconf{'crsownerchg'}{'by'}) eq 'ARRAY') {
 8771:                             if (@{$passwdconf{'crsownerchg'}{'by'}}) {
 8772:                                 my @inststatuses = split(':',$env{'environment.inststatus'});
 8773:                                 unless (@inststatuses) {
 8774:                                     @inststatuses = ('default');
 8775:                                 }
 8776:                                 foreach my $status (@inststatuses) {
 8777:                                     if (grep(/^\Q$status\E$/,@{$passwdconf{'crsownerchg'}{'by'}})) {
 8778:                                         $thisallowed.=$rem;
 8779:                                     }
 8780:                                 }
 8781:                             }
 8782:                         }
 8783:                     }
 8784:                 }
 8785:             }
 8786:         } else {
 8787:             unless (($priv eq 'bro') && (!$ownaccess)) {
 8788:                 $thisallowed.=$1;
 8789:             }
 8790:         }
 8791:     }
 8792: 
 8793: # URI is an uploaded document for this course, default permissions don't matter
 8794: # not allowing 'edit' access (editupload) to uploaded course docs
 8795:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
 8796: 	$thisallowed='';
 8797:         my ($match)=&is_on_map($uri);
 8798:         if ($match) {
 8799:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
 8800:                   =~/\Q$priv\E\&([^\:]*)/) {
 8801:                 my $value = $1;
 8802:                 my $deeplinkblock;
 8803:                 unless ($nodeeplinkcheck) {
 8804:                     $deeplinkblock = &deeplink_check($priv,$symb,$uri);
 8805:                 }
 8806:                 if ($deeplinkblock) {
 8807:                     $thisallowed='D';
 8808:                 } elsif ($noblockcheck) {
 8809:                     $thisallowed.=$value;
 8810:                 } else {
 8811:                     my @blockers = &has_comm_blocking($priv,$symb,$uri,$ignorecache);
 8812:                     if (@blockers > 0) {
 8813:                         $thisallowed = 'B';
 8814:                     } else {
 8815:                         $thisallowed.=$value;
 8816:                     }
 8817:                 }
 8818:             }
 8819:         } else {
 8820:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
 8821:             if ($refuri) {
 8822:                 if ($refuri =~ m|^/adm/|) {
 8823:                     $thisallowed='F';
 8824:                 } else {
 8825:                     $refuri=&declutter($refuri);
 8826:                     my ($match) = &is_on_map($refuri);
 8827:                     if ($match) {
 8828:                         my $deeplinkblock;
 8829:                         unless ($nodeeplinkcheck) {
 8830:                             $deeplinkblock = &deeplink_check($priv,$symb,$refuri);
 8831:                         }
 8832:                         if ($deeplinkblock) {
 8833:                             $thisallowed='D';
 8834:                         } elsif ($noblockcheck) {
 8835:                             $thisallowed='F';
 8836:                         } else {
 8837:                             my @blockers = &has_comm_blocking($priv,'',$refuri,'',1);
 8838:                             if (@blockers > 0) {
 8839:                                 $thisallowed = 'B';
 8840:                             } else {
 8841:                                 $thisallowed='F';
 8842:                             }
 8843:                         }
 8844:                     }
 8845:                 }
 8846:             }
 8847:         }
 8848:     }
 8849: 
 8850:     if ($priv eq 'bre'
 8851: 	&& $thisallowed ne 'F' 
 8852: 	&& $thisallowed ne '2'
 8853: 	&& &is_portfolio_url($uri)) {
 8854: 	$thisallowed = &portfolio_access($uri,$clientip);
 8855:     }
 8856: 
 8857: # Full access at system, domain or course-wide level? Exit.
 8858:     if ($thisallowed=~/F/) {
 8859: 	return 'F';
 8860:     }
 8861: 
 8862: # If this is generating or modifying users, exit with special codes
 8863: 
 8864:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:vca:vaa:'=~/\:\Q$priv\E\:/) {
 8865: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
 8866: 	    my ($audom,$auname)=split('/',$uri);
 8867: # no author name given, so this just checks on the general right to make a co-author in this domain
 8868: 	    unless ($auname) { return $thisallowed; }
 8869: # an author name is given, so we are about to actually make a co-author for a certain account
 8870: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
 8871: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
 8872: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
 8873: 	} elsif (($priv eq 'vca') || ($priv eq 'vaa')) {
 8874:             my ($audom,$auname)=split('/',$uri);
 8875:             unless ($auname) { return $thisallowed; }
 8876:             unless (($env{'request.role'} eq "dc./$audom") ||
 8877:                     ($env{'request.role'} eq "ca./$uri")) {
 8878:                 return '';
 8879:             }
 8880: 	}
 8881: 	return $thisallowed;
 8882:     }
 8883: #
 8884: # Gathered so far: system, domain and course wide privileges
 8885: #
 8886: # Course: See if uri or referer is an individual resource that is part of 
 8887: # the course
 8888: 
 8889:     if ($env{'request.course.id'}) {
 8890: 
 8891:         if ($priv eq 'bre') {
 8892:             if (&is_coursetool_logo($uri)) {
 8893:                 return 'F';
 8894:             }
 8895:         }
 8896: 
 8897: # If this is modifying password (internal auth) domains must match for user and user's role.
 8898: 
 8899:         if ($priv eq 'mip') {
 8900:             if ($env{'user.domain'} eq $env{'request.role.domain'}) {
 8901:                 return $thisallowed;
 8902:             } else {
 8903:                 return '';
 8904:             }
 8905:         }
 8906: 
 8907:        $courseprivid=$env{'request.course.id'};
 8908:        if ($env{'request.course.sec'}) {
 8909:           $courseprivid.='/'.$env{'request.course.sec'};
 8910:        }
 8911:        $courseprivid=~s/\_/\//;
 8912:        my $checkreferer=1;
 8913:        my ($match,$cond)=&is_on_map($uri);
 8914:        if ($match) {
 8915:            $statecond=$cond;
 8916:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 8917:                =~/\Q$priv\E\&([^\:]*)/) {
 8918:                my $value = $1;
 8919:                if ($priv eq 'bre') {
 8920:                    my $deeplinkblock;
 8921:                    unless ($nodeeplinkcheck) {
 8922:                        $deeplinkblock = &deeplink_check($priv,$symb,$uri);
 8923:                    }
 8924:                    if ($deeplinkblock) {
 8925:                        $thisallowed = 'D';
 8926:                    } elsif ($noblockcheck) {
 8927:                        $thisallowed.=$value;
 8928:                    } else {
 8929:                        my @blockers = &has_comm_blocking($priv,$symb,$uri,$ignorecache);
 8930:                        if (@blockers > 0) {
 8931:                            $thisallowed = 'B';
 8932:                        } else {
 8933:                            $thisallowed.=$value;
 8934:                        }
 8935:                    }
 8936:                } else {
 8937:                    $thisallowed.=$value;
 8938:                }
 8939:                $checkreferer=0;
 8940:            }
 8941:        }
 8942: 
 8943:        if ($checkreferer) {
 8944: 	  my $refuri=$env{'httpref.'.$orguri};
 8945:             unless ($refuri) {
 8946:                 foreach my $key (keys(%env)) {
 8947: 		    if ($key=~/^httpref\..*\*/) {
 8948: 			my $pattern=$key;
 8949:                         $pattern=~s/^httpref\.\/res\///;
 8950:                         $pattern=~s/\*/\[\^\/\]\+/g;
 8951:                         $pattern=~s/\//\\\//g;
 8952:                         if ($orguri=~/$pattern/) {
 8953: 			    $refuri=$env{$key};
 8954:                         }
 8955:                     }
 8956:                 }
 8957:             }
 8958: 
 8959:          if ($refuri) { 
 8960: 	  $refuri=&declutter($refuri);
 8961:           my ($match,$cond)=&is_on_map($refuri);
 8962:             if ($match) {
 8963:               my $refstatecond=$cond;
 8964:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 8965:                   =~/\Q$priv\E\&([^\:]*)/) {
 8966:                   my $value = $1;
 8967:                   if ($priv eq 'bre') {
 8968:                       my $deeplinkblock;
 8969:                       unless ($nodeeplinkcheck) {
 8970:                           $deeplinkblock = &deeplink_check($priv,$symb,$refuri);
 8971:                       }
 8972:                       if ($deeplinkblock) {
 8973:                           $thisallowed = 'D';
 8974:                       } elsif ($noblockcheck) {
 8975:                           $thisallowed.=$value;
 8976:                       } else {
 8977:                           my @blockers = &has_comm_blocking($priv,'',$refuri,'',1);
 8978:                           if (@blockers > 0) {
 8979:                               $thisallowed = 'B';
 8980:                           } else {
 8981:                               $thisallowed.=$value;
 8982:                           }
 8983:                       }
 8984:                   } else {
 8985:                       $thisallowed.=$value;
 8986:                   }
 8987:                   $uri=$refuri;
 8988:                   $statecond=$refstatecond;
 8989:               }
 8990:           }
 8991:         }
 8992:        }
 8993:    }
 8994: 
 8995: #
 8996: # Gathered now: all privileges that could apply, and condition number
 8997: # 
 8998: #
 8999: # Full or no access?
 9000: #
 9001: 
 9002:     if ($thisallowed=~/F/) {
 9003: 	return 'F';
 9004:     }
 9005: 
 9006:     unless ($thisallowed) {
 9007:         return '';
 9008:     }
 9009: 
 9010: # Restrictions exist, deal with them
 9011: #
 9012: #   C:according to course preferences
 9013: #   R:according to resource settings
 9014: #   L:unless locked
 9015: #   X:according to user session state
 9016: #
 9017: 
 9018: # Possibly locked functionality, check all courses
 9019: # In roles.tab, L (unless locked) available for bre, pch, plc, pac and sma.
 9020: # Locks might take effect only after 10 minutes cache expiration for other
 9021: # courses, and 2 minutes for current course, in which user has st or ta role
 9022: # which is neither expired nor a future role (unless current course).
 9023: 
 9024:     my ($needlockcheck,$now,$crsonly);
 9025:     if ($thisallowed=~/L/) {
 9026:         $now = time;
 9027:         if ($priv eq 'bre') {
 9028:             if ($uri ne '') {
 9029:                 if ($orguri =~ m{^/+res/}) {
 9030:                     if ($uri =~ m{^lib/templates/}) {
 9031:                         if ($env{'request.course.id'}) {
 9032:                             $crsonly = 1;
 9033:                             $needlockcheck = 1;
 9034:                         }
 9035:                     } else {
 9036:                         $needlockcheck = 1;
 9037:                     }
 9038:                 } elsif ($env{'request.course.id'}) {
 9039:                     my ($crsdom,$crsnum) = split('_',$env{'request.course.id'});
 9040:                     if (($uri =~ m{^(adm|uploaded|public)/$crsdom/$crsnum/}) ||
 9041:                         ($uri =~ m{^adm/$match_domain/$match_username/\d+/(smppg|bulletinboard)$})) {
 9042:                         $crsonly = 1;
 9043:                     }
 9044:                     $needlockcheck = 1;
 9045:                 }
 9046:             }
 9047:         } elsif (($priv eq 'pch') || ($priv eq 'plc') || ($priv eq 'pac') || ($priv eq 'sma')) {
 9048:             $needlockcheck = 1;
 9049:         }
 9050:     }
 9051:     if ($needlockcheck) {
 9052:         foreach my $envkey (keys(%env)) {
 9053:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
 9054:                my $courseid=$2;
 9055:                my $roleid=$1.'.'.$2;
 9056:                $courseid=~s/^\///;
 9057:                unless ($env{'request.role'} eq $roleid) {
 9058:                    my ($start,$end) = split(/\./,$env{$envkey});
 9059:                    next unless (($now >= $start) && (!$end || $end > $now));
 9060:                }
 9061:                my $expiretime=600;
 9062:                if ($env{'request.role'} eq $roleid) {
 9063: 		  $expiretime=120;
 9064:                }
 9065: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
 9066:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
 9067:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
 9068: 		   &coursedescription($courseid,{'freshen_cache' => 1});
 9069:                }
 9070:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
 9071:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
 9072: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
 9073:                        &log($env{'user.domain'},$env{'user.name'},
 9074:                             $env{'user.home'},
 9075:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
 9076:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 9077:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 9078: 		       return '';
 9079:                    }
 9080:                }
 9081:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
 9082:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
 9083: 		   if ($env{$prefix.'priv.'.$priv.'.lock.expire'}>time) {
 9084:                        &log($env{'user.domain'},$env{'user.name'},
 9085:                             $env{'user.home'},
 9086:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
 9087:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 9088:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 9089: 		       return '';
 9090:                    }
 9091:                }
 9092: 	   }
 9093:        }
 9094:     }
 9095: 
 9096: #
 9097: # Rest of the restrictions depend on selected course
 9098: #
 9099: 
 9100:     unless ($env{'request.course.id'}) {
 9101: 	if ($thisallowed eq 'A') {
 9102: 	    return 'A';
 9103:         } elsif ($thisallowed eq 'B') {
 9104:             return 'B';
 9105: 	} else {
 9106: 	    return '1';
 9107: 	}
 9108:     }
 9109: 
 9110: #
 9111: # Now user is definitely in a course
 9112: #
 9113: 
 9114: 
 9115: # Course preferences
 9116: 
 9117:    if ($thisallowed=~/C/) {
 9118:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 9119:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
 9120:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
 9121: 	   =~/\Q$rolecode\E/) {
 9122: 	   if (($priv ne 'pch') && ($priv ne 'plc') && ($priv ne 'pac')) {
 9123: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 9124: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
 9125: 			$env{'request.course.id'});
 9126: 	   }
 9127:            return '';
 9128:        }
 9129: 
 9130:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
 9131: 	   =~/\Q$unamedom\E/) {
 9132: 	   if (($priv ne 'pch') && ($priv ne 'plc') && ($priv ne 'pac')) {
 9133: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
 9134: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
 9135: 			$env{'request.course.id'});
 9136: 	   }
 9137:            return '';
 9138:        }
 9139:    }
 9140: 
 9141: # Resource preferences
 9142: 
 9143:    if ($thisallowed=~/R/) {
 9144:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 9145:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
 9146: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
 9147: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 9148: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
 9149: 	   }
 9150: 	   return '';
 9151:        }
 9152:    }
 9153: 
 9154: # Restricted for deeplinked session?
 9155: 
 9156:     if ($env{'request.deeplink.login'}) {
 9157:         if ($env{'acc.deeplinkout'} && !$nodeeplinkout) {
 9158:             if (!$symb) { $symb=&symbread($uri,1); }
 9159:             if (($symb) && ($env{'acc.deeplinkout'}=~/\&\Q$symb\E\&/)) {
 9160:                 return '';
 9161:             }
 9162:         }
 9163:     }
 9164: 
 9165: # Restricted by state or randomout?
 9166: 
 9167:    if ($thisallowed=~/X/) {
 9168:       if ($env{'acc.randomout'}) {
 9169: 	 if (!$symb) { $symb=&symbread($uri,1); }
 9170:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
 9171:             return ''; 
 9172:          }
 9173:       }
 9174:       if (&condval($statecond)) {
 9175: 	 return '2';
 9176:       } else {
 9177:          return '';
 9178:       }
 9179:    }
 9180: 
 9181:     if ($thisallowed eq 'A') {
 9182: 	return 'A';
 9183:     } elsif ($thisallowed eq 'B') {
 9184:         return 'B';
 9185:     } elsif ($thisallowed eq 'D') {
 9186:         return 'D';
 9187:     }
 9188:    return 'F';
 9189: }
 9190: 
 9191: # ------------------------------------------- Check construction space access
 9192: 
 9193: sub constructaccess {
 9194:     my ($url,$setpriv)=@_;
 9195: 
 9196: # We do not allow editing of previous versions of files
 9197:     if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
 9198: 
 9199: # Get username and domain from URL
 9200:     my ($ownername,$ownerdomain,$ownerhome);
 9201: 
 9202:     ($ownerdomain,$ownername) =
 9203:         ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)(?:/daxepage|/daxeopen)?/priv/($match_domain)/($match_username)(?:/|$)});
 9204: 
 9205: # The URL does not really point to any authorspace, forget it
 9206:     unless (($ownername) && ($ownerdomain)) { return ''; }
 9207: 
 9208: # Now we need to see if the user has access to the authorspace of
 9209: # $ownername at $ownerdomain
 9210: 
 9211:     if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
 9212: # Real author for this?
 9213:        $ownerhome = $env{'user.home'};
 9214:        if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
 9215:           return ($ownername,$ownerdomain,$ownerhome);
 9216:        }
 9217:     } elsif (&is_course($ownerdomain,$ownername)) {
 9218: # Course Authoring Space?
 9219:         if ($env{'request.course.id'}) {
 9220:             if (($ownername eq $env{'course.'.$env{'request.course.id'}.'.num'}) &&
 9221:                 ($ownerdomain eq $env{'course.'.$env{'request.course.id'}.'.domain'})) {
 9222:                 if (&allowed('mdc',$env{'request.course.id'})) {
 9223:                     return if ($env{'course.'.$env{'request.course.id'}.'.internal.crsauthor'} eq '0');
 9224:                     unless ($env{'course.'.$env{'request.course.id'}.'.internal.crsauthor'}) {
 9225:                         my %domdefs = &get_domain_defaults($ownerdomain);
 9226:                         my $type = lc($env{'course.'.$env{'request.course.id'}.'.type'});
 9227:                         unless (($type eq 'community') || ($type eq 'placement')) {
 9228:                             $type = 'unofficial';
 9229:                             if ($env{'course.'.$env{'request.course.id'}.'internal.coursecode'} ne '') {
 9230:                                 $type = 'official';
 9231:                             } elsif ($env{'course.'.$env{'request.course.id'}.'internal.textbook'} ne '') {
 9232:                                 $type = 'textbook';
 9233:                             } else {
 9234:                                 $type = 'unofficial';
 9235:                             }
 9236:                         }
 9237:                         return if ($domdefs{$type.'crsauthor'} eq '0');
 9238:                     }
 9239:                     $ownerhome = $env{'course.'.$env{'request.course.id'}.'.home'};
 9240:                     return ($ownername,$ownerdomain,$ownerhome);
 9241:                 }
 9242:             }
 9243:         }
 9244:         return '';
 9245:     } else {
 9246: # Co-author for this?
 9247:         if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
 9248:             exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
 9249:             $ownerhome = &homeserver($ownername,$ownerdomain);
 9250:             return ($ownername,$ownerdomain,$ownerhome);
 9251:         }
 9252:     }
 9253: 
 9254: # We don't have any access right now. If we are not possibly going to do anything about this,
 9255: # we might as well leave
 9256:    unless ($setpriv) { return ''; }
 9257: 
 9258: # Backdoor access?
 9259:     my $allowed=&allowed('eco',$ownerdomain);
 9260: # Nope
 9261:     unless ($allowed) { return ''; }
 9262: # Looks like we may have access, but could be locked by the owner of the construction space
 9263:     if ($allowed eq 'U') {
 9264:         my %blocked=&get('environment',['domcoord.author'],
 9265:                          $ownerdomain,$ownername);
 9266: # Is blocked by owner
 9267:         if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
 9268:     }
 9269:     if (($allowed eq 'F') || ($allowed eq 'U')) {
 9270: # Grant temporary access
 9271:         my $then=$env{'user.login.time'};
 9272:         my $update=$env{'user.update.time'};
 9273:         if (!$update) { $update = $then; }
 9274:         my $refresh=$env{'user.refresh.time'};
 9275:         if (!$refresh) { $refresh = $update; }
 9276:         my $now = time;
 9277:         &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
 9278:                            $now,'ca','constructaccess');
 9279:         $ownerhome = &homeserver($ownername,$ownerdomain);
 9280:         return($ownername,$ownerdomain,$ownerhome);
 9281:     }
 9282: # No business here
 9283:     return '';
 9284: }
 9285: 
 9286: # ----------------------------------------------------------- Content Blocking
 9287: 
 9288: {
 9289: # Caches for faster Course Contents display where content blocking
 9290: # is in operation (i.e., interval param set) for timed quiz.
 9291: #
 9292: # User for whom data are being temporarily cached.
 9293: my $cacheduser='';
 9294: # Course for which data are being temporarily cached.
 9295: my $cachedcid='';
 9296: # Cached blockers for this user (a hash of blocking items). 
 9297: my %cachedblockers=();
 9298: # When the data were last cached.
 9299: my $cachedlast='';
 9300: 
 9301: sub load_all_blockers {
 9302:     my ($uname,$udom)=@_;
 9303:     if (($uname ne '') && ($udom ne '')) { 
 9304:         if (($cacheduser eq $uname.':'.$udom) &&
 9305:             ($cachedcid eq $env{'request.course.id'}) &&
 9306:             (abs($cachedlast-time)<5)) {
 9307:             return;
 9308:         }
 9309:     }
 9310:     $cachedlast=time;
 9311:     $cacheduser=$uname.':'.$udom;
 9312:     $cachedcid=$env{'request.course.id'};
 9313:     %cachedblockers = &get_commblock_resources();
 9314:     return;
 9315: }
 9316: 
 9317: sub get_comm_blocks {
 9318:     my ($cdom,$cnum) = @_;
 9319:     if ($cdom eq '' || $cnum eq '') {
 9320:         return unless ($env{'request.course.id'});
 9321:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 9322:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 9323:     }
 9324:     my %commblocks;
 9325:     my $hashid=$cdom.'_'.$cnum;
 9326:     my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
 9327:     if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
 9328:         %commblocks = %{$blocksref};
 9329:     } else {
 9330:         %commblocks = &dump('comm_block',$cdom,$cnum);
 9331:         my $cachetime = 600;
 9332:         &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
 9333:     }
 9334:     return %commblocks;
 9335: }
 9336: 
 9337: sub get_commblock_resources {
 9338:     my ($blocks) = @_;
 9339:     my %blockers = ();
 9340:     return %blockers unless ($env{'request.course.id'});
 9341:     my $courseurl = &courseid_to_courseurl($env{'request.course.id'});
 9342:     if ($env{'request.course.sec'}) {
 9343:         $courseurl .= '/'.$env{'request.course.sec'};
 9344:     }
 9345:     return %blockers if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseurl} =~/evb\&([^\:]*)/);
 9346:     my %commblocks;
 9347:     if (ref($blocks) eq 'HASH') {
 9348:         %commblocks = %{$blocks};
 9349:     } else {
 9350:         %commblocks = &get_comm_blocks();
 9351:     }
 9352:     return %blockers unless (keys(%commblocks) > 0); 
 9353:     my $navmap = Apache::lonnavmaps::navmap->new();
 9354:     return %blockers unless (ref($navmap));
 9355:     my $now = time;
 9356:     foreach my $block (keys(%commblocks)) {
 9357:         if ($block =~ /^(\d+)____(\d+)$/) {
 9358:             my ($start,$end) = ($1,$2);
 9359:             if ($start <= $now && $end >= $now) {
 9360:                 if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
 9361:                     if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
 9362:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
 9363:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
 9364:                                 $blockers{$block}{maps} = $commblocks{$block}{'blocks'}{'docs'}{'maps'}; 
 9365:                             }
 9366:                         }
 9367:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
 9368:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
 9369:                                 $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
 9370:                             }
 9371:                         }
 9372:                     }
 9373:                 }
 9374:             }
 9375:         } elsif ($block =~ /^firstaccess____(.+)$/) {
 9376:             my $item = $1;
 9377:             if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
 9378:                 if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
 9379:                     my (@interval,$mapname);
 9380:                     my $type = 'map';
 9381:                     if ($item eq 'course') {
 9382:                         $type = 'course';
 9383:                         @interval=&EXT("resource.0.interval");
 9384:                     } else {
 9385:                         if ($item =~ /___\d+___/) {
 9386:                             $type = 'resource';
 9387:                             @interval=&EXT("resource.0.interval",$item);
 9388:                         } else {
 9389:                             $mapname = &deversion($item);
 9390:                             if (ref($navmap)) {
 9391:                                 my $timelimit = $navmap->get_mapparam(undef,$mapname,'0.interval');
 9392:                                 @interval = ($timelimit,'map');
 9393:                             }
 9394:                         }
 9395:                     }
 9396:                     if ($interval[0] =~ /^(\d+)/) {
 9397:                         my $timelimit = $1; 
 9398:                         my $first_access;
 9399:                         if ($type eq 'resource') {
 9400:                             $first_access=&get_first_access($interval[1],$item);
 9401:                         } elsif ($type eq 'map') {
 9402:                             $first_access=&get_first_access($interval[1],undef,$item);
 9403:                         } else {
 9404:                             $first_access=&get_first_access($interval[1]);
 9405:                         }
 9406:                         if ($first_access) {
 9407:                             my $timesup = $first_access+$timelimit;
 9408:                             if ($timesup > $now) {
 9409:                                 my $activeblock;
 9410:                                 if ($type eq 'resource') {
 9411:                                     if (ref($navmap)) {
 9412:                                         my $res = $navmap->getBySymb($item);
 9413:                                         if ($res->answerable()) {
 9414:                                             $activeblock = 1;
 9415:                                         }
 9416:                                     }
 9417:                                 } elsif ($type eq 'map') {
 9418:                                     my $mapsymb = &symbread($mapname,1);
 9419:                                     if (($mapsymb) && (ref($navmap))) {
 9420:                                         my $mapres = $navmap->getBySymb($mapsymb);
 9421:                                         if (ref($mapres)) {
 9422:                                             my $first = $mapres->map_start();
 9423:                                             my $finish = $mapres->map_finish();
 9424:                                             my $it = $navmap->getIterator($first,$finish,undef,0,0);
 9425:                                             if (ref($it)) {
 9426:                                                 my $res;
 9427:                                                 while ($res = $it->next(undef,1)) {
 9428:                                                     next unless (ref($res));
 9429:                                                     my $symb = $res->symb();
 9430:                                                     next if (($symb eq $mapsymb) || ($symb eq ''));
 9431:                                                     @interval=&EXT("resource.0.interval",$symb);
 9432:                                                     if ($interval[1] eq 'map') {
 9433:                                                         if ($res->answerable()) {
 9434:                                                             $activeblock = 1;
 9435:                                                             last;
 9436:                                                         }
 9437:                                                     }
 9438:                                                 }
 9439:                                             }
 9440:                                         }
 9441:                                     }
 9442:                                 }
 9443:                                 if ($activeblock) {
 9444:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
 9445:                                          if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
 9446:                                              $blockers{$block}{'maps'} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
 9447:                                          }
 9448:                                     }
 9449:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
 9450:                                         if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
 9451:                                             $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
 9452:                                         }
 9453:                                     }
 9454:                                 }
 9455:                             }
 9456:                         }
 9457:                     }
 9458:                 }
 9459:             }
 9460:         }
 9461:     }
 9462:     return %blockers;
 9463: }
 9464: 
 9465: sub has_comm_blocking {
 9466:     my ($priv,$symb,$uri,$ignoresymbdb,$noenccheck,$blocked,$blocks) = @_;
 9467:     my @blockers;
 9468:     return unless ($env{'request.course.id'});
 9469:     return unless ($priv eq 'bre');
 9470:     return if ($env{'request.state'} eq 'construct');
 9471:     my $courseurl = &courseid_to_courseurl($env{'request.course.id'});
 9472:     if ($env{'request.course.sec'}) {
 9473:         $courseurl .= '/'.$env{'request.course.sec'};
 9474:     }
 9475:     return if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseurl} =~/evb\&([^\:]*)/);
 9476:     my %blockinfo;
 9477:     if (ref($blocks) eq 'HASH') {
 9478:         %blockinfo = &get_commblock_resources($blocks);
 9479:     } else {
 9480:         &load_all_blockers($env{'user.name'},$env{'user.domain'});
 9481:         %blockinfo = %cachedblockers;
 9482:     }
 9483:     return unless (keys(%blockinfo) > 0);
 9484:     my (%possibles,@symbs);
 9485:     if (!$symb) {
 9486:         $symb = &symbread($uri,1,1,1,\%possibles,$ignoresymbdb,$noenccheck);
 9487:     }
 9488:     if ($symb) {
 9489:         @symbs = ($symb);
 9490:     } elsif (keys(%possibles)) { 
 9491:         @symbs = keys(%possibles);
 9492:     }
 9493:     my $noblock;
 9494:     foreach my $symb (@symbs) {
 9495:         last if ($noblock);
 9496:         my ($map,$resid,$resurl)=&decode_symb($symb);
 9497:         foreach my $block (keys(%blockinfo)) {
 9498:             if ($block =~ /^firstaccess____(.+)$/) {
 9499:                 my $item = $1;
 9500:                 unless ($blocked) {
 9501:                     if (($item eq $map) || ($item eq $symb)) {
 9502:                         $noblock = 1;
 9503:                         last;
 9504:                     }
 9505:                 }
 9506:             }
 9507:             if (ref($blockinfo{$block}) eq 'HASH') {
 9508:                 if (ref($blockinfo{$block}{'resources'}) eq 'HASH') {
 9509:                     if ($blockinfo{$block}{'resources'}{$symb}) {
 9510:                         unless (grep(/^\Q$block\E$/,@blockers)) {
 9511:                             push(@blockers,$block);
 9512:                         }
 9513:                     }
 9514:                 }
 9515:                 if (ref($blockinfo{$block}{'maps'}) eq 'HASH') {
 9516:                     if ($blockinfo{$block}{'maps'}{$map}) {
 9517:                         unless (grep(/^\Q$block\E$/,@blockers)) {
 9518:                             push(@blockers,$block);
 9519:                         }
 9520:                     }
 9521:                 }
 9522:             }
 9523:         }
 9524:     }
 9525:     unless ($noblock) { 
 9526:         return @blockers;
 9527:     }
 9528:     return;
 9529: }
 9530: }
 9531: 
 9532: sub deeplink_check {
 9533:     my ($priv,$symb,$uri) = @_;
 9534:     return unless ($env{'request.course.id'});
 9535:     return unless ($priv eq 'bre');
 9536:     return if ($env{'request.state'} eq 'construct');
 9537:     return if ($env{'request.role.adv'});
 9538:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 9539:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 9540:     my (%possibles,@symbs);
 9541:     if (!$symb) {
 9542:         $symb = &symbread($uri,1,1,1,\%possibles);
 9543:     }
 9544:     if ($symb) {
 9545:         @symbs = ($symb);
 9546:     } elsif (keys(%possibles)) {
 9547:         @symbs = keys(%possibles);
 9548:     }
 9549: 
 9550:     my ($deeplink_symb,$allow);
 9551:     if ($env{'request.deeplink.login'}) {
 9552:         $deeplink_symb = &Apache::loncommon::deeplink_login_symb($cnum,$cdom);
 9553:     }
 9554:     foreach my $symb (@symbs) {
 9555:         last if ($allow);
 9556:         my $deeplink = &EXT("resource.0.deeplink",$symb);
 9557:         if ($deeplink eq '') {
 9558:             $allow = 1;
 9559:         } else {
 9560:             my ($state,$others,$listed,$scope,$protect) = split(/,/,$deeplink);
 9561:             if ($state ne 'only') {
 9562:                 $allow = 1;
 9563:             } else {
 9564:                 my $check_deeplink_entry;
 9565:                 if ($protect ne 'none') {
 9566:                     my ($acctype,$item) = split(/:/,$protect);
 9567:                     if (($acctype eq 'ltic') && ($env{'user.linkprotector'})) {
 9568:                         if (grep(/^\Q$item\Ec$/,split(/,/,$env{'user.linkprotector'}))) {
 9569:                             $check_deeplink_entry = 1
 9570:                         }
 9571:                     } elsif (($acctype eq 'ltid') && ($env{'user.linkprotector'})) {
 9572:                         if (grep(/^\Q$item\Ed$/,split(/,/,$env{'user.linkprotector'}))) {
 9573:                             $check_deeplink_entry = 1;
 9574:                         }
 9575:                     } elsif (($acctype eq 'key') && ($env{'user.deeplinkkey'})) {
 9576:                         if (grep(/^\Q$item\E$/,split(/,/,$env{'user.deeplinkkey'}))) {
 9577:                             $check_deeplink_entry = 1;
 9578:                         }
 9579:                     }
 9580:                 }
 9581:                 if (($protect eq 'none') || ($check_deeplink_entry)) {
 9582:                     if ($scope eq 'res') {
 9583:                         if ($symb eq $deeplink_symb) {
 9584:                             $allow = 1;
 9585:                         }
 9586:                     } elsif (($scope eq 'map') || ($scope eq 'rec')) {
 9587:                         my ($map_from_symb,$map_from_login);
 9588:                         $map_from_symb = &deversion((&decode_symb($symb))[0]);
 9589:                         if ($deeplink_symb =~ /\.(page|sequence)$/) {
 9590:                             $map_from_login = &deversion((&decode_symb($deeplink_symb))[2]);
 9591:                         } else {
 9592:                             $map_from_login = &deversion((&decode_symb($deeplink_symb))[0]);
 9593:                         }
 9594:                         if (($map_from_symb) && ($map_from_login)) {
 9595:                             if ($map_from_symb eq $map_from_login) {
 9596:                                 $allow = 1;
 9597:                             } elsif ($scope eq 'rec') {
 9598:                                 my @recurseup = &get_map_hierarchy($map_from_symb,$env{'request.course.id'});
 9599:                                 if (grep(/^\Q$map_from_login\E$/,@recurseup)) {
 9600:                                     $allow = 1;
 9601:                                 }
 9602:                             }
 9603:                         }
 9604:                     }
 9605:                 }
 9606:             }
 9607:         }
 9608:     }
 9609:     return if ($allow);
 9610:     return 1;
 9611: }
 9612: 
 9613: # -------------------------------- Deversion and split uri into path an filename   
 9614: 
 9615: #
 9616: #   Removes the version from a URI and
 9617: #   splits it in to its filename and path to the filename.
 9618: #   Seems like File::Basename could have done this more clearly.
 9619: #   Parameters:
 9620: #      $uri   - input URI
 9621: #   Returns:
 9622: #     Two element list consisting of 
 9623: #     $pathname  - the URI up to and excluding the trailing /
 9624: #     $filename  - The part of the URI following the last /
 9625: #  NOTE:
 9626: #    Another realization of this is simply:
 9627: #    use File::Basename;
 9628: #    ...
 9629: #    $uri = shift;
 9630: #    $filename = basename($uri);
 9631: #    $path     = dirname($uri);
 9632: #    return ($filename, $path);
 9633: #
 9634: #     The implementation below is probably faster however.
 9635: #
 9636: sub split_uri_for_cond {
 9637:     my $uri=&deversion(&declutter(shift));
 9638:     my @uriparts=split(/\//,$uri);
 9639:     my $filename=pop(@uriparts);
 9640:     my $pathname=join('/',@uriparts);
 9641:     return ($pathname,$filename);
 9642: }
 9643: # --------------------------------------------------- Is a resource on the map?
 9644: 
 9645: sub is_on_map {
 9646:     my ($pathname,$filename) = &split_uri_for_cond(shift);
 9647:     #Trying to find the conditional for the file
 9648:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
 9649: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
 9650:     if ($match) {
 9651: 	return (1,$1);
 9652:     } else {
 9653: 	return (0,0);
 9654:     }
 9655: }
 9656: 
 9657: # --------------------------------------------------------- Get symb from alias
 9658: 
 9659: sub get_symb_from_alias {
 9660:     my $symb=shift;
 9661:     my ($map,$resid,$url)=&decode_symb($symb);
 9662: # Already is a symb
 9663:     if ($url) { return $symb; }
 9664: # Must be an alias
 9665:     my $aliassymb='';
 9666:     my %bighash;
 9667:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 9668:                             &GDBM_READER(),0640)) {
 9669:         my $rid=$bighash{'mapalias_'.$symb};
 9670: 	if ($rid) {
 9671: 	    my ($mapid,$resid)=split(/\./,$rid);
 9672: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
 9673: 				    $resid,$bighash{'src_'.$rid});
 9674: 	}
 9675:         untie %bighash;
 9676:     }
 9677:     return $aliassymb;
 9678: }
 9679: 
 9680: # ----------------------------------------------------------------- Define Role
 9681: 
 9682: sub definerole {
 9683:   if (allowed('mcr','/')) {
 9684:     my ($rolename,$sysrole,$domrole,$courole,$uname,$udom)=@_;
 9685:     foreach my $role (split(':',$sysrole)) {
 9686: 	my ($crole,$cqual)=split(/\&/,$role);
 9687:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
 9688:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
 9689: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 9690:                return "refused:s:$crole&$cqual"; 
 9691:             }
 9692:         }
 9693:     }
 9694:     foreach my $role (split(':',$domrole)) {
 9695: 	my ($crole,$cqual)=split(/\&/,$role);
 9696:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
 9697:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
 9698: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
 9699:                return "refused:d:$crole&$cqual"; 
 9700:             }
 9701:         }
 9702:     }
 9703:     foreach my $role (split(':',$courole)) {
 9704: 	my ($crole,$cqual)=split(/\&/,$role);
 9705:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
 9706:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
 9707: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 9708:                return "refused:c:$crole&$cqual"; 
 9709:             }
 9710:         }
 9711:     }
 9712:     my $uhome;
 9713:     if (($uname ne '') && ($udom ne '')) {
 9714:         $uhome = &homeserver($uname,$udom);
 9715:         return $uhome if ($uhome eq 'no_host');
 9716:     } else {
 9717:         $uname = $env{'user.name'};
 9718:         $udom = $env{'user.domain'};
 9719:         $uhome = $env{'user.home'};
 9720:     }
 9721:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
 9722:                 "$udom:$uname:rolesdef_$rolename=".
 9723:                 escape($sysrole.'_'.$domrole.'_'.$courole);
 9724:     return reply($command,$uhome);
 9725:   } else {
 9726:     return 'refused';
 9727:   }
 9728: }
 9729: 
 9730: # ---------------- Make a metadata query against the network of library servers
 9731: 
 9732: sub metadata_query {
 9733:     my ($query,$custom,$customshow,$server_array,$domains_hash)=@_;
 9734:     my %rhash;
 9735:     my %libserv = &all_library();
 9736:     my @server_list = (defined($server_array) ? @$server_array
 9737:                                               : keys(%libserv) );
 9738:     for my $server (@server_list) {
 9739:         my $domains = ''; 
 9740:         if (ref($domains_hash) eq 'HASH') {
 9741:             $domains = $domains_hash->{$server}; 
 9742:         }
 9743: 	unless ($custom or $customshow) {
 9744: 	    my $reply=&reply("querysend:".&escape($query).':::'.&escape($domains),$server);
 9745: 	    $rhash{$server}=$reply;
 9746: 	}
 9747: 	else {
 9748: 	    my $reply=&reply("querysend:".&escape($query).':'.
 9749: 			     &escape($custom).':'.&escape($customshow).':'.&escape($domains),
 9750: 			     $server);
 9751: 	    $rhash{$server}=$reply;
 9752: 	}
 9753:     }
 9754:     return \%rhash;
 9755: }
 9756: 
 9757: # ----------------------------------------- Send log queries and wait for reply
 9758: 
 9759: sub log_query {
 9760:     my ($uname,$udom,$query,%filters)=@_;
 9761:     my $uhome=&homeserver($uname,$udom);
 9762:     if ($uhome eq 'no_host') { return 'error: no_host'; }
 9763:     my $uhost=&hostname($uhome);
 9764:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
 9765:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
 9766:                        $uhome);
 9767:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
 9768:     return get_query_reply($queryid);
 9769: }
 9770: 
 9771: # -------------------------- Update MySQL table for portfolio file
 9772: 
 9773: sub update_portfolio_table {
 9774:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
 9775:     if ($group ne '') {
 9776:         $file_name =~s /^\Q$group\E//;
 9777:     }
 9778:     my $homeserver = &homeserver($uname,$udom);
 9779:     my $queryid=
 9780:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
 9781:                ':'.&escape($file_name).':'.$action,$homeserver);
 9782:     my $reply = &get_query_reply($queryid);
 9783:     return $reply;
 9784: }
 9785: 
 9786: # -------------------------- Update MySQL allusers table
 9787: 
 9788: sub update_allusers_table {
 9789:     my ($uname,$udom,$names) = @_;
 9790:     my $homeserver = &homeserver($uname,$udom);
 9791:     my $queryid=
 9792:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
 9793:                'lastname='.&escape($names->{'lastname'}).'%%'.
 9794:                'firstname='.&escape($names->{'firstname'}).'%%'.
 9795:                'middlename='.&escape($names->{'middlename'}).'%%'.
 9796:                'generation='.&escape($names->{'generation'}).'%%'.
 9797:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
 9798:                'id='.&escape($names->{'id'}),$homeserver);
 9799:     return;
 9800: }
 9801: 
 9802: # ------- Request retrieval of institutional classlists for course(s)
 9803: 
 9804: sub fetch_enrollment_query {
 9805:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
 9806:     my ($homeserver,$sleep,$loopmax);
 9807:     my $maxtries = 1;
 9808:     if ($context eq 'automated') {
 9809:         $homeserver = $perlvar{'lonHostID'};
 9810:         $sleep = 2;
 9811:         $loopmax = 100;
 9812:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
 9813:     } else {
 9814:         $homeserver = &homeserver($cnum,$dom);
 9815:     }
 9816:     my $host=&hostname($homeserver);
 9817:     my $cmd = '';
 9818:     foreach my $affiliate (keys(%{$affiliatesref})) {
 9819:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
 9820:     }
 9821:     $cmd =~ s/%%$//;
 9822:     $cmd = &escape($cmd);
 9823:     my $query = 'fetchenrollment';
 9824:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
 9825:     unless ($queryid=~/^\Q$host\E\_/) { 
 9826:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
 9827:         return 'error: '.$queryid;
 9828:     }
 9829:     my $reply = &get_query_reply($queryid,$sleep,$loopmax);
 9830:     my $tries = 1;
 9831:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 9832:         $reply = &get_query_reply($queryid,$sleep,$loopmax);
 9833:         $tries ++;
 9834:     }
 9835:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 9836:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 9837:     } else {
 9838:         my @responses = split(/:/,$reply);
 9839:         if (grep { $_ eq $homeserver } &current_machine_ids()) {
 9840:             foreach my $line (@responses) {
 9841:                 my ($key,$value) = split(/=/,$line,2);
 9842:                 $$replyref{$key} = $value;
 9843:             }
 9844:         } else {
 9845:             my $pathname = LONCAPA::tempdir();
 9846:             foreach my $line (@responses) {
 9847:                 my ($key,$value) = split(/=/,$line);
 9848:                 $$replyref{$key} = $value;
 9849:                 if ($value > 0) {
 9850:                     foreach my $item (@{$$affiliatesref{$key}}) {
 9851:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
 9852:                         my $destname = $pathname.'/'.$filename;
 9853:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
 9854:                         if ($xml_classlist =~ /^error/) {
 9855:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
 9856:                         } else {
 9857:                             if ( open(FILE,">",$destname) ) {
 9858:                                 print FILE &unescape($xml_classlist);
 9859:                                 close(FILE);
 9860:                             } else {
 9861:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
 9862:                             }
 9863:                         }
 9864:                     }
 9865:                 }
 9866:             }
 9867:         }
 9868:         return 'ok';
 9869:     }
 9870:     return 'error';
 9871: }
 9872: 
 9873: sub get_query_reply {
 9874:     my ($queryid,$sleep,$loopmax) = @_;
 9875:     if (($sleep eq '') || ($sleep !~ /^\d+\.?\d*$/)) {
 9876:         $sleep = 0.2;
 9877:     }
 9878:     if (($loopmax eq '') || ($loopmax =~ /\D/)) {
 9879:         $loopmax = 100;
 9880:     }
 9881:     my $replyfile=LONCAPA::tempdir().$queryid;
 9882:     my $reply='';
 9883:     for (1..$loopmax) {
 9884: 	sleep($sleep);
 9885:         if (-e $replyfile.'.end') {
 9886: 	    if (open(my $fh,"<",$replyfile)) {
 9887: 		$reply = join('',<$fh>);
 9888: 		close($fh);
 9889: 	   } else { return 'error: reply_file_error'; }
 9890:            return &unescape($reply);
 9891: 	}
 9892:     }
 9893:     return 'timeout:'.$queryid;
 9894: }
 9895: 
 9896: sub courselog_query {
 9897: #
 9898: # possible filters:
 9899: # url: url or symb
 9900: # username
 9901: # domain
 9902: # action: view, submit, grade
 9903: # start: timestamp
 9904: # end: timestamp
 9905: #
 9906:     my (%filters)=@_;
 9907:     unless ($env{'request.course.id'}) { return 'no_course'; }
 9908:     if ($filters{'url'}) {
 9909: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
 9910:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
 9911:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
 9912:     }
 9913:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 9914:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 9915:     return &log_query($cname,$cdom,'courselog',%filters);
 9916: }
 9917: 
 9918: sub userlog_query {
 9919: #
 9920: # possible filters:
 9921: # action: log check role
 9922: # start: timestamp
 9923: # end: timestamp
 9924: #
 9925:     my ($uname,$udom,%filters)=@_;
 9926:     return &log_query($uname,$udom,'userlog',%filters);
 9927: }
 9928: 
 9929: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
 9930: 
 9931: sub auto_run {
 9932:     my ($cnum,$cdom) = @_;
 9933:     my $response = 0;
 9934:     my $settings;
 9935:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
 9936:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
 9937:         $settings = $domconfig{'autoenroll'};
 9938:         if ($settings->{'run'} eq '1') {
 9939:             $response = 1;
 9940:         }
 9941:     } else {
 9942:         my $homeserver;
 9943:         if (&is_course($cdom,$cnum)) {
 9944:             $homeserver = &homeserver($cnum,$cdom);
 9945:         } else {
 9946:             $homeserver = &domain($cdom,'primary');
 9947:         }
 9948:         if ($homeserver ne 'no_host') {
 9949:             $response = &reply('autorun:'.$cdom,$homeserver);
 9950:         }
 9951:     }
 9952:     return $response;
 9953: }
 9954: 
 9955: sub auto_get_sections {
 9956:     my ($cnum,$cdom,$inst_coursecode) = @_;
 9957:     my $homeserver;
 9958:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) { 
 9959:         $homeserver = &homeserver($cnum,$cdom);
 9960:     }
 9961:     if (!defined($homeserver)) { 
 9962:         if ($cdom =~ /^$match_domain$/) {
 9963:             $homeserver = &domain($cdom,'primary');
 9964:         }
 9965:     }
 9966:     my @secs;
 9967:     if (defined($homeserver)) {
 9968:         my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
 9969:         unless ($response eq 'refused') {
 9970:             @secs = split(/:/,$response);
 9971:         }
 9972:     }
 9973:     return @secs;
 9974: }
 9975: 
 9976: sub auto_new_course {
 9977:     my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
 9978:     my $homeserver = &homeserver($cnum,$cdom);
 9979:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
 9980:     return $response;
 9981: }
 9982: 
 9983: sub auto_validate_courseID {
 9984:     my ($cnum,$cdom,$inst_course_id) = @_;
 9985:     my $homeserver = &homeserver($cnum,$cdom);
 9986:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
 9987:     return $response;
 9988: }
 9989: 
 9990: sub auto_validate_instcode {
 9991:     my ($cnum,$cdom,$instcode,$owner) = @_;
 9992:     my ($homeserver,$response);
 9993:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
 9994:         $homeserver = &homeserver($cnum,$cdom);
 9995:     }
 9996:     if (!defined($homeserver)) {
 9997:         if ($cdom =~ /^$match_domain$/) {
 9998:             $homeserver = &domain($cdom,'primary');
 9999:         }
10000:     }
10001:     $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
10002:                         &escape($instcode).':'.&escape($owner),$homeserver));
10003:     my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
10004:     return ($outcome,$description,$defaultcredits);
10005: }
10006: 
10007: sub auto_validate_inst_crosslist {
10008:     my ($cnum,$cdom,$instcode,$inst_xlist,$coowner) = @_;
10009:     my ($homeserver,$response);
10010:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
10011:         $homeserver = &homeserver($cnum,$cdom);
10012:     }
10013:     if (!defined($homeserver)) {
10014:         if ($cdom =~ /^$match_domain$/) {
10015:             $homeserver = &domain($cdom,'primary');
10016:         }
10017:     }
10018:     unless (($homeserver eq '') || ($homeserver eq 'no_host')) {
10019:         $response=&reply('autovalidateinstcrosslist:'.$cdom.':'.
10020:                          &escape($instcode).':'.&escape($inst_xlist).':'.
10021:                          &escape($coowner),$homeserver);
10022:     }
10023:     return $response;
10024: }
10025: 
10026: sub auto_create_password {
10027:     my ($cnum,$cdom,$authparam,$udom) = @_;
10028:     my ($homeserver,$response);
10029:     my $create_passwd = 0;
10030:     my $authchk = '';
10031:     if ($udom =~ /^$match_domain$/) {
10032:         $homeserver = &domain($udom,'primary');
10033:     }
10034:     if ($homeserver eq '') {
10035:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
10036:             $homeserver = &homeserver($cnum,$cdom);
10037:         }
10038:     }
10039:     if ($homeserver eq '') {
10040:         $authchk = 'nodomain';
10041:     } else {
10042:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
10043:         if ($response eq 'refused') {
10044:             $authchk = 'refused';
10045:         } else {
10046:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
10047:         }
10048:     }
10049:     return ($authparam,$create_passwd,$authchk);
10050: }
10051: 
10052: sub auto_photo_permission {
10053:     my ($cnum,$cdom,$students) = @_;
10054:     my $homeserver = &homeserver($cnum,$cdom);
10055:     my ($outcome,$perm_reqd,$conditions) = 
10056: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
10057:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
10058: 	return (undef,undef);
10059:     }
10060:     return ($outcome,$perm_reqd,$conditions);
10061: }
10062: 
10063: sub auto_checkphotos {
10064:     my ($uname,$udom,$pid) = @_;
10065:     my $homeserver = &homeserver($uname,$udom);
10066:     my ($result,$resulttype);
10067:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
10068: 				   &escape($uname).':'.&escape($pid),
10069: 				   $homeserver));
10070:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
10071: 	return (undef,undef);
10072:     }
10073:     if ($outcome) {
10074:         ($result,$resulttype) = split(/:/,$outcome);
10075:     } 
10076:     return ($result,$resulttype);
10077: }
10078: 
10079: sub auto_photochoice {
10080:     my ($cnum,$cdom) = @_;
10081:     my $homeserver = &homeserver($cnum,$cdom);
10082:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
10083: 						       &escape($cdom),
10084: 						       $homeserver)));
10085:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
10086: 	return (undef,undef);
10087:     }
10088:     return ($update,$comment);
10089: }
10090: 
10091: sub auto_photoupdate {
10092:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
10093:     my $homeserver = &homeserver($cnum,$dom);
10094:     my $host=&hostname($homeserver);
10095:     my $cmd = '';
10096:     my $maxtries = 1;
10097:     foreach my $affiliate (keys(%{$affiliatesref})) {
10098:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
10099:     }
10100:     $cmd =~ s/%%$//;
10101:     $cmd = &escape($cmd);
10102:     my $query = 'institutionalphotos';
10103:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
10104:     unless ($queryid=~/^\Q$host\E\_/) {
10105:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
10106:         return 'error: '.$queryid;
10107:     }
10108:     my $reply = &get_query_reply($queryid);
10109:     my $tries = 1;
10110:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
10111:         $reply = &get_query_reply($queryid);
10112:         $tries ++;
10113:     }
10114:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
10115:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
10116:     } else {
10117:         my @responses = split(/:/,$reply);
10118:         my $outcome = shift(@responses); 
10119:         foreach my $item (@responses) {
10120:             my ($key,$value) = split(/=/,$item);
10121:             $$photo{$key} = $value;
10122:         }
10123:         return $outcome;
10124:     }
10125:     return 'error';
10126: }
10127: 
10128: sub auto_instcode_format {
10129:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
10130: 	$cat_order) = @_;
10131:     my $courses = '';
10132:     my @homeservers;
10133:     if ($caller eq 'global') {
10134: 	my %servers = &get_servers($codedom,'library');
10135: 	foreach my $tryserver (keys(%servers)) {
10136: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
10137: 		push(@homeservers,$tryserver);
10138: 	    }
10139:         }
10140:     } elsif ($caller eq 'requests') {
10141:         if ($codedom =~ /^$match_domain$/) {
10142:             my $chome = &domain($codedom,'primary');
10143:             unless ($chome eq 'no_host') {
10144:                 push(@homeservers,$chome);
10145:             }
10146:         }
10147:     } else {
10148:         push(@homeservers,&homeserver($caller,$codedom));
10149:     }
10150:     foreach my $code (keys(%{$instcodes})) {
10151:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
10152:     }
10153:     chop($courses);
10154:     my $ok_response = 0;
10155:     my $response;
10156:     while (@homeservers > 0 && $ok_response == 0) {
10157:         my $server = shift(@homeservers); 
10158:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
10159:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
10160:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
10161: 		split(/:/,$response);
10162:             %{$codes} = (%{$codes},&str2hash($codes_str));
10163:             push(@{$codetitles},&str2array($codetitles_str));
10164:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
10165:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
10166:             $ok_response = 1;
10167:         }
10168:     }
10169:     if ($ok_response) {
10170:         return 'ok';
10171:     } else {
10172:         return $response;
10173:     }
10174: }
10175: 
10176: sub auto_instcode_defaults {
10177:     my ($domain,$returnhash,$code_order) = @_;
10178:     my @homeservers;
10179: 
10180:     my %servers = &get_servers($domain,'library');
10181:     foreach my $tryserver (keys(%servers)) {
10182: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
10183: 	    push(@homeservers,$tryserver);
10184: 	}
10185:     }
10186: 
10187:     my $response;
10188:     foreach my $server (@homeservers) {
10189:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
10190:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
10191: 	
10192: 	foreach my $pair (split(/\&/,$response)) {
10193: 	    my ($name,$value)=split(/\=/,$pair);
10194: 	    if ($name eq 'code_order') {
10195: 		@{$code_order} = split(/\&/,&unescape($value));
10196: 	    } else {
10197: 		$returnhash->{&unescape($name)}=&unescape($value);
10198: 	    }
10199: 	}
10200: 	return 'ok';
10201:     }
10202: 
10203:     return $response;
10204: }
10205: 
10206: sub auto_possible_instcodes {
10207:     my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
10208:     unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') && 
10209:             (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
10210:         return;
10211:     }
10212:     my (@homeservers,$uhome);
10213:     if (defined(&domain($domain,'primary'))) {
10214:         $uhome=&domain($domain,'primary');
10215:         push(@homeservers,&domain($domain,'primary'));
10216:     } else {
10217:         my %servers = &get_servers($domain,'library');
10218:         foreach my $tryserver (keys(%servers)) {
10219:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
10220:                 push(@homeservers,$tryserver);
10221:             }
10222:         }
10223:     }
10224:     my $response;
10225:     foreach my $server (@homeservers) {
10226:         $response=&reply('autopossibleinstcodes:'.$domain,$server);
10227:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
10228:         my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) = 
10229:             split(':',$response);
10230:         @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
10231:         @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
10232:         foreach my $item (split('&',$cat_title)) {   
10233:             my ($name,$value)=split('=',$item);
10234:             $cat_titles->{&unescape($name)}=&thaw_unescape($value);
10235:         }
10236:         foreach my $item (split('&',$cat_order)) {
10237:             my ($name,$value)=split('=',$item);
10238:             $cat_orders->{&unescape($name)}=&thaw_unescape($value);
10239:         }
10240:         return 'ok';
10241:     }
10242:     return $response;
10243: }
10244: 
10245: sub auto_courserequest_checks {
10246:     my ($dom) = @_;
10247:     my ($homeserver,%validations);
10248:     if ($dom =~ /^$match_domain$/) {
10249:         $homeserver = &domain($dom,'primary');
10250:     }
10251:     unless ($homeserver eq 'no_host') {
10252:         my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
10253:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
10254:             my @items = split(/&/,$response);
10255:             foreach my $item (@items) {
10256:                 my ($key,$value) = split('=',$item);
10257:                 $validations{&unescape($key)} = &thaw_unescape($value);
10258:             }
10259:         }
10260:     }
10261:     return %validations; 
10262: }
10263: 
10264: sub auto_courserequest_validation {
10265:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist,$custominfo) = @_;
10266:     my ($homeserver,$response);
10267:     if ($dom =~ /^$match_domain$/) {
10268:         $homeserver = &domain($dom,'primary');
10269:     }
10270:     unless ($homeserver eq 'no_host') {
10271:         my $customdata;
10272:         if (ref($custominfo) eq 'HASH') {
10273:             $customdata = &freeze_escape($custominfo);
10274:         }
10275:         $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
10276:                                     ':'.&escape($crstype).':'.&escape($inststatuslist).
10277:                                     ':'.&escape($instcode).':'.&escape($instseclist).':'.
10278:                                     $customdata,$homeserver));
10279:     }
10280:     return $response;
10281: }
10282: 
10283: sub auto_validate_class_sec {
10284:     my ($cdom,$cnum,$owners,$inst_class) = @_;
10285:     my $homeserver = &homeserver($cnum,$cdom);
10286:     my $ownerlist;
10287:     if (ref($owners) eq 'ARRAY') {
10288:         $ownerlist = join(',',@{$owners});
10289:     } else {
10290:         $ownerlist = $owners;
10291:     }
10292:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
10293:                         &escape($ownerlist).':'.$cdom,$homeserver);
10294:     return $response;
10295: }
10296: 
10297: sub auto_instsec_reformat {
10298:     my ($cdom,$action,$instsecref) = @_;
10299:     return unless(($action eq 'clutter') || ($action eq 'declutter'));
10300:     my @homeservers;
10301:     if (defined(&domain($cdom,'primary'))) {
10302:         push(@homeservers,&domain($cdom,'primary'));
10303:     } else {
10304:         my %servers = &get_servers($cdom,'library');
10305:         foreach my $tryserver (keys(%servers)) {
10306:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
10307:                 push(@homeservers,$tryserver);
10308:             }
10309:         }
10310:     }
10311:     my $response;
10312:     my %reformatted = %{$instsecref};
10313:     foreach my $server (@homeservers) {
10314:         if (ref($instsecref) eq 'HASH') {
10315:             my $info = &freeze_escape($instsecref);
10316:             my $response=&reply('autoinstsecreformat:'.$cdom.':'.
10317:                                 $action.':'.$info,$server);
10318:             next if ($response =~ /(con_lost|error|no_such_host|refused|unknown_command)/);
10319:             my @items = split(/&/,$response);
10320:             foreach my $item (@items) {
10321:                 my ($key,$value) = split(/=/,$item);
10322:                 $reformatted{&unescape($key)} = &thaw_unescape($value);
10323:             }
10324:         }
10325:     }
10326:     return %reformatted;
10327: }
10328: 
10329: sub auto_validate_instclasses {
10330:     my ($cdom,$cnum,$owners,$classesref) = @_;
10331:     my ($homeserver,%validations);
10332:     $homeserver = &homeserver($cnum,$cdom);
10333:     unless ($homeserver eq 'no_host') {
10334:         my $ownerlist;
10335:         if (ref($owners) eq 'ARRAY') {
10336:             $ownerlist = join(',',@{$owners});
10337:         } else {
10338:             $ownerlist = $owners;
10339:         }
10340:         if (ref($classesref) eq 'HASH') {
10341:             my $classes = &freeze_escape($classesref);
10342:             my $response=&reply('autovalidateinstclasses:'.&escape($ownerlist).
10343:                                 ':'.$cdom.':'.$classes,$homeserver);
10344:             unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
10345:                 my @items = split(/&/,$response);
10346:                 foreach my $item (@items) {
10347:                     my ($key,$value) = split('=',$item);
10348:                     $validations{&unescape($key)} = &thaw_unescape($value);
10349:                 }
10350:             }
10351:         }
10352:     }
10353:     return %validations;
10354: }
10355: 
10356: sub auto_crsreq_update {
10357:     my ($cdom,$cnum,$crstype,$action,$ownername,$ownerdomain,$fullname,$title,
10358:         $code,$accessstart,$accessend,$inbound) = @_;
10359:     my ($homeserver,%crsreqresponse);
10360:     if ($cdom =~ /^$match_domain$/) {
10361:         $homeserver = &domain($cdom,'primary');
10362:     }
10363:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
10364:         my $info;
10365:         if (ref($inbound) eq 'HASH') {
10366:             $info = &freeze_escape($inbound);
10367:         }
10368:         my $response=&reply('autocrsrequpdate:'.$cdom.':'.$cnum.':'.&escape($crstype).
10369:                             ':'.&escape($action).':'.&escape($ownername).':'.
10370:                             &escape($ownerdomain).':'.&escape($fullname).':'.
10371:                             &escape($title).':'.&escape($code).':'.
10372:                             &escape($accessstart).':'.&escape($accessend).':'.$info,
10373:                             $homeserver);
10374:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
10375:             my @items = split(/&/,$response);
10376:             foreach my $item (@items) {
10377:                 my ($key,$value) = split('=',$item);
10378:                 $crsreqresponse{&unescape($key)} = &thaw_unescape($value);
10379:             }
10380:         }
10381:     }
10382:     return \%crsreqresponse;
10383: }
10384: 
10385: sub auto_export_grades {
10386:     my ($cdom,$cnum,$inforef,$gradesref) = @_;
10387:     my ($homeserver,%exportresponse);
10388:     if ($cdom =~ /^$match_domain$/) {
10389:         $homeserver = &domain($cdom,'primary');
10390:     }
10391:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
10392:         my $info;
10393:         if (ref($inforef) eq 'HASH') {
10394:             $info = &freeze_escape($inforef);
10395:         }
10396:         if (ref($gradesref) eq 'HASH') {
10397:             my $grades = &freeze_escape($gradesref);
10398:             my $response=&reply('encrypt:autoexportgrades:'.$cdom.':'.$cnum.':'.
10399:                                 $info.':'.$grades,$homeserver);
10400:             unless ($response =~ /(con_lost|error|no_such_host|refused|unknown_command)/) {
10401:                 my @items = split(/&/,$response);
10402:                 foreach my $item (@items) {
10403:                     my ($key,$value) = split('=',$item);
10404:                     $exportresponse{&unescape($key)} = &thaw_unescape($value);
10405:                 }
10406:             }
10407:         }
10408:     }
10409:     return \%exportresponse;
10410: }
10411: 
10412: sub check_instcode_cloning {
10413:     my ($codedefaults,$code_order,$cloner,$clonefromcode,$clonetocode) = @_;
10414:     unless ((ref($codedefaults) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
10415:         return;
10416:     }
10417:     my $canclone;
10418:     if (@{$code_order} > 0) {
10419:         my $instcoderegexp ='^';
10420:         my @clonecodes = split(/\&/,$cloner);
10421:         foreach my $item (@{$code_order}) {
10422:             if (grep(/^\Q$item\E=/,@clonecodes)) {
10423:                 foreach my $pair (@clonecodes) {
10424:                     my ($key,$val) = split(/\=/,$pair,2);
10425:                     $val = &unescape($val);
10426:                     if ($key eq $item) {
10427:                         $instcoderegexp .= '('.$val.')';
10428:                         last;
10429:                     }
10430:                 }
10431:             } else {
10432:                 $instcoderegexp .= $codedefaults->{$item};
10433:             }
10434:         }
10435:         $instcoderegexp .= '$';
10436:         my (@from,@to);
10437:         eval {
10438:                (@from) = ($clonefromcode =~ /$instcoderegexp/);
10439:                (@to) = ($clonetocode =~ /$instcoderegexp/);
10440:         };
10441:         if ((@from > 0) && (@to > 0)) {
10442:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
10443:             if (!@diffs) {
10444:                 $canclone = 1;
10445:             }
10446:         }
10447:     }
10448:     return $canclone;
10449: }
10450: 
10451: sub default_instcode_cloning {
10452:     my ($clonedom,$domdefclone,$clonefromcode,$clonetocode,$codedefaultsref,$codeorderref) = @_;
10453:     my (%codedefaults,@code_order,$canclone);
10454:     if ((ref($codedefaultsref) eq 'HASH') && (ref($codeorderref) eq 'ARRAY')) {
10455:         %codedefaults = %{$codedefaultsref};
10456:         @code_order = @{$codeorderref};
10457:     } elsif ($clonedom) {
10458:         &auto_instcode_defaults($clonedom,\%codedefaults,\@code_order);
10459:     }
10460:     if (($domdefclone) && (@code_order)) {
10461:         my @clonecodes = split(/\+/,$domdefclone);
10462:         my $instcoderegexp ='^';
10463:         foreach my $item (@code_order) {
10464:             if (grep(/^\Q$item\E$/,@clonecodes)) {
10465:                 $instcoderegexp .= '('.$codedefaults{$item}.')';
10466:             } else {
10467:                 $instcoderegexp .= $codedefaults{$item};
10468:             }
10469:         }
10470:         $instcoderegexp .= '$';
10471:         my (@from,@to);
10472:         eval {
10473:             (@from) = ($clonefromcode =~ /$instcoderegexp/);
10474:             (@to) = ($clonetocode =~ /$instcoderegexp/);
10475:         };
10476:         if ((@from > 0) && (@to > 0)) {
10477:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
10478:             if (!@diffs) {
10479:                 $canclone = 1;
10480:             }
10481:         }
10482:     }
10483:     return $canclone;
10484: }
10485: 
10486: # ------------------------------------------------------- Course Group routines
10487: 
10488: sub get_coursegroups {
10489:     my ($cdom,$cnum,$group,$namespace) = @_;
10490:     return(&dump($namespace,$cdom,$cnum,$group));
10491: }
10492: 
10493: sub modify_coursegroup {
10494:     my ($cdom,$cnum,$groupsettings) = @_;
10495:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
10496: }
10497: 
10498: sub toggle_coursegroup_status {
10499:     my ($cdom,$cnum,$group,$action) = @_;
10500:     my ($from_namespace,$to_namespace);
10501:     if ($action eq 'delete') {
10502:         $from_namespace = 'coursegroups';
10503:         $to_namespace = 'deleted_groups';
10504:     } else {
10505:         $from_namespace = 'deleted_groups';
10506:         $to_namespace = 'coursegroups';
10507:     }
10508:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
10509:     if (my $tmp = &error(%curr_group)) {
10510:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
10511:         return ('read error',$tmp);
10512:     } else {
10513:         my %savedsettings = %curr_group; 
10514:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
10515:         my $deloutcome;
10516:         if ($result eq 'ok') {
10517:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
10518:         } else {
10519:             return ('write error',$result);
10520:         }
10521:         if ($deloutcome eq 'ok') {
10522:             return 'ok';
10523:         } else {
10524:             return ('delete error',$deloutcome);
10525:         }
10526:     }
10527: }
10528: 
10529: sub modify_group_roles {
10530:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context,
10531:         $othdomby,$requester) = @_;
10532:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
10533:     my $role = 'gr/'.&escape($userprivs);
10534:     my ($uname,$udom) = split(/:/,$user);
10535:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context,
10536:                              $othdomby,$requester);
10537:     if ($result eq 'ok') {
10538:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
10539:     }
10540:     return $result;
10541: }
10542: 
10543: sub modify_coursegroup_membership {
10544:     my ($cdom,$cnum,$membership) = @_;
10545:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
10546:     return $result;
10547: }
10548: 
10549: sub get_active_groups {
10550:     my ($udom,$uname,$cdom,$cnum) = @_;
10551:     my $now = time;
10552:     my %groups = ();
10553:     foreach my $key (keys(%env)) {
10554:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
10555:             my ($start,$end) = split(/\./,$env{$key});
10556:             if (($end!=0) && ($end<$now)) { next; }
10557:             if (($start!=0) && ($start>$now)) { next; }
10558:             if ($1 eq $cdom && $2 eq $cnum) {
10559:                 $groups{$3} = $env{$key} ;
10560:             }
10561:         }
10562:     }
10563:     return %groups;
10564: }
10565: 
10566: sub get_group_membership {
10567:     my ($cdom,$cnum,$group) = @_;
10568:     return(&dump('groupmembership',$cdom,$cnum,$group));
10569: }
10570: 
10571: sub get_users_groups {
10572:     my ($udom,$uname,$courseid) = @_;
10573:     my @usersgroups;
10574:     my $cachetime=1800;
10575: 
10576:     my $hashid="$udom:$uname:$courseid";
10577:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
10578:     if (defined($cached)) {
10579:         @usersgroups = split(/:/,$grouplist);
10580:     } else {  
10581:         $grouplist = '';
10582:         my $courseurl = &courseid_to_courseurl($courseid);
10583:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
10584:         my $access_end = $env{'course.'.$courseid.
10585:                               '.default_enrollment_end_date'};
10586:         my $now = time;
10587:         foreach my $key (keys(%roleshash)) {
10588:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
10589:                 my $group = $1;
10590:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
10591:                     my $start = $2;
10592:                     my $end = $1;
10593:                     if ($start == -1) { next; } # deleted from group
10594:                     if (($start!=0) && ($start>$now)) { next; }
10595:                     if (($end!=0) && ($end<$now)) {
10596:                         if ($access_end && $access_end < $now) {
10597:                             if ($access_end - $end < 86400) {
10598:                                 push(@usersgroups,$group);
10599:                             }
10600:                         }
10601:                         next;
10602:                     }
10603:                     push(@usersgroups,$group);
10604:                 }
10605:             }
10606:         }
10607:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
10608:         $grouplist = join(':',@usersgroups);
10609:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
10610:     }
10611:     return @usersgroups;
10612: }
10613: 
10614: sub devalidate_getgroups_cache {
10615:     my ($udom,$uname,$cdom,$cnum)=@_;
10616:     my $courseid = $cdom.'_'.$cnum;
10617: 
10618:     my $hashid="$udom:$uname:$courseid";
10619:     &devalidate_cache_new('getgroups',$hashid);
10620: }
10621: 
10622: # ------------------------------------------------------------------ Plain Text
10623: 
10624: sub plaintext {
10625:     my ($short,$type,$cid,$forcedefault) = @_;
10626:     if ($short =~ m{^cr/}) {
10627: 	return (split('/',$short))[-1];
10628:     }
10629:     if (!defined($cid)) {
10630:         $cid = $env{'request.course.id'};
10631:     }
10632:     my %rolenames = (
10633:                       Course    => 'std',
10634:                       Community => 'alt1',
10635:                       Placement => 'std',
10636:                     );
10637:     if ($cid ne '') {
10638:         if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
10639:             unless ($forcedefault) {
10640:                 my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
10641:                 &Apache::lonlocal::mt_escape(\$roletext);
10642:                 return &Apache::lonlocal::mt($roletext);
10643:             }
10644:         }
10645:     }
10646:     if ((defined($type)) && (defined($rolenames{$type})) &&
10647:         (defined($rolenames{$type})) && 
10648:         (defined($prp{$short}{$rolenames{$type}}))) {
10649:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
10650:     } elsif ($cid ne '') {
10651:         my $crstype = $env{'course.'.$cid.'.type'};
10652:         if (($crstype ne '') && (defined($rolenames{$crstype})) &&
10653:             (defined($prp{$short}{$rolenames{$crstype}}))) {
10654:             return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
10655:         }
10656:     }
10657:     return &Apache::lonlocal::mt($prp{$short}{'std'});
10658: }
10659: 
10660: # ----------------------------------------------------------------- Assign Role
10661: 
10662: sub assignrole {
10663:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
10664:         $context,$othdomby,$requester,$reqsec,$reqrole)=@_;
10665:     my ($mrole,$rolelogcontext);
10666:     if ($role =~ /^cr\//) {
10667:         my $cwosec=$url;
10668:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
10669:         if ((!&allowed('ccr',$cwosec)) && (!&allowed('ccr',$udom))) {
10670:             my $refused = 1;
10671:             if ($context eq 'requestcourses') {
10672:                 if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
10673:                     if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
10674:                         if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
10675:                             my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
10676:                             my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
10677:                             if ($crsenv{'internal.courseowner'} eq
10678:                                 $env{'user.name'}.':'.$env{'user.domain'}) {
10679:                                 $refused = '';
10680:                             }
10681:                         }
10682:                     }
10683:                 }
10684:             } elsif (($context eq 'course') && ($othdomby eq 'othdombyuser')) {
10685:                 my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
10686:                 my ($sec) = ($url =~ m{^/\Q$cwosec\E/(.*)$});
10687:                 my $key = "$uname:$udom:$role:$sec";
10688:                 my %queuedrolereq = &Apache::lonnet::get('nohist_othdomqueued',[$key],$cdom,$cnum);
10689:                 if ((exists($queuedrolereq{$key})) && (ref($queuedrolereq{$key}) eq 'HASH')) {
10690:                     if (($queuedrolereq{$key}{'adj'} eq 'user') && ($queuedrolereq{$key}{'requester'} eq $requester)) {
10691:                         $refused = '';
10692:                     }
10693:                 }
10694:             }
10695:             if ($refused) {
10696:                 &logthis('Refused custom assignrole: '.
10697:                          $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
10698:                          ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
10699:                 return 'refused';
10700:             }
10701:         }
10702:         $mrole='cr';
10703:     } elsif ($role =~ /^gr\//) {
10704:         my $cwogrp=$url;
10705:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
10706:         if (!&allowed('mdg',$cwogrp)) {
10707:             my $refused = 1;
10708:             if (($refused) && ($othdomby eq 'othdombyuser') && ($requester ne '') && ($reqrole ne '')) {
10709:                 my ($cdom,$cnum) = ($cwogrp =~ m{^/?($match_domain)/($match_courseid)$});
10710:                 my $key = "$uname:$udom:$reqrole:$reqsec";
10711:                 my %queuedrolereq = &Apache::lonnet::get('nohist_othdomqueued',[$key],$cdom,$cnum);
10712:                 if ((exists($queuedrolereq{$key})) && (ref($queuedrolereq{$key}) eq 'HASH')) {
10713:                     if (($queuedrolereq{$key}{'adj'} eq 'user') && ($queuedrolereq{$key}{'requester'} eq $requester)) {
10714:                         $refused = '';
10715:                     }
10716:                 }
10717:             }
10718:             if ($refused) {
10719:                 &logthis('Refused group assignrole: '.
10720:                          $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
10721:                          $env{'user.name'}.' at '.$env{'user.domain'});
10722:                 return 'refused';
10723:             }
10724:         }
10725:         $mrole='gr';
10726:     } else {
10727:         my $cwosec=$url;
10728:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
10729:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
10730:             my $refused;
10731:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
10732:                 if (!(&allowed('c'.$role,$url))) {
10733:                     $refused = 1;
10734:                 }
10735:             } else {
10736:                 $refused = 1;
10737:             }
10738:             if ($refused) {
10739:                 my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
10740:                 if (!$selfenroll && ($othdomby ne 'othdombyuser') &&
10741:                    (($context eq 'course') || ($context eq 'ltienroll' && $env{'request.lti.login'}))) {
10742:                     my %crsenv;
10743:                     if ($role eq 'cc' || $role eq 'co') {
10744:                         %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
10745:                         if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
10746:                             if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
10747:                                 if ($crsenv{'internal.courseowner'} eq 
10748:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
10749:                                     $refused = '';
10750:                                 }
10751:                             }
10752:                         } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) { 
10753:                             if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
10754:                                 if ($crsenv{'internal.courseowner'} eq 
10755:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
10756:                                     $refused = '';
10757:                                 }
10758:                             }
10759:                         }
10760:                     }
10761:                 } elsif (($selfenroll == 1) && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
10762:                     if ($role eq 'st') {
10763:                         $refused = '';
10764:                     } elsif (($context eq 'ltienroll') && ($env{'request.lti.login'})) {
10765:                         $refused = '';
10766:                     }
10767:                 } elsif ($othdomby eq 'othdombyuser') {
10768:                     my ($key,%queuedrolereq);
10769:                     if ($context eq 'course') {
10770:                         my ($sec) = ($url =~ m{^/\Q$cwosec\E/(.*)$});
10771:                         $key = "$uname:$udom:$role:$sec";
10772:                         %queuedrolereq = &Apache::lonnet::get('nohist_othdomqueued',[$key],$cdom,$cnum);
10773:                         if ((exists($queuedrolereq{$key})) && (ref($queuedrolereq{$key}) eq 'HASH')) {
10774:                             if (($queuedrolereq{$key}{'adj'} eq 'user') && ($queuedrolereq{$key}{'requester'} eq $requester)) {
10775:                                 if ((($role eq 'cc') && ($cnum !~ /^$match_community$/)) || 
10776:                                     (($role eq 'co') && ($cnum =~ /^$match_community$/))) {
10777:                                     my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
10778:                                     if ($crsenv{'internal.courseowner'} eq $requester) {
10779:                                         $refused = '';
10780:                                     }
10781:                                 } elsif ($role =~ /^(?:in|ta|ep|st)$/) {
10782:                                     $refused = '';
10783:                                 }
10784:                             }
10785:                         }
10786:                     } elsif (($context eq 'author') && ($role =~ /^ca|aa$/)) {
10787:                         my $key = "$uname:$udom:$role"; 
10788:                         my ($audom,$auname) = ($url =~ m{^/($match_domain)/($match_username)$});
10789:                         if (($audom ne '') && ($auname ne '')) {
10790:                             my %queuedrolereq = &Apache::lonnet::get('nohist_othdomqueued',[$key],$audom,$auname);
10791:                             if ((exists($queuedrolereq{$key})) && (ref($queuedrolereq{$key}) eq 'HASH')) {
10792:                                 if (($queuedrolereq{$key}{'adj'} eq 'user') && ($queuedrolereq{$key}{'requester'} eq $requester)) {
10793:                                     $refused = '';
10794:                                 }
10795:                             }
10796:                         }
10797:                     } elsif (($context eq 'domain') && ($role ne 'dc') && ($role ne 'su')) {
10798:                         my $key = "$uname:$udom:$role";
10799:                         my ($roledom) = ($url =~ m{^/($match_domain)/\Q$role\E$});
10800:                         if ($roledom ne '') {
10801:                             my $confname = $roledom.'-domainconfig';
10802:                             my %queuedrolereq = &Apache::lonnet::get('nohist_othdomqueued',[$key],$roledom,$confname);
10803:                             if ((exists($queuedrolereq{$key})) && (ref($queuedrolereq{$key}) eq 'HASH')) {
10804:                                 if (($queuedrolereq{$key}{'adj'} eq 'user') && ($queuedrolereq{$key}{'requester'} eq $requester)) {
10805:                                     $refused = '';
10806:                                 }
10807:                             }
10808:                         }
10809:                     }
10810:                 } elsif ($context eq 'requestcourses') {
10811:                     my @possroles = ('st','ta','ep','in','cc','co');
10812:                     if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
10813:                         my $wrongcc;
10814:                         if ($cnum =~ /^$match_community$/) {
10815:                             $wrongcc = 1 if ($role eq 'cc');
10816:                         } else {
10817:                             $wrongcc = 1 if ($role eq 'co');
10818:                         }
10819:                         unless ($wrongcc) {
10820:                             my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
10821:                             if ($crsenv{'internal.courseowner'} eq 
10822:                                  $env{'user.name'}.':'.$env{'user.domain'}) {
10823:                                 $refused = '';
10824:                             }
10825:                         }
10826:                     }
10827:                 } elsif ($context eq 'requestauthor') {
10828:                     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) && 
10829:                         ($url eq '/'.$udom.'/') && ($role eq 'au')) {
10830:                         if ($env{'environment.requestauthor'} eq 'automatic') {
10831:                             $refused = '';
10832:                         } else {
10833:                             my %domdefaults = &get_domain_defaults($udom);
10834:                             if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
10835:                                 my $checkbystatus;
10836:                                 if ($env{'user.adv'}) { 
10837:                                     my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
10838:                                     if ($disposition eq 'automatic') {
10839:                                         $refused = '';
10840:                                     } elsif ($disposition eq '') {
10841:                                         $checkbystatus = 1;
10842:                                     } 
10843:                                 } else {
10844:                                     $checkbystatus = 1;
10845:                                 }
10846:                                 if ($checkbystatus) {
10847:                                     if ($env{'environment.inststatus'}) {
10848:                                         my @inststatuses = split(/,/,$env{'environment.inststatus'});
10849:                                         foreach my $type (@inststatuses) {
10850:                                             if (($type ne '') &&
10851:                                                 ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
10852:                                                 $refused = '';
10853:                                             }
10854:                                         }
10855:                                     } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
10856:                                         $refused = '';
10857:                                     }
10858:                                 }
10859:                             }
10860:                         }
10861:                     }
10862:                 } elsif (($context eq 'author') && (($role eq 'ca' || $role eq 'aa'))) {
10863:                     if ($url =~ m{^/($match_domain)/($match_username)$}) {
10864:                         my ($audom,$auname) = ($1,$2);
10865:                         if ((&Apache::lonnet::allowed('v'.$role,"$audom/$auname")) &&
10866:                             ($env{"environment.internal.manager.$url"})) {
10867:                             $refused = '';
10868:                             $rolelogcontext = 'coauthor';
10869:                         }
10870:                     }
10871:                 }
10872:                 if ($refused) {
10873:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
10874:                              ' '.$role.' '.$end.' '.$start.' by '.
10875: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
10876:                     return 'refused';
10877:                 }
10878:             }
10879:         } elsif ($role eq 'au') {
10880:             if ($url ne '/'.$udom.'/') {
10881:                 &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
10882:                          ' to assign author role for '.$uname.':'.$udom.
10883:                          ' in domain: '.$url.' refused (wrong domain).');
10884:                 return 'refused';
10885:             }
10886:         }
10887:         $mrole=$role;
10888:     }
10889:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
10890:                 "$udom:$uname:$url".'_'."$mrole=$role";
10891:     if ($end) { $command.='_'.$end; }
10892:     if ($start) {
10893: 	if ($end) { 
10894:            $command.='_'.$start; 
10895:         } else {
10896:            $command.='_0_'.$start;
10897:         }
10898:     }
10899:     my $origstart = $start;
10900:     my $origend = $end;
10901:     my $delflag;
10902: # actually delete
10903:     if ($deleteflag) {
10904: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
10905: # modify command to delete the role
10906:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
10907:                 "$udom:$uname:$url".'_'."$mrole";
10908: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
10909: # set start and finish to negative values for userrolelog
10910:            $start=-1;
10911:            $end=-1;
10912:            $delflag = 1;
10913:         }
10914:     }
10915: # send command
10916:     my $answer=&reply($command,&homeserver($uname,$udom));
10917: # log new user role if status is ok
10918:     if ($answer eq 'ok') {
10919: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
10920:         if (($role eq 'cc') || ($role eq 'in') ||
10921:             ($role eq 'ep') || ($role eq 'ad') ||
10922:             ($role eq 'ta') || ($role eq 'st') ||
10923:             ($role=~/^cr/) || ($role eq 'gr') ||
10924:             ($role eq 'co')) {
10925: # for course roles, perform group memberships changes triggered by role change.
10926:             unless ($role =~ /^gr/) {
10927:                 &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
10928:                                                  $origstart,$selfenroll,$context);
10929:             }
10930:             &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
10931:                            $selfenroll,$context,$othdomby,$requester);
10932:         } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
10933:                  ($role eq 'au') || ($role eq 'dc') || ($role eq 'dh') ||
10934:                  ($role eq 'da')) {
10935:             &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
10936:                            $context,$othdomby,$requester);
10937:         } elsif (($role eq 'ca') || ($role eq 'aa')) {
10938:             if ($rolelogcontext eq '') {
10939:                 $rolelogcontext = $context;
10940:             }
10941:             &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
10942:                              $rolelogcontext,$othdomby,$requester); 
10943:         }
10944:         if ($role eq 'cc') {
10945:             &autoupdate_coowners($url,$end,$start,$uname,$udom);
10946:         }
10947:     }
10948:     return $answer;
10949: }
10950: 
10951: sub autoupdate_coowners {
10952:     my ($url,$end,$start,$uname,$udom) = @_;
10953:     my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
10954:     if (($cdom ne '') && ($cnum ne '')) {
10955:         my $now = time;
10956:         my %domdesign = &Apache::loncommon::get_domainconf($cdom);
10957:         if ($domdesign{$cdom.'.autoassign.co-owners'}) {
10958:             my %coursehash = &coursedescription($cdom.'_'.$cnum);
10959:             my $instcode = $coursehash{'internal.coursecode'};
10960:             my $xlists = $coursehash{'internal.crosslistings'};
10961:             if ($instcode ne '') {
10962:                 if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
10963:                     unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
10964:                         my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
10965:                         my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
10966:                         unless ($result eq 'valid') {
10967:                             if ($xlists ne '') {
10968:                                 foreach my $xlist (split(',',$xlists)) {
10969:                                     my ($inst_crosslist,$lcsec) = split(':',$xlist);
10970:                                     $result =
10971:                                         &auto_validate_inst_crosslist($cnum,$cdom,$instcode,
10972:                                                                       $inst_crosslist,$uname.':'.$udom);
10973:                                     last if ($result eq 'valid');
10974:                                 }
10975:                             }
10976:                         }
10977:                         if ($result eq 'valid') {
10978:                             if ($coursehash{'internal.co-owners'}) {
10979:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
10980:                                     push(@newcoowners,$coowner);
10981:                                 }
10982:                                 unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
10983:                                     push(@newcoowners,$uname.':'.$udom);
10984:                                 }
10985:                                 @newcoowners = sort(@newcoowners);
10986:                             } else {
10987:                                 push(@newcoowners,$uname.':'.$udom);
10988:                             }
10989:                         } elsif ($coursehash{'internal.co-owners'}) {
10990:                             foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
10991:                                 unless ($coowner eq $uname.':'.$udom) {
10992:                                     push(@newcoowners,$coowner);
10993:                                 }
10994:                             }
10995:                             unless (@newcoowners > 0) {
10996:                                 $delcoowners = 1;
10997:                                 $coowners = '';
10998:                             }
10999:                         }
11000:                         if (@newcoowners || $delcoowners) {
11001:                             &store_coowners($cdom,$cnum,$coursehash{'home'},
11002:                                             $delcoowners,@newcoowners);
11003:                         }
11004:                     }
11005:                 }
11006:             }
11007:         }
11008:     }
11009: }
11010: 
11011: sub store_coowners {
11012:     my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
11013:     my $cid = $cdom.'_'.$cnum;
11014:     my ($coowners,$delresult,$putresult);
11015:     if (@newcoowners) {
11016:         $coowners = join(',',@newcoowners);
11017:         my %coownershash = (
11018:                             'internal.co-owners' => $coowners,
11019:                            );
11020:         $putresult = &put('environment',\%coownershash,$cdom,$cnum);
11021:         if ($putresult eq 'ok') {
11022:             if ($env{'course.'.$cid.'.num'} eq $cnum) {
11023:                 &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
11024:             }
11025:         }
11026:     }
11027:     if ($delcoowners) {
11028:         $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
11029:         if ($delresult eq 'ok') {
11030:             if ($env{'course.'.$cid.'.internal.co-owners'}) {
11031:                 &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
11032:             }
11033:         }
11034:     }
11035:     if (($putresult eq 'ok') || ($delresult eq 'ok')) {
11036:         my %crsinfo =
11037:             &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
11038:         if (ref($crsinfo{$cid}) eq 'HASH') {
11039:             $crsinfo{$cid}{'co-owners'} = \@newcoowners;
11040:             my $cidput = &courseidput($cdom,\%crsinfo,$chome,'notime');
11041:         }
11042:     }
11043: }
11044: 
11045: # -------------------------------------------------- Modify user authentication
11046: # Overrides without validation
11047: 
11048: sub modifyuserauth {
11049:     my ($udom,$uname,$umode,$upass)=@_;
11050:     my $uhome=&homeserver($uname,$udom);
11051:     my $allowed;
11052:     if (&allowed('mau',$udom)) {
11053:         $allowed = 1;
11054:     } elsif (($umode eq 'internal') && ($udom eq $env{'user.domain'}) &&
11055:              ($env{'request.course.id'}) && (&allowed('mip',$env{'request.course.id'})) &&
11056:              (!$env{'course.'.$env{'request.course.id'}.'.internal.nopasswdchg'})) {
11057:         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
11058:         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
11059:         if (($cdom ne '') && ($cnum ne '')) {
11060:             my $is_owner = &is_course_owner($cdom,$cnum);
11061:             if ($is_owner) {
11062:                 $allowed = 1;
11063:             }
11064:         }
11065:     }
11066:     unless ($allowed) { return 'refused'; }
11067:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
11068:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
11069:              ' in domain '.$env{'request.role.domain'});  
11070:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
11071: 		     &escape($upass),$uhome);
11072:     my $ip = &get_requestor_ip();
11073:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
11074:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
11075:          '(Remote '.$ip.'): '.$reply);
11076:     &log($udom,,$uname,$uhome,
11077:         'Authentication changed by '.$env{'user.domain'}.', '.
11078:                                      $env{'user.name'}.', '.$umode.
11079:          '(Remote '.$ip.'): '.$reply);
11080:     unless ($reply eq 'ok') {
11081:         &logthis('Authentication mode error: '.$reply);
11082: 	return 'error: '.$reply;
11083:     }   
11084:     return 'ok';
11085: }
11086: 
11087: # --------------------------------------------------------------- Modify a user
11088: 
11089: sub modifyuser {
11090:     my ($udom,    $uname, $uid,
11091:         $umode,   $upass, $first,
11092:         $middle,  $last,  $gene,
11093:         $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
11094:     $udom= &LONCAPA::clean_domain($udom);
11095:     $uname=&LONCAPA::clean_username($uname);
11096:     my $showcandelete = 'none';
11097:     if (ref($candelete) eq 'ARRAY') {
11098:         if (@{$candelete} > 0) {
11099:             $showcandelete = join(', ',@{$candelete});
11100:         }
11101:     }
11102:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
11103:              $umode.', '.$first.', '.$middle.', '.
11104: 	     $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
11105:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
11106:                                      ' desiredhome not specified'). 
11107:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
11108:              ' in domain '.$env{'request.role.domain'});
11109:     my $uhome=&homeserver($uname,$udom,'true');
11110:     my $newuser;
11111:     if ($uhome eq 'no_host') {
11112:         $newuser = 1;
11113:         unless (($umode && ($upass ne '')) || ($umode eq 'localauth') ||
11114:                 ($umode eq 'lti')) {
11115:             return 'error: more information needed to create new user';
11116:         }
11117:     }
11118: # ----------------------------------------------------------------- Create User
11119:     if (($uhome eq 'no_host') && 
11120: 	(($umode && $upass) || ($umode eq 'localauth') || ($umode eq 'lti'))) {
11121:         my $unhome='';
11122:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
11123:             $unhome = $desiredhome;
11124: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
11125: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
11126:         } else { # load balancing routine for determining $unhome
11127:             my $loadm=10000000;
11128: 	    my %servers = &get_servers($udom,'library');
11129: 	    foreach my $tryserver (keys(%servers)) {
11130: 		my $answer=reply('load',$tryserver);
11131: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
11132: 		    $loadm=$answer;
11133: 		    $unhome=$tryserver;
11134: 		}
11135: 	    }
11136:         }
11137:         if (($unhome eq '') || ($unhome eq 'no_host')) {
11138: 	    return 'error: unable to find a home server for '.$uname.
11139:                    ' in domain '.$udom;
11140:         }
11141:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
11142:                          &escape($upass),$unhome);
11143: 	unless ($reply eq 'ok') {
11144:             return 'error: '.$reply;
11145:         }   
11146:         $uhome=&homeserver($uname,$udom,'true');
11147:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
11148: 	    return 'error: unable verify users home machine.';
11149:         }
11150:     }   # End of creation of new user
11151: # ---------------------------------------------------------------------- Add ID
11152:     if ($uid) {
11153:        $uid=~tr/A-Z/a-z/;
11154:        my %uidhash=&idrget($udom,$uname);
11155:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
11156:          && (!$forceid)) {
11157: 	  unless ($uid eq $uidhash{$uname}) {
11158: 	      return 'error: user id "'.$uid.'" does not match '.
11159:                   'current user id "'.$uidhash{$uname}.'".';
11160:           }
11161:        } else {
11162: 	  &idput($udom,{$uname => $uid},$uhome,'ids');
11163:        }
11164:     }
11165: # -------------------------------------------------------------- Add names, etc
11166:     my @tmp=&get('environment',
11167: 		   ['firstname','middlename','lastname','generation','id',
11168:                     'permanentemail','inststatus'],
11169: 		   $udom,$uname);
11170:     my (%names,%oldnames);
11171:     if ($tmp[0] =~ m/^error:.*/) { 
11172:         %names=(); 
11173:     } else {
11174:         %names = @tmp;
11175:         %oldnames = %names;
11176:     }
11177: #
11178: # If name, email and/or uid are blank (e.g., because an uploaded file
11179: # of users did not contain them), do not overwrite existing values
11180: # unless field is in $candelete array ref.  
11181: #
11182: 
11183:     my @fields = ('firstname','middlename','lastname','generation',
11184:                   'permanentemail','id');
11185:     my %newvalues;
11186:     if (ref($candelete) eq 'ARRAY') {
11187:         foreach my $field (@fields) {
11188:             if (grep(/^\Q$field\E$/,@{$candelete})) {
11189:                 if ($field eq 'firstname') {
11190:                     $names{$field} = $first;
11191:                 } elsif ($field eq 'middlename') {
11192:                     $names{$field} = $middle;
11193:                 } elsif ($field eq 'lastname') {
11194:                     $names{$field} = $last;
11195:                 } elsif ($field eq 'generation') { 
11196:                     $names{$field} = $gene;
11197:                 } elsif ($field eq 'permanentemail') {
11198:                     $names{$field} = $email;
11199:                 } elsif ($field eq 'id') {
11200:                     $names{$field}  = $uid;
11201:                 }
11202:             }
11203:         }
11204:     }
11205:     if ($first)  { $names{'firstname'}  = $first; }
11206:     if (defined($middle)) { $names{'middlename'} = $middle; }
11207:     if ($last)   { $names{'lastname'}   = $last; }
11208:     if (defined($gene))   { $names{'generation'} = $gene; }
11209:     if ($email) {
11210:        $email=~s/[^\w\@\.\-\,]//gs;
11211:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
11212:     }
11213:     if ($uid) { $names{'id'}  = $uid; }
11214:     if (defined($inststatus)) {
11215:         $names{'inststatus'} = '';
11216:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
11217:         if (ref($usertypes) eq 'HASH') {
11218:             my @okstatuses; 
11219:             foreach my $item (split(/:/,$inststatus)) {
11220:                 if (defined($usertypes->{$item})) {
11221:                     push(@okstatuses,$item);  
11222:                 }
11223:             }
11224:             if (@okstatuses) {
11225:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
11226:             }
11227:         }
11228:     }
11229:     my $logmsg = $udom.', '.$uname.', '.$uid.', '.
11230:                  $umode.', '.$first.', '.$middle.', '.
11231:                  $last.', '.$gene.', '.$email.', '.$inststatus;
11232:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
11233:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
11234:     } else {
11235:         $logmsg .= ' during self creation';
11236:     }
11237:     my $changed;
11238:     if ($newuser) {
11239:         $changed = 1;
11240:     } else {
11241:         foreach my $field (@fields) {
11242:             if ($names{$field} ne $oldnames{$field}) {
11243:                 $changed = 1;
11244:                 last;
11245:             }
11246:         }
11247:     }
11248:     unless ($changed) {
11249:         $logmsg = 'No changes in user information needed for: '.$logmsg;
11250:         &logthis($logmsg);
11251:         return 'ok';
11252:     }
11253:     my $reply = &put('environment', \%names, $udom,$uname);
11254:     if ($reply ne 'ok') { 
11255:         return 'error: '.$reply;
11256:     }
11257:     if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
11258:         &devalidate_cache_new('emailscache',$uname.':'.$udom);
11259:     }
11260:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
11261:     &devalidate_cache_new('namescache',$uname.':'.$udom);
11262:     $logmsg = 'Success modifying user '.$logmsg;
11263:     &logthis($logmsg);
11264:     return 'ok';
11265: }
11266: 
11267: # -------------------------------------------------------------- Modify student
11268: 
11269: sub modifystudent {
11270:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
11271:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
11272:         $selfenroll,$context,$inststatus,$credits,$instsec)=@_;
11273:     if (!$cid) {
11274: 	unless ($cid=$env{'request.course.id'}) {
11275: 	    return 'not_in_class';
11276: 	}
11277:     }
11278: # --------------------------------------------------------------- Make the user
11279:     my $reply=&modifyuser
11280: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
11281:          $desiredhome,$email,$inststatus);
11282:     unless ($reply eq 'ok') { return $reply; }
11283:     # This will cause &modify_student_enrollment to get the uid from the
11284:     # student's environment
11285:     $uid = undef if (!$forceid);
11286:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
11287:                                         $gene,$usec,$end,$start,$type,$locktype,
11288:                                         $cid,$selfenroll,$context,$credits,$instsec);
11289:     return $reply;
11290: }
11291: 
11292: sub modify_student_enrollment {
11293:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,
11294:         $locktype,$cid,$selfenroll,$context,$credits,$instsec,$othdomby,$requester) = @_;
11295:     my ($cdom,$cnum,$chome);
11296:     if (!$cid) {
11297: 	unless ($cid=$env{'request.course.id'}) {
11298: 	    return 'not_in_class';
11299: 	}
11300: 	$cdom=$env{'course.'.$cid.'.domain'};
11301: 	$cnum=$env{'course.'.$cid.'.num'};
11302:     } else {
11303: 	($cdom,$cnum)=split(/_/,$cid);
11304:     }
11305:     $chome=$env{'course.'.$cid.'.home'};
11306:     if (!$chome) {
11307: 	$chome=&homeserver($cnum,$cdom);
11308:     }
11309:     if (!$chome) { return 'unknown_course'; }
11310:     # Make sure the user exists
11311:     my $uhome=&homeserver($uname,$udom);
11312:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
11313: 	return 'error: no such user';
11314:     }
11315:     # Get student data if we were not given enough information
11316:     if (!defined($first)  || $first  eq '' || 
11317:         !defined($last)   || $last   eq '' || 
11318:         !defined($uid)    || $uid    eq '' || 
11319:         !defined($middle) || $middle eq '' || 
11320:         !defined($gene)   || $gene   eq '') {
11321:         # They did not supply us with enough data to enroll the student, so
11322:         # we need to pick up more information.
11323:         my %tmp = &get('environment',
11324:                        ['firstname','middlename','lastname', 'generation','id']
11325:                        ,$udom,$uname);
11326: 
11327:         #foreach my $key (keys(%tmp)) {
11328:         #    &logthis("key $key = ".$tmp{$key});
11329:         #}
11330:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
11331:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
11332:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
11333:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
11334:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
11335:     }
11336:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
11337:     my $user = "$uname:$udom";
11338:     my %old_entry = &get('classlist',[$user],$cdom,$cnum);
11339:     my $reply=cput('classlist',
11340: 		   {$user => 
11341: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits,$instsec) },
11342: 		   $cdom,$cnum);
11343:     if (($reply eq 'ok') || ($reply eq 'delayed')) {
11344:         &devalidate_getsection_cache($udom,$uname,$cid);
11345:     } else { 
11346: 	return 'error: '.$reply;
11347:     }
11348:     # Add student role to user
11349:     my $uurl='/'.$cid;
11350:     $uurl=~s/\_/\//g;
11351:     if ($usec) {
11352: 	$uurl.='/'.$usec;
11353:     }
11354:     my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
11355:                              $selfenroll,$context,$othdomby,$requester);
11356:     if ($result ne 'ok') {
11357:         if ($old_entry{$user} ne '') {
11358:             $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
11359:         } else {
11360:             $reply = &del('classlist',[$user],$cdom,$cnum);
11361:         }
11362:     }
11363:     return $result; 
11364: }
11365: 
11366: sub format_name {
11367:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
11368:     my $name;
11369:     if ($first ne 'lastname') {
11370: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
11371:     } else {
11372: 	if ($lastname=~/\S/) {
11373: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
11374: 	    $name=~s/\s+,/,/;
11375: 	} else {
11376: 	    $name.= $firstname.' '.$middlename.' '.$generation;
11377: 	}
11378:     }
11379:     $name=~s/^\s+//;
11380:     $name=~s/\s+$//;
11381:     $name=~s/\s+/ /g;
11382:     return $name;
11383: }
11384: 
11385: # ------------------------------------------------- Write to course preferences
11386: 
11387: sub writecoursepref {
11388:     my ($courseid,%prefs)=@_;
11389:     $courseid=~s/^\///;
11390:     $courseid=~s/\_/\//g;
11391:     my ($cdomain,$cnum)=split(/\//,$courseid);
11392:     my $chome=homeserver($cnum,$cdomain);
11393:     if (($chome eq '') || ($chome eq 'no_host')) { 
11394: 	return 'error: no such course';
11395:     }
11396:     my $cstring='';
11397:     foreach my $pref (keys(%prefs)) {
11398: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
11399:     }
11400:     $cstring=~s/\&$//;
11401:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
11402: }
11403: 
11404: # ---------------------------------------------------------- Make/modify course
11405: 
11406: sub createcourse {
11407:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
11408:         $course_owner,$crstype,$cnum,$context,$category,$callercontext)=@_;
11409:     $url=&declutter($url);
11410:     my $cid='';
11411:     if ($context eq 'requestcourses') {
11412:         my $can_create = 0;
11413:         my ($ownername,$ownerdom) = split(':',$course_owner);
11414:         if ($udom eq $ownerdom) {
11415:             my $reload;
11416:             if (($callercontext eq 'auto') &&
11417:                ($ownerdom eq $env{'user.domain'}) && ($ownername eq $env{'user.name'})) {
11418:                 $reload = 'reload';
11419:             }
11420:             if (&usertools_access($ownername,$ownerdom,$category,$reload,
11421:                                   $context)) {
11422:                 $can_create = 1;
11423:             }
11424:         } else {
11425:             my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
11426:                                            $category);
11427:             if ($userenv{'reqcrsotherdom.'.$category} ne '') {
11428:                 my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
11429:                 if (@curr > 0) {
11430:                     my @options = qw(approval validate autolimit);
11431:                     my $optregex = join('|',@options);
11432:                     if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
11433:                         $can_create = 1;
11434:                     }
11435:                 }
11436:             }
11437:         }
11438:         if ($can_create) {
11439:             unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
11440:                 unless (&allowed('ccc',$udom)) {
11441:                     return 'refused'; 
11442:                 }
11443:             }
11444:         } else {
11445:             return 'refused';
11446:         }
11447:     } elsif (!&allowed('ccc',$udom)) {
11448:         return 'refused';
11449:     }
11450: # --------------------------------------------------------------- Get Unique ID
11451:     my $uname;
11452:     if ($cnum =~ /^$match_courseid$/) {
11453:         my $chome=&homeserver($cnum,$udom,'true');
11454:         if (($chome eq '') || ($chome eq 'no_host')) {
11455:             $uname = $cnum;
11456:         } else {
11457:             $uname = &generate_coursenum($udom,$crstype);
11458:         }
11459:     } else {
11460:         $uname = &generate_coursenum($udom,$crstype);
11461:     }
11462:     return $uname if ($uname =~ /^error/);
11463: # -------------------------------------------------- Check supplied server name
11464:     if (!defined($course_server)) {
11465:         if (defined(&domain($udom,'primary'))) {
11466:             $course_server = &domain($udom,'primary');
11467:         } else {
11468:             $course_server = $env{'user.home'}; 
11469:         }
11470:     }
11471:     my %host_servers =
11472:         &get_servers($udom,'library');
11473:     unless ($host_servers{$course_server}) {
11474:         return 'error: invalid home server for course: '.$course_server;
11475:     }
11476: # ------------------------------------------------------------- Make the course
11477:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
11478:                       $course_server);
11479:     unless ($reply eq 'ok') { return 'error: '.$reply; }
11480:     my $uhome=&homeserver($uname,$udom,'true');
11481:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
11482: 	return 'error: no such course';
11483:     }
11484: # ----------------------------------------------------------------- Course made
11485: # log existence
11486:     my $now = time;
11487:     my $newcourse = {
11488:                     $udom.'_'.$uname => {
11489:                                      description => $description,
11490:                                      inst_code   => $inst_code,
11491:                                      owner       => $course_owner,
11492:                                      type        => $crstype,
11493:                                      creator     => $env{'user.name'}.':'.
11494:                                                     $env{'user.domain'},
11495:                                      created     => $now,
11496:                                      context     => $context,
11497:                                                 },
11498:                     };
11499:     &courseidput($udom,$newcourse,$uhome,'notime');
11500: # set toplevel url
11501:     my $topurl=$url;
11502:     unless ($nonstandard) {
11503: # ------------------------------------------ For standard courses, make top url
11504:         my $mapurl=&clutter($url);
11505:         if ($mapurl eq '/res/') { $mapurl=''; }
11506:         $env{'form.initmap'}=(<<ENDINITMAP);
11507: <map>
11508: <resource id="1" type="start"></resource>
11509: <resource id="2" src="$mapurl"></resource>
11510: <resource id="3" type="finish"></resource>
11511: <link index="1" from="1" to="2"></link>
11512: <link index="2" from="2" to="3"></link>
11513: </map>
11514: ENDINITMAP
11515:         $topurl=&declutter(
11516:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
11517:                           );
11518:     }
11519: # ----------------------------------------------------------- Write preferences
11520:     &writecoursepref($udom.'_'.$uname,
11521:                      ('description'              => $description,
11522:                       'url'                      => $topurl,
11523:                       'internal.creator'         => $env{'user.name'}.':'.
11524:                                                     $env{'user.domain'},
11525:                       'internal.created'         => $now,
11526:                       'internal.creationcontext' => $context)
11527:                     );
11528:     return '/'.$udom.'/'.$uname;
11529: }
11530: 
11531: # ------------------------------------------------------------------- Create ID
11532: sub generate_coursenum {
11533:     my ($udom,$crstype) = @_;
11534:     my $domdesc = &domain($udom);
11535:     return 'error: invalid domain' if ($domdesc eq '');
11536:     my $first;
11537:     if ($crstype eq 'Community') {
11538:         $first = '0';
11539:     } else {
11540:         $first = int(1+rand(9)); 
11541:     } 
11542:     my $uname=$first.
11543:         ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
11544:         substr($$.time,0,5).unpack("H8",pack("I32",time)).
11545:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
11546: # ----------------------------------------------- Make sure that does not exist
11547:     my $uhome=&homeserver($uname,$udom,'true');
11548:     unless (($uhome eq '') || ($uhome eq 'no_host')) {
11549:         if ($crstype eq 'Community') {
11550:             $first = '0';
11551:         } else {
11552:             $first = int(1+rand(9));
11553:         }
11554:         $uname=$first.
11555:                ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
11556:                substr($$.time,0,5).unpack("H8",pack("I32",time)).
11557:                unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
11558:         $uhome=&homeserver($uname,$udom,'true');
11559:         unless (($uhome eq '') || ($uhome eq 'no_host')) {
11560:             return 'error: unable to generate unique course-ID';
11561:         }
11562:     }
11563:     return $uname;
11564: }
11565: 
11566: sub is_course {
11567:     my ($cdom, $cnum) = scalar(@_) == 1 ? 
11568:          ($_[0] =~ /^($match_domain)_($match_courseid)$/)  :  @_;
11569: 
11570:     return unless (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/));
11571:     my $uhome=&homeserver($cnum,$cdom);
11572:     my $iscourse;
11573:     if (grep { $_ eq $uhome } current_machine_ids()) {
11574:         $iscourse = &LONCAPA::Lond::is_course($cdom,$cnum);
11575:     } else {
11576:         my $hashid = $cdom.':'.$cnum;
11577:         ($iscourse,my $cached) = &is_cached_new('iscourse',$hashid);
11578:         unless (defined($cached)) {
11579:             my %courses = &courseiddump($cdom, '.', 1, '.', '.',
11580:                                         $cnum,undef,undef,'.');
11581:             $iscourse = 0;
11582:             if (exists($courses{$cdom.'_'.$cnum})) {
11583:                 $iscourse = 1;
11584:             }
11585:             &do_cache_new('iscourse',$hashid,$iscourse,3600);
11586:         }
11587:     }
11588:     return unless ($iscourse);
11589:     return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
11590: }
11591: 
11592: sub store_userdata {
11593:     my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
11594:     my $result;
11595:     if ($datakey ne '') {
11596:         if (ref($storehash) eq 'HASH') {
11597:             if ($udom eq '' || $uname eq '') {
11598:                 $udom = $env{'user.domain'};
11599:                 $uname = $env{'user.name'};
11600:             }
11601:             my $uhome=&homeserver($uname,$udom);
11602:             if (($uhome eq '') || ($uhome eq 'no_host')) {
11603:                 $result = 'error: no_host';
11604:             } else {
11605:                 $storehash->{'ip'} = &get_requestor_ip();
11606:                 $storehash->{'host'} = $perlvar{'lonHostID'};
11607: 
11608:                 my $namevalue='';
11609:                 foreach my $key (keys(%{$storehash})) {
11610:                     $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
11611:                 }
11612:                 $namevalue=~s/\&$//;
11613:                 unless ($namespace eq 'courserequests') {
11614:                     $datakey = &escape($datakey);
11615:                 }
11616:                 $result =  &reply("store:$udom:$uname:$namespace:$datakey:".
11617:                                   $namevalue,$uhome);
11618:             }
11619:         } else {
11620:             $result = 'error: data to store was not a hash reference'; 
11621:         }
11622:     } else {
11623:         $result= 'error: invalid requestkey'; 
11624:     }
11625:     return $result;
11626: }
11627: 
11628: # ---------------------------------------------------------- Assign Custom Role
11629: 
11630: sub assigncustomrole {
11631:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,
11632:         $selfenroll,$context,$othdomby,$requester)=@_;
11633:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
11634:                        $end,$start,$deleteflag,$selfenroll,$context,$othdomby,
11635:                        $requester);
11636: }
11637: 
11638: # ----------------------------------------------------------------- Revoke Role
11639: 
11640: sub revokerole {
11641:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
11642:     my $now=time;
11643:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
11644: }
11645: 
11646: # ---------------------------------------------------------- Revoke Custom Role
11647: 
11648: sub revokecustomrole {
11649:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
11650:     my $now=time;
11651:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
11652:            $deleteflag,$selfenroll,$context);
11653: }
11654: 
11655: # ------------------------------------------------------------ Disk usage
11656: sub diskusage {
11657:     my ($udom,$uname,$directorypath,$getpropath)=@_;
11658:     $directorypath =~ s/\/$//;
11659:     my $listing=&reply('du2:'.&escape($directorypath).':'
11660:                        .&escape($getpropath).':'.&escape($uname).':'
11661:                        .&escape($udom),homeserver($uname,$udom));
11662:     if ($listing eq 'unknown_cmd') {
11663:         if ($getpropath) {
11664:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
11665:         }
11666:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
11667:     }
11668:     return $listing;
11669: }
11670: 
11671: sub is_locked {
11672:     my ($file_name, $domain, $user, $which) = @_;
11673:     my @check;
11674:     my $is_locked;
11675:     push (@check,$file_name);
11676:     my %locked = &get('file_permissions',\@check,
11677: 		      $env{'user.domain'},$env{'user.name'});
11678:     my ($tmp)=keys(%locked);
11679:     if ($tmp=~/^error:/) { undef(%locked); }
11680:     
11681:     if (ref($locked{$file_name}) eq 'ARRAY') {
11682:         $is_locked = 'false';
11683:         foreach my $entry (@{$locked{$file_name}}) {
11684:            if (ref($entry) eq 'ARRAY') {
11685:                $is_locked = 'true';
11686:                if (ref($which) eq 'ARRAY') {
11687:                    push(@{$which},$entry);
11688:                } else {
11689:                    last;
11690:                }
11691:            }
11692:        }
11693:     } else {
11694:         $is_locked = 'false';
11695:     }
11696:     return $is_locked;
11697: }
11698: 
11699: sub declutter_portfile {
11700:     my ($file) = @_;
11701:     $file =~ s{^(/portfolio/|portfolio/)}{/};
11702:     return $file;
11703: }
11704: 
11705: # ------------------------------------------------------------- Mark as Read Only
11706: 
11707: sub mark_as_readonly {
11708:     my ($domain,$user,$files,$what) = @_;
11709:     my %current_permissions = &dump('file_permissions',$domain,$user);
11710:     my ($tmp)=keys(%current_permissions);
11711:     if ($tmp=~/^error:/) { undef(%current_permissions); }
11712:     foreach my $file (@{$files}) {
11713: 	$file = &declutter_portfile($file);
11714:         push(@{$current_permissions{$file}},$what);
11715:     }
11716:     &put('file_permissions',\%current_permissions,$domain,$user);
11717:     return;
11718: }
11719: 
11720: # ------------------------------------------------------------Save Selected Files
11721: 
11722: sub save_selected_files {
11723:     my ($user, $path, @files) = @_;
11724:     my $filename = $user."savedfiles";
11725:     my @other_files = &files_not_in_path($user, $path);
11726:     open (OUT,'>',LONCAPA::tempdir().$filename);
11727:     foreach my $file (@files) {
11728:         print (OUT $env{'form.currentpath'}.$file."\n");
11729:     }
11730:     foreach my $file (@other_files) {
11731:         print (OUT $file."\n");
11732:     }
11733:     close (OUT);
11734:     return 'ok';
11735: }
11736: 
11737: sub clear_selected_files {
11738:     my ($user) = @_;
11739:     my $filename = $user."savedfiles";
11740:     open (OUT,'>',LONCAPA::tempdir().$filename);
11741:     print (OUT undef);
11742:     close (OUT);
11743:     return ("ok");    
11744: }
11745: 
11746: sub files_in_path {
11747:     my ($user, $path) = @_;
11748:     my $filename = $user."savedfiles";
11749:     my %return_files;
11750:     open (IN,'<',LONCAPA::tempdir().$filename);
11751:     while (my $line_in = <IN>) {
11752:         chomp ($line_in);
11753:         my @paths_and_file = split (m!/!, $line_in);
11754:         my $file_part = pop (@paths_and_file);
11755:         my $path_part = join ('/', @paths_and_file);
11756:         $path_part.='/';
11757:         my $path_and_file = $path_part.$file_part;
11758:         if ($path_part eq $path) {
11759:             $return_files{$file_part}= 'selected';
11760:         }
11761:     }
11762:     close (IN);
11763:     return (\%return_files);
11764: }
11765: 
11766: # called in portfolio select mode, to show files selected NOT in current directory
11767: sub files_not_in_path {
11768:     my ($user, $path) = @_;
11769:     my $filename = $user."savedfiles";
11770:     my @return_files;
11771:     my $path_part;
11772:     open(IN, '<',LONCAPA::tempdir().$filename);
11773:     while (my $line = <IN>) {
11774:         #ok, I know it's clunky, but I want it to work
11775:         my @paths_and_file = split(m|/|, $line);
11776:         my $file_part = pop(@paths_and_file);
11777:         chomp($file_part);
11778:         my $path_part = join('/', @paths_and_file);
11779:         $path_part .= '/';
11780:         my $path_and_file = $path_part.$file_part;
11781:         if ($path_part ne $path) {
11782:             push(@return_files, ($path_and_file));
11783:         }
11784:     }
11785:     close(OUT);
11786:     return (@return_files);
11787: }
11788: 
11789: #------------------------------Submitted/Handedback Portfolio Files Versioning
11790:  
11791: sub portfiles_versioning {
11792:     my ($symb,$domain,$stu_name,$portfiles,$versioned_portfiles) = @_;
11793:     my $portfolio_root = '/userfiles/portfolio';
11794:     return unless ((ref($portfiles) eq 'ARRAY') && (ref($versioned_portfiles) eq 'ARRAY'));
11795:     foreach my $file (@{$portfiles}) {
11796:         &unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
11797:         my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
11798:         my ($answer_name,$answer_ver,$answer_ext) = &file_name_version_ext($answer_file);
11799:         my $getpropath = 1;
11800:         my ($dir_list,$listerror) = &dirlist($portfolio_root.$directory,$domain,
11801:                                              $stu_name,$getpropath);
11802:         my $version = &get_next_version($answer_name,$answer_ext,$dir_list);
11803:         my $new_answer = 
11804:             &version_selected_portfile($domain,$stu_name,$directory,$answer_file,$version);
11805:         if ($new_answer ne 'problem getting file') {
11806:             push(@{$versioned_portfiles}, $directory.$new_answer);
11807:             &mark_as_readonly($domain,$stu_name,[$directory.$new_answer],
11808:                               [$symb,$env{'request.course.id'},'graded']);
11809:         }
11810:     }
11811: }
11812: 
11813: sub get_next_version {
11814:     my ($answer_name, $answer_ext, $dir_list) = @_;
11815:     my $version;
11816:     if (ref($dir_list) eq 'ARRAY') {
11817:         foreach my $row (@{$dir_list}) {
11818:             my ($file) = split(/\&/,$row,2);
11819:             my ($file_name,$file_version,$file_ext) =
11820:                 &file_name_version_ext($file);
11821:             if (($file_name eq $answer_name) &&
11822:                 ($file_ext eq $answer_ext)) {
11823:                      # gets here if filename and extension match,
11824:                      # regardless of version
11825:                 if ($file_version ne '') {
11826:                     # a versioned file is found  so save it for later
11827:                     if ($file_version > $version) {
11828:                         $version = $file_version;
11829:                     }
11830:                 }
11831:             }
11832:         }
11833:     }
11834:     $version ++;
11835:     return($version);
11836: }
11837: 
11838: sub version_selected_portfile {
11839:     my ($domain,$stu_name,$directory,$file_name,$version) = @_;
11840:     my ($answer_name,$answer_ver,$answer_ext) =
11841:         &file_name_version_ext($file_name);
11842:     my $new_answer;
11843:     $env{'form.copy'} =
11844:         &getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
11845:     if($env{'form.copy'} eq '-1') {
11846:         $new_answer = 'problem getting file';
11847:     } else {
11848:         $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
11849:         my $copy_result = 
11850:             &finishuserfileupload($stu_name,$domain,'copy',
11851:                                   '/portfolio'.$directory.$new_answer);
11852:     }
11853:     undef($env{'form.copy'});
11854:     return ($new_answer);
11855: }
11856: 
11857: sub file_name_version_ext {
11858:     my ($file)=@_;
11859:     my @file_parts = split(/\./, $file);
11860:     my ($name,$version,$ext);
11861:     if (@file_parts > 1) {
11862:         $ext=pop(@file_parts);
11863:         if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
11864:             $version=pop(@file_parts);
11865:         }
11866:         $name=join('.',@file_parts);
11867:     } else {
11868:         $name=join('.',@file_parts);
11869:     }
11870:     return($name,$version,$ext);
11871: }
11872: 
11873: #----------------------------------------------Get portfolio file permissions
11874: 
11875: sub get_portfile_permissions {
11876:     my ($domain,$user) = @_;
11877:     my %current_permissions = &dump('file_permissions',$domain,$user);
11878:     my ($tmp)=keys(%current_permissions);
11879:     if ($tmp=~/^error:/) { undef(%current_permissions); }
11880:     return \%current_permissions;
11881: }
11882: 
11883: #---------------------------------------------Get portfolio file access controls
11884: 
11885: sub get_access_controls {
11886:     my ($current_permissions,$group,$file) = @_;
11887:     my %access;
11888:     my $real_file = $file;
11889:     $file =~ s/\.meta$//;
11890:     if (defined($file)) {
11891:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
11892:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
11893:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
11894:             }
11895:         }
11896:     } else {
11897:         foreach my $key (keys(%{$current_permissions})) {
11898:             if ($key =~ /\0accesscontrol$/) {
11899:                 if (defined($group)) {
11900:                     if ($key !~ m-^\Q$group\E/-) {
11901:                         next;
11902:                     }
11903:                 }
11904:                 my ($fullpath) = split(/\0/,$key);
11905:                 if (ref($$current_permissions{$key}) eq 'HASH') {
11906:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
11907:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
11908:                     }
11909:                 }
11910:             }
11911:         }
11912:     }
11913:     return %access;
11914: }
11915: 
11916: sub modify_access_controls {
11917:     my ($file_name,$changes,$domain,$user)=@_;
11918:     my ($outcome,$deloutcome);
11919:     my %store_permissions;
11920:     my %new_values;
11921:     my %new_control;
11922:     my %translation;
11923:     my @deletions = ();
11924:     my $now = time;
11925:     if (exists($$changes{'activate'})) {
11926:         if (ref($$changes{'activate'}) eq 'HASH') {
11927:             my @newitems = sort(keys(%{$$changes{'activate'}}));
11928:             my $numnew = scalar(@newitems);
11929:             for (my $i=0; $i<$numnew; $i++) {
11930:                 my $newkey = $newitems[$i];
11931:                 my $newid = &Apache::loncommon::get_cgi_id();
11932:                 if ($newkey =~ /^\d+:/) { 
11933:                     $newkey =~ s/^(\d+)/$newid/;
11934:                     $translation{$1} = $newid;
11935:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
11936:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
11937:                     $translation{$1} = $newid;
11938:                 }
11939:                 $new_values{$file_name."\0".$newkey} = 
11940:                                           $$changes{'activate'}{$newitems[$i]};
11941:                 $new_control{$newkey} = $now;
11942:             }
11943:         }
11944:     }
11945:     my %todelete;
11946:     my %changed_items;
11947:     foreach my $action ('delete','update') {
11948:         if (exists($$changes{$action})) {
11949:             if (ref($$changes{$action}) eq 'HASH') {
11950:                 foreach my $key (keys(%{$$changes{$action}})) {
11951:                     my ($itemnum) = ($key =~ /^([^:]+):/);
11952:                     if ($action eq 'delete') { 
11953:                         $todelete{$itemnum} = 1;
11954:                     } else {
11955:                         $changed_items{$itemnum} = $key;
11956:                     }
11957:                 }
11958:             }
11959:         }
11960:     }
11961:     # get lock on access controls for file.
11962:     my $lockhash = {
11963:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
11964:                                                        ':'.$env{'user.domain'},
11965:                    }; 
11966:     my $tries = 0;
11967:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
11968:    
11969:     while (($gotlock ne 'ok') && $tries < 10) {
11970:         $tries ++;
11971:         sleep(0.1);
11972:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
11973:     }
11974:     if ($gotlock eq 'ok') {
11975:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
11976:         my ($tmp)=keys(%curr_permissions);
11977:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
11978:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
11979:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
11980:             if (ref($curr_controls) eq 'HASH') {
11981:                 foreach my $control_item (keys(%{$curr_controls})) {
11982:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
11983:                     if (defined($todelete{$itemnum})) {
11984:                         push(@deletions,$file_name."\0".$control_item);
11985:                     } else {
11986:                         if (defined($changed_items{$itemnum})) {
11987:                             $new_control{$changed_items{$itemnum}} = $now;
11988:                             push(@deletions,$file_name."\0".$control_item);
11989:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
11990:                         } else {
11991:                             $new_control{$control_item} = $$curr_controls{$control_item};
11992:                         }
11993:                     }
11994:                 }
11995:             }
11996:         }
11997:         my ($group);
11998:         if (&is_course($domain,$user)) {
11999:             ($group,my $file) = split(/\//,$file_name,2);
12000:         }
12001:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
12002:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
12003:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
12004:         #  remove lock
12005:         my @del_lock = ($file_name."\0".'locked_access_records');
12006:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
12007:         my $sqlresult =
12008:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
12009:                                     $group);
12010:     } else {
12011:         $outcome = "error: could not obtain lockfile\n";  
12012:     }
12013:     return ($outcome,$deloutcome,\%new_values,\%translation);
12014: }
12015: 
12016: sub make_public_indefinitely {
12017:     my (@requrl) = @_;
12018:     return &automated_portfile_access('public',\@requrl);
12019: }
12020: 
12021: sub automated_portfile_access {
12022:     my ($accesstype,$addsref,$delsref,$info) = @_;
12023:     unless (($accesstype eq 'public') || ($accesstype eq 'ip')) {
12024:         return 'invalid';
12025:     }
12026:     my %urls;
12027:     if (ref($addsref) eq 'ARRAY') {
12028:         foreach my $requrl (@{$addsref}) {
12029:             if (&is_portfolio_url($requrl)) {
12030:                 unless (exists($urls{$requrl})) {
12031:                     $urls{$requrl} = 'add';
12032:                 }
12033:             }
12034:         }
12035:     }
12036:     if (ref($delsref) eq 'ARRAY') {
12037:         foreach my $requrl (@{$delsref}) { 
12038:             if (&is_portfolio_url($requrl)) {
12039:                 unless (exists($urls{$requrl})) {
12040:                     $urls{$requrl} = 'delete'; 
12041:                 }
12042:             }
12043:         }
12044:     }
12045:     unless (keys(%urls)) {
12046:         return 'invalid';
12047:     }
12048:     my $ip;
12049:     if ($accesstype eq 'ip') {
12050:         if (ref($info) eq 'HASH') {
12051:             if ($info->{'ip'} ne '') {
12052:                 $ip = $info->{'ip'};
12053:             }
12054:         }
12055:         if ($ip eq '') {
12056:             return 'invalid';
12057:         }
12058:     }
12059:     my $errors;
12060:     my $now = time;
12061:     my %current_perms;
12062:     foreach my $requrl (sort(keys(%urls))) {
12063:         my $action;
12064:         if ($urls{$requrl} eq 'add') {
12065:             $action = 'activate';
12066:         } else {
12067:             $action = 'none';
12068:         }
12069:         my $aclnum = 0;
12070:         my (undef,$udom,$unum,$file_name,$group) =
12071:             &parse_portfolio_url($requrl);
12072:         unless (exists($current_perms{$unum.':'.$udom})) {
12073:             $current_perms{$unum.':'.$udom} = &get_portfile_permissions($udom,$unum);
12074:         }
12075:         my %access_controls = &get_access_controls($current_perms{$unum.':'.$udom},
12076:                                                    $group,$file_name);
12077:         foreach my $key (keys(%{$access_controls{$file_name}})) {
12078:             my ($num,$scope,$end,$start) = 
12079:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
12080:             if ($scope eq $accesstype) {
12081:                 if (($start <= $now) && ($end == 0)) {
12082:                     if ($accesstype eq 'ip') {
12083:                         if (ref($access_controls{$file_name}{$key}) eq 'HASH') {
12084:                             if (ref($access_controls{$file_name}{$key}{'ip'}) eq 'ARRAY') {
12085:                                 if (grep(/^\Q$ip\E$/,@{$access_controls{$file_name}{$key}{'ip'}})) {
12086:                                     if ($urls{$requrl} eq 'add') {
12087:                                         $action = 'none';
12088:                                         last;
12089:                                     } else {
12090:                                         $action = 'delete';
12091:                                         $aclnum = $num;
12092:                                         last;
12093:                                     }
12094:                                 }
12095:                             }
12096:                         }
12097:                     } elsif ($accesstype eq 'public') {
12098:                         if ($urls{$requrl} eq 'add') {
12099:                             $action = 'none';
12100:                             last;
12101:                         } else {
12102:                             $action = 'delete';
12103:                             $aclnum = $num;
12104:                             last;
12105:                         }
12106:                     }
12107:                 } elsif ($accesstype eq 'public') {
12108:                     $action = 'update';
12109:                     $aclnum = $num;
12110:                     last;
12111:                 }
12112:             }
12113:         }
12114:         if ($action eq 'none') {
12115:             next;
12116:         } else {
12117:             my %changes;
12118:             my $newend = 0;
12119:             my $newstart = $now;
12120:             my $newkey = $aclnum.':'.$accesstype.'_'.$newend.'_'.$newstart;
12121:             $changes{$action}{$newkey} = {
12122:                 type => $accesstype,
12123:                 time => {
12124:                     start => $newstart,
12125:                     end   => $newend,
12126:                 },
12127:             };
12128:             if ($accesstype eq 'ip') {
12129:                 $changes{$action}{$newkey}{'ip'} = [$ip];
12130:             }
12131:             my ($outcome,$deloutcome,$new_values,$translation) =
12132:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
12133:             unless ($outcome eq 'ok') {
12134:                 $errors .= $outcome.' ';
12135:             }
12136:         }
12137:     }
12138:     if ($errors) {
12139:         $errors =~ s/\s$//;
12140:         return $errors;
12141:     } else {
12142:         return 'ok';
12143:     }
12144: }
12145: 
12146: #------------------------------------------------------Get Marked as Read Only
12147: 
12148: sub get_marked_as_readonly {
12149:     my ($domain,$user,$what,$group) = @_;
12150:     my $current_permissions = &get_portfile_permissions($domain,$user);
12151:     my @readonly_files;
12152:     my $cmp1=$what;
12153:     if (ref($what)) { $cmp1=join('',@{$what}) };
12154:     while (my ($file_name,$value) = each(%{$current_permissions})) {
12155:         if (defined($group)) {
12156:             if ($file_name !~ m-^\Q$group\E/-) {
12157:                 next;
12158:             }
12159:         }
12160:         if (ref($value) eq "ARRAY"){
12161:             foreach my $stored_what (@{$value}) {
12162:                 my $cmp2=$stored_what;
12163:                 if (ref($stored_what) eq 'ARRAY') {
12164:                     $cmp2=join('',@{$stored_what});
12165:                 }
12166:                 if ($cmp1 eq $cmp2) {
12167:                     push(@readonly_files, $file_name);
12168:                     last;
12169:                 } elsif (!defined($what)) {
12170:                     push(@readonly_files, $file_name);
12171:                     last;
12172:                 }
12173:             }
12174:         }
12175:     }
12176:     return @readonly_files;
12177: }
12178: #-----------------------------------------------------------Get Marked as Read Only Hash
12179: 
12180: sub get_marked_as_readonly_hash {
12181:     my ($current_permissions,$group,$what) = @_;
12182:     my %readonly_files;
12183:     while (my ($file_name,$value) = each(%{$current_permissions})) {
12184:         if (defined($group)) {
12185:             if ($file_name !~ m-^\Q$group\E/-) {
12186:                 next;
12187:             }
12188:         }
12189:         if (ref($value) eq "ARRAY"){
12190:             foreach my $stored_what (@{$value}) {
12191:                 if (ref($stored_what) eq 'ARRAY') {
12192:                     foreach my $lock_descriptor(@{$stored_what}) {
12193:                         if ($lock_descriptor eq 'graded') {
12194:                             $readonly_files{$file_name} = 'graded';
12195:                         } elsif ($lock_descriptor eq 'handback') {
12196:                             $readonly_files{$file_name} = 'handback';
12197:                         } else {
12198:                             if (!exists($readonly_files{$file_name})) {
12199:                                 $readonly_files{$file_name} = 'locked';
12200:                             }
12201:                         }
12202:                     }
12203:                 } 
12204:             }
12205:         } 
12206:     }
12207:     return %readonly_files;
12208: }
12209: # ------------------------------------------------------------ Unmark as Read Only
12210: 
12211: sub unmark_as_readonly {
12212:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
12213:     # for portfolio submissions, $what contains [$symb,$crsid] 
12214:     my ($domain,$user,$what,$file_name,$group) = @_;
12215:     $file_name = &declutter_portfile($file_name);
12216:     my $symb_crs = $what;
12217:     if (ref($what)) { $symb_crs=join('',@$what); }
12218:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
12219:     my ($tmp)=keys(%current_permissions);
12220:     if ($tmp=~/^error:/) { undef(%current_permissions); }
12221:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
12222:     foreach my $file (@readonly_files) {
12223: 	my $clean_file = &declutter_portfile($file);
12224: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
12225: 	my $current_locks = $current_permissions{$file};
12226:         my @new_locks;
12227:         my @del_keys;
12228:         if (ref($current_locks) eq "ARRAY"){
12229:             foreach my $locker (@{$current_locks}) {
12230:                 my $compare=$locker;
12231:                 if (ref($locker) eq 'ARRAY') {
12232:                     $compare=join('',@{$locker});
12233:                     if ($compare ne $symb_crs) {
12234:                         push(@new_locks, $locker);
12235:                     }
12236:                 }
12237:             }
12238:             if (scalar(@new_locks) > 0) {
12239:                 $current_permissions{$file} = \@new_locks;
12240:             } else {
12241:                 push(@del_keys, $file);
12242:                 &del('file_permissions',\@del_keys, $domain, $user);
12243:                 delete($current_permissions{$file});
12244:             }
12245:         }
12246:     }
12247:     &put('file_permissions',\%current_permissions,$domain,$user);
12248:     return;
12249: }
12250: 
12251: # ------------------------------------------------------------ Directory lister
12252: 
12253: sub dirlist {
12254:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
12255:     $uri=~s/^\///;
12256:     $uri=~s/\/$//;
12257:     my ($udom, $uname);
12258:     if ($getuserdir) {
12259:         $udom = $userdomain;
12260:         $uname = $username;
12261:     } else {
12262:         (undef,$udom,$uname)=split(/\//,$uri);
12263:         if(defined($userdomain)) {
12264:             $udom = $userdomain;
12265:         }
12266:         if(defined($username)) {
12267:             $uname = $username;
12268:         }
12269:     }
12270:     my ($dirRoot,$listing,@listing_results);
12271: 
12272:     $dirRoot = $perlvar{'lonDocRoot'};
12273:     if (defined($getpropath)) {
12274:         $dirRoot = &propath($udom,$uname);
12275:         $dirRoot =~ s/\/$//;
12276:     } elsif (defined($getuserdir)) {
12277:         my $subdir=$uname.'__';
12278:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
12279:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
12280:                    ."/$udom/$subdir/$uname";
12281:     } elsif (defined($alternateRoot)) {
12282:         $dirRoot = $alternateRoot;
12283:     }
12284: 
12285:     if($udom) {
12286:         if($uname) {
12287:             my $uhome = &homeserver($uname,$udom);
12288:             if ($uhome eq 'no_host') {
12289:                 return ([],'no_host');
12290:             }
12291:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
12292:                               .$getuserdir.':'.&escape($dirRoot)
12293:                               .':'.&escape($uname).':'.&escape($udom),$uhome);
12294:             if ($listing eq 'unknown_cmd') {
12295:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
12296:             } else {
12297:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
12298:             }
12299:             if ($listing eq 'unknown_cmd') {
12300:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
12301:                 @listing_results = split(/:/,$listing);
12302:             } else {
12303:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
12304:             }
12305:             if (($listing eq 'no_such_host') || ($listing eq 'con_lost') || 
12306:                 ($listing eq 'rejected') || ($listing eq 'refused') ||
12307:                 ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
12308:                 return ([],$listing);
12309:             } else {
12310:                 return (\@listing_results);
12311:             }
12312:         } elsif(!$alternateRoot) {
12313:             my (%allusers,%listerror);
12314: 	    my %servers = &get_servers($udom,'library');
12315:  	    foreach my $tryserver (keys(%servers)) {
12316:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
12317:                                   &escape($udom),$tryserver);
12318:                 if ($listing eq 'unknown_cmd') {
12319: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
12320: 				      $udom, $tryserver);
12321:                 } else {
12322:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
12323:                 }
12324: 		if ($listing eq 'unknown_cmd') {
12325: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
12326: 				      $udom, $tryserver);
12327: 		    @listing_results = split(/:/,$listing);
12328: 		} else {
12329: 		    @listing_results =
12330: 			map { &unescape($_); } split(/:/,$listing);
12331: 		}
12332:                 if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
12333:                     ($listing eq 'rejected') || ($listing eq 'refused') ||
12334:                     ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
12335:                     $listerror{$tryserver} = $listing;
12336:                 } else {
12337: 		    foreach my $line (@listing_results) {
12338: 			my ($entry) = split(/&/,$line,2);
12339: 			$allusers{$entry} = 1;
12340: 		    }
12341: 		}
12342:             }
12343:             my @alluserslist=();
12344:             foreach my $user (sort(keys(%allusers))) {
12345:                 push(@alluserslist,$user.'&user');
12346:             }
12347: 
12348:             if (!%listerror) {
12349:                 # no errors
12350:                 return (\@alluserslist);
12351:             } elsif (scalar(keys(%servers)) == 1) {
12352:                 # one library server, one error 
12353:                 my ($key) = keys(%listerror);
12354:                 return (\@alluserslist, $listerror{$key});
12355:             } elsif ( grep { $_ eq 'con_lost' } values(%listerror) ) {
12356:                 # con_lost indicates that we might miss data from at least one
12357:                 # library server
12358:                 return (\@alluserslist, 'con_lost');
12359:             } else {
12360:                 # multiple library servers and no con_lost -> data should be
12361:                 # complete. 
12362:                 return (\@alluserslist);
12363:             }
12364: 
12365:         } else {
12366:             return ([],'missing username');
12367:         }
12368:     } elsif(!defined($getpropath)) {
12369:         my $path = $perlvar{'lonDocRoot'}.'/res/'; 
12370:         my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
12371:         return (\@all_domains);
12372:     } else {
12373:         return ([],'missing domain');
12374:     }
12375: }
12376: 
12377: # --------------------------------------------- GetFileTimestamp
12378: # This function utilizes dirlist and returns the date stamp for
12379: # when it was last modified.  It will also return an error of -1
12380: # if an error occurs
12381: 
12382: sub GetFileTimestamp {
12383:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
12384:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
12385:     $studentName   = &LONCAPA::clean_username($studentName);
12386:     my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
12387:                                     undef,$getuserdir);
12388:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
12389:         return -1;
12390:     }
12391:     if (ref($fileref) eq 'ARRAY') {
12392:         my @stats = split('&',$fileref->[0]);
12393:         # @stats contains first the filename, then the stat output
12394:         return $stats[10]; # so this is 10 instead of 9.
12395:     } else {
12396:         return -1;
12397:     }
12398: }
12399: 
12400: sub stat_file {
12401:     my ($uri) = @_;
12402:     $uri = &clutter_with_no_wrapper($uri);
12403: 
12404:     my ($udom,$uname,$file);
12405:     if ($uri =~ m-^/(uploaded|editupload)/-) {
12406: 	($udom,$uname,$file) =
12407: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
12408: 	$file = 'userfiles/'.$file;
12409:     }
12410:     if ($uri =~ m-^/res/-) {
12411: 	($udom,$uname) = 
12412: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
12413: 	$file = $uri;
12414:     }
12415: 
12416:     if (!$udom || !$uname || !$file) {
12417: 	# unable to handle the uri
12418: 	return ();
12419:     }
12420:     my $getpropath;
12421:     if ($file =~ /^userfiles\//) {
12422:         $getpropath = 1;
12423:     }
12424:     my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
12425:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
12426:         return ();
12427:     } else {
12428:         if (ref($listref) eq 'ARRAY') {
12429:             my @stats = split('&',$listref->[0]);
12430: 	    shift(@stats); #filename is first
12431: 	    return @stats;
12432:         }
12433:     }
12434:     return ();
12435: }
12436: 
12437: # --------------------------------------------------------- recursedirs
12438: # Recursive function to traverse either a specific user's Authoring Space
12439: # or corresponding Published Resource Space, and populate the hash ref:
12440: # $dirhashref with URLs of all directories, and if $filehashref hash
12441: # ref arg is provided, the URLs of any files, excluding versioned, .meta,
12442: # or .rights files in resource space, and .meta, .save, .log, .bak and
12443: # .rights files in Authoring Space.
12444: #
12445: # Inputs:
12446: #
12447: # $is_home - true if current server is home server for user's space
12448: # $recurse - if true will also traverse subdirectories recursively
12449: # $include - reference to hash containing allowed file extensions.  If provided,
12450: #             files which do not have a matching extension will be ignored.
12451: # $exclude - reference to hash containing excluded file extensions.  If provided,
12452: #             files which have a matching extension will be ignored.
12453: # $nonemptydir - if true, will only populate $fileshashref hash entry for a particular
12454: #             directory with first file found (with acceptable extension).
12455: # $addtopdir - if true, set $dirhashref->{'/'} = 1 
12456: # $toppath - Top level directory (i.e., /res/$dom/$uname or /priv/$dom/$uname
12457: # $relpath - Current path (relative to top level).
12458: # $dirhashref - reference to hash to populate with URLs of directories (Required)
12459: # $filehashref - reference to hash to populate with URLs of files (Optional)
12460: #
12461: # Returns: nothing
12462: #
12463: # Side Effects: populates $dirhashref, and $filehashref (if provided).
12464: #
12465: # Currently used by interface/londocs.pm to create linked select boxes for
12466: # directory and filename to import a Course "Author" resource into a course, and
12467: # also to create linked select boxes for Authoring Space and Directory to choose
12468: # save location for creation of a new "standard" problem from the Course Editor.
12469: #
12470: 
12471: sub recursedirs {
12472:     my ($is_home,$recurse,$include,$exclude,$nonemptydir,$addtopdir,$toppath,$relpath,$dirhashref,$filehashref) = @_;
12473:     return unless (ref($dirhashref) eq 'HASH');
12474:     my $docroot = $perlvar{'lonDocRoot'};
12475:     my $currpath = $docroot.$toppath;
12476:     if ($relpath ne '') {
12477:         $currpath .= "/$relpath";
12478:     }
12479:     my ($savefile,$checkinc,$checkexc);
12480:     if (ref($filehashref)) {
12481:         $savefile = 1;
12482:     }
12483:     if (ref($include) eq 'HASH') {
12484:         $checkinc = 1;
12485:     }
12486:     if (ref($exclude) eq 'HASH') {
12487:         $checkexc = 1;
12488:     }
12489:     if ($is_home) {
12490:         if ((-e $currpath) && (opendir(my $dirh,$currpath))) {
12491:             my $filecount = 0;
12492:             foreach my $item (sort { lc($a) cmp lc($b) } grep(!/^\.+$/,readdir($dirh))) {
12493:                 next if ($item eq '');
12494:                 if (-d "$currpath/$item") {
12495:                     my $newpath;
12496:                     if ($relpath ne '') {
12497:                         $newpath = "$relpath/$item";
12498:                     } else {
12499:                         $newpath = $item;
12500:                     }
12501:                     $dirhashref->{&Apache::lonlocal::js_escape($newpath)} = 1;
12502:                     if ($recurse) {
12503:                         &recursedirs($is_home,$recurse,$include,$exclude,$nonemptydir,$addtopdir,$toppath,$newpath,$dirhashref,$filehashref);
12504:                     }
12505:                 } elsif (($savefile) || ($relpath eq '')) {
12506:                     next if ($nonemptydir && $filecount);
12507:                     if ($checkinc || $checkexc) {
12508:                         my ($extension) = ($item =~ /\.(\w+)$/);
12509:                         if ($checkinc) {
12510:                             next unless ($extension && $include->{$extension});
12511:                         }
12512:                         if ($checkexc) {
12513:                             next if ($extension && $exclude->{$extension});
12514:                         }
12515:                     }
12516:                     if (($relpath eq '') && (!exists($dirhashref->{'/'}))) {
12517:                         $dirhashref->{'/'} = 1;
12518:                     }
12519:                     if ($savefile) {
12520:                         if ($relpath eq '') {
12521:                             $filehashref->{'/'}{$item} = 1;
12522:                         } else {
12523:                             $filehashref->{&Apache::lonlocal::js_escape($relpath)}{$item} = 1;
12524:                         }
12525:                     }
12526:                     $filecount ++;
12527:                 }
12528:             }
12529:             closedir($dirh);
12530:         }
12531:     } else {
12532:         my ($dirlistref,$listerror) =
12533:             &dirlist($toppath.$relpath);
12534:         my @dir_lines;
12535:         my $dirptr=16384;
12536:         if (ref($dirlistref) eq 'ARRAY') {
12537:             my $filecount = 0;
12538:             foreach my $dir_line (sort
12539:                               {
12540:                                   my ($afile)=split('&',$a,2);
12541:                                   my ($bfile)=split('&',$b,2);
12542:                                   return (lc($afile) cmp lc($bfile));
12543:                               } (@{$dirlistref})) {
12544:                 my ($item,$dom,undef,$testdir,undef,undef,undef,undef,$size,undef,$mtime,undef,undef,undef,$obs,undef) =
12545:                     split(/\&/,$dir_line,16);
12546:                 $item =~ s/\s+$//;
12547:                 next if (($item =~ /^\.\.?$/) || ($obs));
12548:                 if ($dirptr&$testdir) {
12549:                     my $newpath;
12550:                     if ($relpath) {
12551:                         $newpath = "$relpath/$item";
12552:                     } else {
12553:                         $newpath = $item;
12554:                     }
12555:                     $dirhashref->{&Apache::lonlocal::js_escape($newpath)} = 1;
12556:                     if ($recurse) {
12557:                         &recursedirs($is_home,$recurse,$include,$exclude,$nonemptydir,$addtopdir,$toppath,$newpath,$dirhashref,$filehashref);
12558:                     }
12559:                 } elsif (($savefile) || ($relpath eq '')) {
12560:                     next if ($nonemptydir && $filecount);
12561:                     if ($checkinc || $checkexc) {
12562:                         my $extension;
12563:                         if ($checkinc) {
12564:                             next unless ($extension && $include->{$extension});
12565:                         }
12566:                         if ($checkexc) {
12567:                             next if ($extension && $exclude->{$extension});
12568:                         }
12569:                     }
12570:                     if (($relpath eq '') && (!exists($dirhashref->{'/'}))) {
12571:                         $dirhashref->{'/'} = 1;
12572:                     }
12573:                     if ($savefile) {
12574:                         if ($relpath eq '') {
12575:                             $filehashref->{'/'}{$item} = 1;
12576:                         } else {
12577:                             $filehashref->{&Apache::lonlocal::js_escape($relpath)}{$item} = 1;
12578:                         }
12579:                     }
12580:                     $filecount ++; 
12581:                 }
12582:             }
12583:         }
12584:     }
12585:     if ($addtopdir) {
12586:         if (($relpath eq '') && (!exists($dirhashref->{'/'}))) {
12587:             $dirhashref->{'/'} = 1;
12588:         }
12589:     }
12590:     return;
12591: }
12592: 
12593: sub priv_exclude {
12594:     return {
12595:              meta => 1,
12596:              save => 1,
12597:              log => 1,
12598:              bak => 1,
12599:              rights => 1,
12600:              DS_Store => 1,
12601:            };
12602: }
12603: 
12604: # -------------------------------------------------------- Value of a Condition
12605: 
12606: # gets the value of a specific preevaluated condition
12607: #    stored in the string  $env{user.state.<cid>}
12608: # or looks up a condition reference in the bighash and if if hasn't
12609: # already been evaluated recurses into docondval to get the value of
12610: # the condition, then memoizing it to 
12611: #   $env{user.state.<cid>.<condition>}
12612: sub directcondval {
12613:     my $number=shift;
12614:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
12615: 	&Apache::lonuserstate::evalstate();
12616:     }
12617:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
12618: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
12619:     } elsif ($number =~ /^_/) {
12620: 	my $sub_condition;
12621: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
12622: 		&GDBM_READER(),0640)) {
12623: 	    $sub_condition=$bighash{'conditions'.$number};
12624: 	    untie(%bighash);
12625: 	}
12626: 	my $value = &docondval($sub_condition);
12627: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
12628: 	return $value;
12629:     }
12630:     if ($env{'user.state.'.$env{'request.course.id'}}) {
12631:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
12632:     } else {
12633:        return 2;
12634:     }
12635: }
12636: 
12637: # get the collection of conditions for this resource
12638: sub condval {
12639:     my $condidx=shift;
12640:     my $allpathcond='';
12641:     foreach my $cond (split(/\|/,$condidx)) {
12642: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
12643: 	    $allpathcond.=
12644: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
12645: 	}
12646:     }
12647:     $allpathcond=~s/\|$//;
12648:     return &docondval($allpathcond);
12649: }
12650: 
12651: #evaluates an expression of conditions
12652: sub docondval {
12653:     my ($allpathcond) = @_;
12654:     my $result=0;
12655:     if ($env{'request.course.id'}
12656: 	&& defined($allpathcond)) {
12657: 	my $operand='|';
12658: 	my @stack;
12659: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
12660: 	    if ($chunk eq '(') {
12661: 		push @stack,($operand,$result);
12662: 	    } elsif ($chunk eq ')') {
12663: 		my $before=pop @stack;
12664: 		if (pop @stack eq '&') {
12665: 		    $result=$result>$before?$before:$result;
12666: 		} else {
12667: 		    $result=$result>$before?$result:$before;
12668: 		}
12669: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
12670: 		$operand=$chunk;
12671: 	    } else {
12672: 		my $new=directcondval($chunk);
12673: 		if ($operand eq '&') {
12674: 		    $result=$result>$new?$new:$result;
12675: 		} else {
12676: 		    $result=$result>$new?$result:$new;
12677: 		}
12678: 	    }
12679: 	}
12680:     }
12681:     return $result;
12682: }
12683: 
12684: # ---------------------------------------------------- Devalidate courseresdata
12685: 
12686: sub devalidatecourseresdata {
12687:     my ($coursenum,$coursedomain)=@_;
12688:     my $hashid=$coursenum.':'.$coursedomain;
12689:     &devalidate_cache_new('courseres',$hashid);
12690: }
12691: 
12692: 
12693: # --------------------------------------------------- Course Resourcedata Query
12694: #
12695: #  Parameters:
12696: #      $coursenum    - Number of the course.
12697: #      $coursedomain - Domain at which the course was created.
12698: #  Returns:
12699: #     A hash of the course parameters along (I think) with timestamps
12700: #     and version info.
12701: 
12702: sub get_courseresdata {
12703:     my ($coursenum,$coursedomain)=@_;
12704:     my $coursehom=&homeserver($coursenum,$coursedomain);
12705:     my $hashid=$coursenum.':'.$coursedomain;
12706:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
12707:     my %dumpreply;
12708:     unless (defined($cached)) {
12709: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
12710: 	$result=\%dumpreply;
12711: 	my ($tmp) = keys(%dumpreply);
12712: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
12713: 	    &do_cache_new('courseres',$hashid,$result,600);
12714: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
12715: 	    return $tmp;
12716: 	} elsif ($tmp =~ /^(error)/) {
12717: 	    $result=undef;
12718: 	    &do_cache_new('courseres',$hashid,$result,600);
12719: 	}
12720:     }
12721:     return $result;
12722: }
12723: 
12724: sub devalidateuserresdata {
12725:     my ($uname,$udom)=@_;
12726:     my $hashid="$udom:$uname";
12727:     &devalidate_cache_new('userres',$hashid);
12728: }
12729: 
12730: sub get_userresdata {
12731:     my ($uname,$udom)=@_;
12732:     #most student don\'t have any data set, check if there is some data
12733:     if (&EXT_cache_status($udom,$uname)) { return undef; }
12734: 
12735:     my $hashid="$udom:$uname";
12736:     my ($result,$cached)=&is_cached_new('userres',$hashid);
12737:     if (!defined($cached)) {
12738: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
12739: 	$result=\%resourcedata;
12740: 	&do_cache_new('userres',$hashid,$result,600);
12741:     }
12742:     my ($tmp)=keys(%$result);
12743:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
12744: 	return $result;
12745:     }
12746:     #error 2 occurs when the .db doesn't exist
12747:     if ($tmp!~/error: 2 /) {
12748:         if ((!defined($cached)) || ($tmp ne 'con_lost')) {
12749: 	    &logthis("<font color=\"blue\">WARNING:".
12750: 		     " Trying to get resource data for ".
12751: 		     $uname." at ".$udom.": ".
12752: 		     $tmp."</font>");
12753:         }
12754:     } elsif ($tmp=~/error: 2 /) {
12755: 	#&EXT_cache_set($udom,$uname);
12756: 	&do_cache_new('userres',$hashid,undef,600);
12757: 	undef($tmp); # not really an error so don't send it back
12758:     }
12759:     return $tmp;
12760: }
12761: #----------------------------------------------- resdata - return resource data
12762: #  Purpose:
12763: #    Return resource data for either users or for a course.
12764: #  Parameters:
12765: #     $name      - Course/user name.
12766: #     $domain    - Name of the domain the user/course is registered on.
12767: #     $type      - Type of thing $name is (must be 'course' or 'user')
12768: #     $mapp      - decluttered URL of enclosing map  
12769: #     $recursed  - Ref to scalar -- set to 1, if nested maps have been recursed.
12770: #     $recurseup - Ref to array of map URLs, starting with map containing
12771: #                  $mapp up through hierarchy of nested maps to top level map.  
12772: #     $courseid  - CourseID (first part of param identifier).
12773: #     $modifier  - Middle part of param identifier.
12774: #     $what      - Last part of param identifier.
12775: #     @which     - Array of names of resources desired.
12776: #  Returns:
12777: #     The value of the first reasource in @which that is found in the
12778: #     resource hash.
12779: #  Exceptional Conditions:
12780: #     If the $type passed in is not valid (not the string 'course' or 
12781: #     'user', an undefined  reference is returned.
12782: #     If none of the resources are found, an undef is returned
12783: sub resdata {
12784:     my ($name,$domain,$type,$mapp,$recursed,$recurseup,$courseid,
12785:         $modifier,$what,@which)=@_;
12786:     my $result;
12787:     if ($type eq 'course') {
12788: 	$result=&get_courseresdata($name,$domain);
12789:     } elsif ($type eq 'user') {
12790: 	$result=&get_userresdata($name,$domain);
12791:     }
12792:     if (!ref($result)) { return $result; }    
12793:     foreach my $item (@which) {
12794:         if ($item->[1] eq 'course') {
12795:             if ((ref($recurseup) eq 'ARRAY') && (ref($recursed) eq 'SCALAR')) {
12796:                 unless ($$recursed) {
12797:                     @{$recurseup} = &get_map_hierarchy($mapp,$courseid);
12798:                     $$recursed = 1;
12799:                 }
12800:                 foreach my $item (@${recurseup}) {
12801:                     my $norecursechk=$courseid.$modifier.$item.'___(all).'.$what;
12802:                     last if (defined($result->{$norecursechk}));
12803:                     my $recursechk=$courseid.$modifier.$item.'___(rec).'.$what;
12804:                     if (defined($result->{$recursechk})) { return [$result->{$recursechk},'map']; }
12805:                 }
12806:             }
12807:         }
12808:         if (defined($result->{$item->[0]})) {
12809: 	    return [$result->{$item->[0]},$item->[1]];
12810: 	}
12811:     }
12812:     return undef;
12813: }
12814: 
12815: sub get_domain_lti {
12816:     my ($cdom,$context) = @_;
12817:     my ($name,$cachename,%lti);
12818:     if ($context eq 'consumer') {
12819:         $name = 'ltitools';
12820:     } elsif ($context eq 'provider') {
12821:         $name = 'lti';
12822:     } elsif ($context eq 'linkprot') {
12823:         $name = 'ltisec';
12824:     } else {
12825:         return %lti;
12826:     }
12827:     if ($context eq 'linkprot') {
12828:         $cachename = $context;
12829:     } else {
12830:         $cachename = $name;
12831:     }
12832:     my ($result,$cached)=&is_cached_new($cachename,$cdom);
12833:     if (defined($cached)) {
12834:         if (ref($result) eq 'HASH') {
12835:             %lti = %{$result};
12836:         }
12837:     } else {
12838:         my %domconfig = &get_dom('configuration',[$name],$cdom);
12839:         if (ref($domconfig{$name}) eq 'HASH') {
12840:             if ($context eq 'linkprot') {
12841:                 if (ref($domconfig{$name}{'linkprot'}) eq 'HASH') {
12842:                     %lti = %{$domconfig{$name}{'linkprot'}};
12843:                 }
12844:             } else {
12845:                 %lti = %{$domconfig{$name}};
12846:             }
12847:         }
12848:         my $cachetime = 24*60*60;
12849:         &do_cache_new($cachename,$cdom,\%lti,$cachetime);
12850:     }
12851:     return %lti;
12852: }
12853: 
12854: sub get_course_lti {
12855:     my ($cnum,$cdom,$context) = @_;
12856:     my ($name,$cachename,%lti);
12857:     if ($context eq 'consumer') {
12858:         $name = 'ltitools';
12859:         $cachename = 'courseltitools';
12860:     } elsif ($context eq 'provider') {
12861:         $name = 'lti';
12862:         $cachename = 'courselti';
12863:     } else {
12864:         return %lti;
12865:     }
12866:     my $hashid=$cdom.'_'.$cnum;
12867:     my ($result,$cached)=&is_cached_new($cachename,$hashid);
12868:     if (defined($cached)) {
12869:         if (ref($result) eq 'HASH') {
12870:             %lti = %{$result};
12871:         }
12872:     } else {
12873:         %lti = &dump($name,$cdom,$cnum,undef,undef,undef,1);
12874:         my $cachetime = 24*60*60;
12875:         &do_cache_new($cachename,$hashid,\%lti,$cachetime);
12876:     }
12877:     return %lti;
12878: }
12879: 
12880: sub courselti_itemid {
12881:     my ($cnum,$cdom,$url,$method,$params,$context) = @_;
12882:     my ($chome,$itemid);
12883:     $chome = &homeserver($cnum,$cdom);
12884:     return if ($chome eq 'no_host');
12885:     if (ref($params) eq 'HASH') {
12886:         my $rep;
12887:         if (grep { $_ eq $chome } current_machine_ids()) {
12888:             $rep = LONCAPA::Lond::crslti_itemid($cdom,$cnum,$url,$method,$params,$perlvar{'lonVersion'});
12889:         } else {
12890:             my $escurl = &escape($url);
12891:             my $escmethod = &escape($method);
12892:             my $items = &freeze_escape($params);
12893:             $rep = &reply("encrypt:lti:$cdom:$cnum:$context:$escurl:$escmethod:$items",$chome);
12894:         }
12895:         unless (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
12896:                 ($rep eq 'unknown_cmd')) {
12897:             $itemid = $rep;
12898:         }
12899:     }
12900:     return $itemid;
12901: }
12902: 
12903: sub domainlti_itemid {
12904:     my ($cdom,$url,$method,$params,$context) = @_;
12905:     my ($primary_id,$itemid);
12906:     $primary_id = &domain($cdom,'primary');
12907:     return if ($primary_id eq '');
12908:     if (ref($params) eq 'HASH') {
12909:         my $rep;
12910:         if (grep { $_ eq $primary_id } current_machine_ids()) {
12911:             $rep = LONCAPA::Lond::domlti_itemid($cdom,$context,$url,$method,$params,$perlvar{'lonVersion'});
12912:         } else {
12913:             my $cnum = '';
12914:             my $escurl = &escape($url);
12915:             my $escmethod = &escape($method);
12916:             my $items = &freeze_escape($params);
12917:             $rep = &reply("encrypt:lti:$cdom:$cnum:$context:$escurl:$escmethod:$items",$primary_id);
12918:         }
12919:         unless (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
12920:                 ($rep eq 'unknown_cmd')) {
12921:             $itemid = $rep;
12922:         }
12923:     }
12924:     return $itemid;
12925: }
12926: 
12927: sub get_ltitools_id {
12928:     my ($context,$cdom,$cnum,$title) = @_;
12929:     my ($lockhash,$tries,$gotlock,$id,$error);
12930: 
12931:     # get lock on ltitools db
12932:     $lockhash = {
12933:                    lock => $env{'user.name'}.
12934:                            ':'.$env{'user.domain'},
12935:                 };
12936:     $tries = 0;
12937:     if ($context eq 'domain') {
12938:         $gotlock = &newput_dom('ltitools',$lockhash,$cdom);
12939:     } else {
12940:         $gotlock = &newput('ltitools',$lockhash,$cdom,$cnum);
12941:     }
12942:     while (($gotlock ne 'ok') && ($tries<10)) {
12943:         $tries ++;
12944:         sleep (0.1);
12945:         if ($context eq 'domain') {
12946:             $gotlock = &newput_dom('ltitools',$lockhash,$cdom);
12947:         } else {
12948:             $gotlock = &newput('ltitools',$lockhash,$cdom,$cnum);
12949:         }
12950:     }
12951:     if ($gotlock eq 'ok') {
12952:         my %currids;
12953:         if ($context eq 'domain') {
12954:             %currids = &dump_dom('ltitools',$cdom);
12955:         } else {
12956:             %currids = &dump('ltitools',$cdom,$cnum);
12957:         }
12958:         if ($currids{'lock'}) {
12959:             delete($currids{'lock'});
12960:             if (keys(%currids)) {
12961:                 my @curr = sort { $a <=> $b } keys(%currids);
12962:                 if ($curr[-1] =~ /^\d+$/) {
12963:                     $id = 1 + $curr[-1];
12964:                 }
12965:             } else {
12966:                 $id = 1;
12967:             }
12968:             if ($id) {
12969:                 if ($context eq 'domain') {
12970:                     unless (&newput_dom('ltitools',{ $id => $title },$cdom) eq 'ok') {
12971:                         $error = 'nostore';
12972:                     }
12973:                 } else {
12974:                     unless (&newput('ltitools',{ $id => $title },$cdom,$cnum) eq 'ok') {
12975:                         $error = 'nostore';
12976:                     }
12977:                 }
12978:             } else {
12979:                 $error = 'nonumber';
12980:             }
12981:         }
12982:         my $dellockoutcome;
12983:         if ($context eq 'domain') {
12984:             $dellockoutcome = &del_dom('ltitools',['lock'],$cdom);
12985:         } else {
12986:             $dellockoutcome = &del('ltitools',['lock'],$cdom,$cnum);
12987:         }
12988:     } else {
12989:         $error = 'nolock';
12990:     }
12991:     return ($id,$error);
12992: }
12993: 
12994: sub count_supptools {
12995:     my ($cnum,$cdom,$ignorecache,$reload)=@_;
12996:     my $hashid=$cnum.':'.$cdom;
12997:     my ($numexttools,$cached);
12998:     unless ($ignorecache) {
12999:         ($numexttools,$cached) = &is_cached_new('supptools',$hashid);
13000:     }
13001:     unless (defined($cached)) {
13002:         my $chome=&homeserver($cnum,$cdom);
13003:         $numexttools = 0;
13004:         unless ($chome eq 'no_host') {
13005:             my ($supplemental) = &Apache::loncommon::get_supplemental($cnum,$cdom,$reload);
13006:             if (ref($supplemental) eq 'HASH') {
13007:                 if ((ref($supplemental->{'ids'}) eq 'HASH') && (ref($supplemental->{'hidden'}) eq 'HASH')) {
13008:                     foreach my $key (keys(%{$supplemental->{'ids'}})) {
13009:                         if ($key =~ m{^/adm/$cdom/$cnum/\d+/ext\.tool$}) {
13010:                             $numexttools ++;
13011:                         }
13012:                     }
13013:                 }
13014:             }
13015:         }
13016:         &do_cache_new('supptools',$hashid,$numexttools,600);
13017:     }
13018:     return $numexttools;
13019: }
13020: 
13021: sub has_unhidden_suppfiles {
13022:     my ($cnum,$cdom,$ignorecache,$possdel)=@_;
13023:     my $hashid=$cnum.':'.$cdom;
13024:     my ($showsupp,$cached);
13025:     unless ($ignorecache) {
13026:         ($showsupp,$cached) = &is_cached_new('showsupp',$hashid);
13027:     }
13028:     unless (defined($cached)) {
13029:         my $chome=&homeserver($cnum,$cdom);
13030:         unless ($chome eq 'no_host') {
13031:             my ($supplemental) = &Apache::loncommon::get_supplemental($cnum,$cdom,$ignorecache,$possdel);
13032:             if (ref($supplemental) eq 'HASH') {
13033:                 if ((ref($supplemental->{'ids'}) eq 'HASH') && (ref($supplemental->{'hidden'}) eq 'HASH')) {
13034:                     foreach my $key (keys(%{$supplemental->{'ids'}})) {
13035:                         next if ($key =~ /\.sequence$/);
13036:                         if (ref($supplemental->{'ids'}->{$key}) eq 'ARRAY') {
13037:                             foreach my $id (@{$supplemental->{'ids'}->{$key}}) {
13038:                                 unless ($supplemental->{'hidden'}->{$id}) {
13039:                                     $showsupp = 1;
13040:                                     last;
13041:                                 }
13042:                             }
13043:                         }
13044:                         last if ($showsupp);
13045:                     }
13046:                 }
13047:             }
13048:         }
13049:         &do_cache_new('showsupp',$hashid,$showsupp,600);
13050:     }
13051:     return $showsupp;
13052: }
13053: 
13054: #
13055: # EXT resource caching routines
13056: #
13057: 
13058: {
13059: # Cache (5 seconds) of map hierarchy for speedup of navmaps display
13060: #
13061: # The course for which we cache
13062: my $cachedmapkey='';
13063: # The cached recursive maps for this course
13064: my %cachedmaps=();
13065: # When this was last done
13066: my $cachedmaptime='';
13067: 
13068: sub clear_EXT_cache_status {
13069:     &delenv('cache.EXT.');
13070: }
13071: 
13072: sub EXT_cache_status {
13073:     my ($target_domain,$target_user) = @_;
13074:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
13075:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
13076:         # We know already the user has no data
13077:         return 1;
13078:     } else {
13079:         return 0;
13080:     }
13081: }
13082: 
13083: sub EXT_cache_set {
13084:     my ($target_domain,$target_user) = @_;
13085:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
13086:     #&appenv({$cachename => time});
13087: }
13088: 
13089: # --------------------------------------------------------- Value of a Variable
13090: sub EXT {
13091: 
13092:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse,$cid,$recurseupref)=@_;
13093:     unless ($varname) { return ''; }
13094:     #get real user name/domain, courseid and symb
13095:     my $courseid;
13096:     my $publicuser;
13097:     if ($symbparm) {
13098: 	$symbparm=&get_symb_from_alias($symbparm);
13099:     }
13100:     if (!($uname && $udom)) {
13101:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
13102:       if (!$symbparm) {	$symbparm=$cursymb; }
13103:     } else {
13104: 	$courseid=$env{'request.course.id'};
13105:     }
13106:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
13107:     my $rest;
13108:     if (defined($therest[0])) {
13109:        $rest=join('.',@therest);
13110:     } else {
13111:        $rest='';
13112:     }
13113: 
13114:     my $qualifierrest=$qualifier;
13115:     if ($rest) { $qualifierrest.='.'.$rest; }
13116:     my $spacequalifierrest=$space;
13117:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
13118:     if ($realm eq 'user') {
13119: # --------------------------------------------------------------- user.resource
13120: 	if ($space eq 'resource') {
13121: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
13122: 		  || defined($Apache::lonhomework::parsing_a_task))
13123: 		 &&
13124: 		 ($symbparm eq &symbread()) ) {
13125: 		# if we are in the middle of processing the resource the
13126: 		# get the value we are planning on committing
13127:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
13128:                     return $Apache::lonhomework::results{$qualifierrest};
13129:                 } else {
13130:                     return $Apache::lonhomework::history{$qualifierrest};
13131:                 }
13132: 	    } else {
13133: 		my %restored;
13134: 		if ($publicuser || $env{'request.state'} eq 'construct') {
13135: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
13136: 		} else {
13137: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
13138: 		}
13139: 		return $restored{$qualifierrest};
13140: 	    }
13141: # ----------------------------------------------------------------- user.access
13142:         } elsif ($space eq 'access') {
13143: 	    # FIXME - not supporting calls for a specific user
13144:             return &allowed($qualifier,$rest);
13145: # ------------------------------------------ user.preferences, user.environment
13146:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
13147: 	    if (($uname eq $env{'user.name'}) &&
13148: 		($udom eq $env{'user.domain'})) {
13149: 		return $env{join('.',('environment',$qualifierrest))};
13150: 	    } else {
13151: 		my %returnhash;
13152: 		if (!$publicuser) {
13153: 		    %returnhash=&userenvironment($udom,$uname,
13154: 						 $qualifierrest);
13155: 		}
13156: 		return $returnhash{$qualifierrest};
13157: 	    }
13158: # ----------------------------------------------------------------- user.course
13159:         } elsif ($space eq 'course') {
13160: 	    # FIXME - not supporting calls for a specific user
13161:             return $env{join('.',('request.course',$qualifier))};
13162: # ------------------------------------------------------------------- user.role
13163:         } elsif ($space eq 'role') {
13164: 	    # FIXME - not supporting calls for a specific user
13165:             my ($role,$where)=split(/\./,$env{'request.role'});
13166:             if ($qualifier eq 'value') {
13167: 		return $role;
13168:             } elsif ($qualifier eq 'extent') {
13169:                 return $where;
13170:             }
13171: # ----------------------------------------------------------------- user.domain
13172:         } elsif ($space eq 'domain') {
13173:             return $udom;
13174: # ------------------------------------------------------------------- user.name
13175:         } elsif ($space eq 'name') {
13176:             return $uname;
13177: # ---------------------------------------------------- Any other user namespace
13178:         } else {
13179: 	    my %reply;
13180: 	    if (!$publicuser) {
13181: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
13182: 	    }
13183: 	    return $reply{$qualifierrest};
13184:         }
13185:     } elsif ($realm eq 'query') {
13186: # ---------------------------------------------- pull stuff out of query string
13187:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
13188: 						[$spacequalifierrest]);
13189: 	return $env{'form.'.$spacequalifierrest}; 
13190:    } elsif ($realm eq 'request') {
13191: # ------------------------------------------------------------- request.browser
13192:         if ($space eq 'browser') {
13193:             return $env{'browser.'.$qualifier};
13194: # ------------------------------------------------------------ request.filename
13195:         } else {
13196:             return $env{'request.'.$spacequalifierrest};
13197:         }
13198:     } elsif ($realm eq 'course') {
13199: # ---------------------------------------------------------- course.description
13200:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
13201:     } elsif ($realm eq 'resource') {
13202: 
13203: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
13204: 	    if (!$symbparm) { $symbparm=&symbread(); }
13205: 	}
13206: 
13207:         if ($qualifier eq '') {
13208: 	    if ($space eq 'title') {
13209: 	        if (!$symbparm) { $symbparm = $env{'request.filename'}; }
13210: 	        return &gettitle($symbparm);
13211: 	    }
13212: 	
13213: 	    if ($space eq 'map') {
13214: 	        my ($map) = &decode_symb($symbparm);
13215: 	        return &symbread($map);
13216: 	    }
13217:             if ($space eq 'maptitle') {
13218:                 my ($map) = &decode_symb($symbparm);
13219:                 return &gettitle($map);
13220:             }
13221: 	    if ($space eq 'filename') {
13222: 	        if ($symbparm) {
13223: 		    return &clutter((&decode_symb($symbparm))[2]);
13224: 	        }
13225: 	        return &hreflocation('',$env{'request.filename'});
13226: 	    }
13227: 
13228:             if ((defined($courseid)) && ($courseid eq $env{'request.course.id'}) && $symbparm) {
13229:                 if ($space eq 'visibleparts') {
13230:                     my $navmap = Apache::lonnavmaps::navmap->new();
13231:                     my $item;
13232:                     if (ref($navmap)) {
13233:                         my $res = $navmap->getBySymb($symbparm);
13234:                         my $parts = $res->parts();
13235:                         if (ref($parts) eq 'ARRAY') {
13236:                             $item = join(',',@{$parts});
13237:                         }
13238:                         undef($navmap);
13239:                     }
13240:                     return $item;
13241:                 }
13242:             }
13243:         }
13244: 
13245: 	my ($section, $group, @groups, @recurseup, $recursed);
13246:         if (ref($recurseupref) eq 'ARRAY') {
13247:             @recurseup = @{$recurseupref};
13248:             $recursed = 1;
13249:         }
13250: 	my ($courselevelm,$courseleveli,$courselevel,$mapp);
13251:         if (($courseid eq '') && ($cid)) {
13252:             $courseid = $cid;
13253:         }
13254: 	if (($symbparm && $courseid) && 
13255: 	    (($courseid eq $env{'request.course.id'}) || ($courseid eq $cid)))  {
13256: 
13257: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
13258: 
13259: # ----------------------------------------------------- Cascading lookup scheme
13260: 	    my $symbp=$symbparm;
13261: 	    $mapp=&deversion((&decode_symb($symbp))[0]);
13262: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
13263:             my $recurseparm=$mapp.'___(rec).'.$spacequalifierrest;
13264: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
13265: 	    if (($env{'user.name'} eq $uname) &&
13266: 		($env{'user.domain'} eq $udom)) {
13267: 		$section=$env{'request.course.sec'};
13268:                 @groups = split(/:/,$env{'request.course.groups'});  
13269:                 @groups=&sort_course_groups($courseid,@groups); 
13270: 	    } else {
13271: 		if (! defined($usection)) {
13272: 		    $section=&getsection($udom,$uname,$courseid);
13273: 		} else {
13274: 		    $section = $usection;
13275: 		}
13276:                 @groups = &get_users_groups($udom,$uname,$courseid);
13277: 	    }
13278: 
13279: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
13280: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
13281:             my $secleveli=$courseid.'.['.$section.'].'.$recurseparm;
13282: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
13283: 
13284: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
13285: 	    my $courselevelr=$courseid.'.'.$symbparm;
13286:             $courseleveli=$courseid.'.'.$recurseparm;
13287: 	    $courselevelm=$courseid.'.'.$mapparm;
13288: 
13289: # ----------------------------------------------------------- first, check user
13290: 
13291: 	    my $userreply=&resdata($uname,$udom,'user',$mapp,\$recursed,
13292:                                    \@recurseup,$courseid,'.',$spacequalifierrest, 
13293: 				       ([$courselevelr,'resource'],
13294: 					[$courselevelm,'map'     ],
13295:                                         [$courseleveli,'map'     ],
13296: 					[$courselevel, 'course'  ]));
13297: 	    if (defined($userreply)) { return &get_reply($userreply); }
13298: 
13299: # ------------------------------------------------ second, check some of course
13300:             my $coursereply;
13301:             if (@groups > 0) {
13302:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
13303:                                        $recurseparm,$mapparm,$spacequalifierrest,
13304:                                        $mapp,\$recursed,\@recurseup);
13305:                 if (defined($coursereply)) { return &get_reply($coursereply); } 
13306:             }
13307: 
13308: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
13309: 				  $env{'course.'.$courseid.'.domain'},
13310: 				  'course',$mapp,\$recursed,\@recurseup,
13311:                                   $courseid,'.['.$section.'].',$spacequalifierrest,
13312: 				  ([$seclevelr,   'resource'],
13313: 				   [$seclevelm,   'map'     ],
13314:                                    [$secleveli,   'map'     ],
13315: 				   [$seclevel,    'course'  ],
13316: 				   [$courselevelr,'resource']));
13317: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
13318: 
13319: # ------------------------------------------------------ third, check map parms
13320: 	    my %parmhash=();
13321: 	    my $thisparm='';
13322: 	    if (tie(%parmhash,'GDBM_File',
13323: 		    $env{'request.course.fn'}.'_parms.db',
13324: 		    &GDBM_READER(),0640)) {
13325: 		$thisparm=$parmhash{$symbparm};
13326: 		untie(%parmhash);
13327: 	    }
13328: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
13329: 	}
13330: # ------------------------------------------ fourth, look in resource metadata
13331:  
13332:         my $what = $spacequalifierrest;
13333: 	$what=~s/\./\_/;
13334: 	my $filename;
13335: 	if (!$symbparm) { $symbparm=&symbread(); }
13336: 	if ($symbparm) {
13337: 	    $filename=(&decode_symb($symbparm))[2];
13338: 	} else {
13339: 	    $filename=$env{'request.filename'};
13340: 	}
13341:         my $toolsymb;
13342:         if (($filename =~ /ext\.tool$/) && ($what ne '0_gradable')) {
13343:             $toolsymb = $symbparm;
13344:         }
13345: 	my $metadata=&metadata($filename,$what,$toolsymb);
13346: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
13347: 	$metadata=&metadata($filename,'parameter_'.$what,$toolsymb);
13348: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
13349: 
13350: # ----------------------------------------------- fifth, look in rest of course
13351: 	if ($symbparm && defined($courseid) && 
13352: 	    $courseid eq $env{'request.course.id'}) {
13353: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
13354: 				     $env{'course.'.$courseid.'.domain'},
13355: 				     'course',$mapp,\$recursed,\@recurseup,
13356:                                      $courseid,'.',$spacequalifierrest,
13357: 				     ([$courselevelm,'map'   ],
13358:                                       [$courseleveli,'map'   ],
13359: 				      [$courselevel, 'course']));
13360: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
13361: 	}
13362: # ------------------------------------------------------------------ Cascade up
13363: 	unless ($space eq '0') {
13364: 	    my @parts=split(/_/,$space);
13365: 	    my $id=pop(@parts);
13366: 	    my $part=join('_',@parts);
13367: 	    if ($part eq '') { $part='0'; }
13368: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
13369: 				 $symbparm,$udom,$uname,$section,1);
13370: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
13371: 	}
13372: 	if ($recurse) { return undef; }
13373: 	my $pack_def=&packages_tab_default($filename,$varname,$toolsymb);
13374: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
13375: # ---------------------------------------------------- Any other user namespace
13376:     } elsif ($realm eq 'environment') {
13377: # ----------------------------------------------------------------- environment
13378: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
13379: 	    return $env{'environment.'.$spacequalifierrest};
13380: 	} else {
13381: 	    if ($uname eq 'anonymous' && $udom eq '') {
13382: 		return '';
13383: 	    }
13384: 	    my %returnhash=&userenvironment($udom,$uname,
13385: 					    $spacequalifierrest);
13386: 	    return $returnhash{$spacequalifierrest};
13387: 	}
13388:     } elsif ($realm eq 'system') {
13389: # ----------------------------------------------------------------- system.time
13390: 	if ($space eq 'time') {
13391: 	    return time;
13392:         }
13393:     } elsif ($realm eq 'server') {
13394: # ----------------------------------------------------------------- system.time
13395: 	if ($space eq 'name') {
13396: 	    return $ENV{'SERVER_NAME'};
13397:         }
13398:     } elsif ($realm eq 'client') {
13399:         if ($space eq 'remote_addr') {
13400:             return &get_requestor_ip();
13401:         }
13402:     }
13403:     return '';
13404: }
13405: 
13406: sub get_reply {
13407:     my ($reply_value) = @_;
13408:     if (ref($reply_value) eq 'ARRAY') {
13409:         if (wantarray) {
13410: 	    return @$reply_value;
13411:         }
13412:         return $reply_value->[0];
13413:     } else {
13414:         return $reply_value;
13415:     }
13416: }
13417: 
13418: sub check_group_parms {
13419:     my ($courseid,$groups,$symbparm,$recurseparm,$mapparm,$what,$mapp,
13420:         $recursed,$recurseupref) = @_;
13421:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$recurseparm,'map'],
13422:                   [$what,'course']);
13423:     my $coursereply;
13424:     foreach my $group (@{$groups}) {
13425:         my @groupitems = ();
13426:         foreach my $level (@levels) {
13427:              my $item = $courseid.'.['.$group.'].'.$level->[0];
13428:              push(@groupitems,[$item,$level->[1]]);
13429:         }
13430:         my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
13431:                                    $env{'course.'.$courseid.'.domain'},
13432:                                    'course',$mapp,$recursed,$recurseupref,
13433:                                    $courseid,'.['.$group.'].',$what,
13434:                                    @groupitems);
13435:         last if (defined($coursereply));
13436:     }
13437:     return $coursereply;
13438: }
13439: 
13440: sub get_map_hierarchy {
13441:     my ($mapname,$courseid) = @_;
13442:     my @recurseup = ();
13443:     if ($mapname) {
13444:         if (($cachedmapkey eq $courseid) &&
13445:             (abs($cachedmaptime-time)<5)) {
13446:             if (ref($cachedmaps{$mapname}) eq 'ARRAY') {
13447:                 return @{$cachedmaps{$mapname}};
13448:             }
13449:         }
13450:         my $navmap = Apache::lonnavmaps::navmap->new();
13451:         if (ref($navmap)) {
13452:             @recurseup = $navmap->recurseup_maps($mapname);
13453:             undef($navmap);
13454:             $cachedmaps{$mapname} = \@recurseup;
13455:             $cachedmaptime=time;
13456:             $cachedmapkey=$courseid;
13457:         }
13458:     }
13459:     return @recurseup;
13460: }
13461: 
13462: }
13463: 
13464: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
13465:     my ($courseid,@groups) = @_;
13466:     @groups = sort(@groups);
13467:     return @groups;
13468: }
13469: 
13470: sub packages_tab_default {
13471:     my ($uri,$varname,$toolsymb)=@_;
13472:     my (undef,$part,$name)=split(/\./,$varname);
13473: 
13474:     my (@extension,@specifics,$do_default);
13475:     foreach my $package (split(/,/,&metadata($uri,'packages',$toolsymb))) {
13476: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
13477: 	if ($pack_type eq 'default') {
13478: 	    $do_default=1;
13479: 	} elsif ($pack_type eq 'extension') {
13480: 	    push(@extension,[$package,$pack_type,$pack_part]);
13481: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
13482: 	    # only look at packages defaults for packages that this id is
13483: 	    push(@specifics,[$package,$pack_type,$pack_part]);
13484: 	}
13485:     }
13486:     # first look for a package that matches the requested part id
13487:     foreach my $package (@specifics) {
13488: 	my (undef,$pack_type,$pack_part)=@{$package};
13489: 	next if ($pack_part ne $part);
13490: 	if (defined($packagetab{"$pack_type&$name&default"})) {
13491: 	    return $packagetab{"$pack_type&$name&default"};
13492: 	}
13493:     }
13494:     # look for any possible matching non extension_ package
13495:     foreach my $package (@specifics) {
13496: 	my (undef,$pack_type,$pack_part)=@{$package};
13497: 	if (defined($packagetab{"$pack_type&$name&default"})) {
13498: 	    return $packagetab{"$pack_type&$name&default"};
13499: 	}
13500: 	if ($pack_type eq 'part') { $pack_part='0'; }
13501: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
13502: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
13503: 	}
13504:     }
13505:     # look for any posible extension_ match
13506:     foreach my $package (@extension) {
13507: 	my ($package,$pack_type)=@{$package};
13508: 	if (defined($packagetab{"$pack_type&$name&default"})) {
13509: 	    return $packagetab{"$pack_type&$name&default"};
13510: 	}
13511: 	if (defined($packagetab{$package."&$name&default"})) {
13512: 	    return $packagetab{$package."&$name&default"};
13513: 	}
13514:     }
13515:     # look for a global default setting
13516:     if ($do_default && defined($packagetab{"default&$name&default"})) {
13517: 	return $packagetab{"default&$name&default"};
13518:     }
13519:     return undef;
13520: }
13521: 
13522: sub add_prefix_and_part {
13523:     my ($prefix,$part)=@_;
13524:     my $keyroot;
13525:     if (defined($prefix) && $prefix !~ /^__/) {
13526: 	# prefix that has a part already
13527: 	$keyroot=$prefix;
13528:     } elsif (defined($prefix)) {
13529: 	# prefix that is missing a part
13530: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
13531:     } else {
13532: 	# no prefix at all
13533: 	if (defined($part)) { $keyroot='_'.$part; }
13534:     }
13535:     return $keyroot;
13536: }
13537: 
13538: # ---------------------------------------------------------------- Get metadata
13539: 
13540: my %metaentry;
13541: my %importedpartids;
13542: my %importedrespids;
13543: sub metadata {
13544:     my ($uri,$what,$toolsymb,$liburi,$prefix,$depthcount)=@_;
13545:     $uri=&declutter($uri);
13546:     # if it is a non metadata possible uri return quickly
13547:     if (($uri eq '') || 
13548: 	(($uri =~ m|^/*adm/|) && 
13549: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard|ext\.tool)$})) ||
13550:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
13551: 	return undef;
13552:     }
13553:     if (($uri =~ /^priv/ || $uri=~m{^home/httpd/html/priv}) 
13554: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
13555: 	return undef;
13556:     }
13557:     my $filename=$uri;
13558:     $uri=~s/\.meta$//;
13559: #
13560: # Is the metadata already cached?
13561: # Look at timestamp of caching
13562: # Everything is cached by the main uri, libraries are never directly cached
13563: #
13564:     if (!defined($liburi)) {
13565: 	my ($result,$cached)=&is_cached_new('meta',$uri);
13566: 	if (defined($cached)) { return $result->{':'.$what}; }
13567:     }
13568: 
13569: #
13570: # If the uri is for an external tool the file from
13571: # which metadata should be retrieved depends on whether
13572: # the tool had been configured to be gradable (set in the Course
13573: # Editor or Resource Editor).
13574: #
13575: # If a valid symb has been included as the third arg in the call
13576: # to &metadata() that can be used to retrieve the value of
13577: # parameter_0_gradable set for the resource, and included in the
13578: # uploaded map containing the tool. The value is retrieved via
13579: # &EXT(), if a valid symb is available.  Otherwise the value of
13580: # gradable in the exttool_$marker.db file for the tool instance
13581: # is retrieved via &get().
13582: #
13583: # When lonuserstate::traceroute() calls lonnet::EXT() for 
13584: # hiddenresource and encrypturl (during course initialization)
13585: # the map-level parameter for resource.0.gradable included in the 
13586: # uploaded map containing the tool will not yet have been stored
13587: # in the user_course_parms.db file for the user's session, so in 
13588: # this case fall back to retrieving gradable status from the
13589: # exttool_$marker.db file.
13590: #
13591: # In order to avoid an infinite loop, &metadata() will return
13592: # before a call to &EXT(), if the uri is for an external tool
13593: # and the $what for which metadata is being requested is
13594: # parameter_0_gradable or 0_gradable.
13595: #
13596: 
13597:     if ($uri =~ /ext\.tool$/) {
13598:         if (($what eq 'parameter_0_gradable') || ($what eq '0_gradable')) {
13599:             return;
13600:         } else {
13601:             my ($checked,$use_passback);
13602:             if ($toolsymb ne '') {
13603:                 (undef,undef,my $tooluri) = &decode_symb($toolsymb);
13604:                 if (($tooluri eq $uri) && (&EXT('resource.0.gradable',$toolsymb))) {
13605:                     $checked = 1;
13606:                     if (&EXT('resource.0.gradable',$toolsymb) =~ /^yes$/i) {
13607:                         $use_passback = 1;
13608:                     }
13609:                 }
13610:             }
13611:             unless ($checked) {
13612:                 my ($ignore,$cdom,$cnum,$marker) = split(m{/},$uri);
13613:                 $marker=~s/\D//g;
13614:                 if ($marker) {
13615:                     my %toolsettings=&get('exttool_'.$marker,['gradable'],$cdom,$cnum);
13616:                     $use_passback = $toolsettings{'gradable'};
13617:                 }
13618:             }
13619:             if ($use_passback) {
13620:                 $filename = '/home/httpd/html/res/lib/templates/LTIpassback.tool';
13621:             } else {
13622:                 $filename = '/home/httpd/html/res/lib/templates/LTIstandard.tool';
13623:             }
13624:         }
13625:     }
13626: 
13627:     {
13628: # Imported parts would go here
13629:         my @origfiletagids=();
13630:         my $importedparts=0;
13631: 
13632: # Imported responseids would go here
13633:         my $importedresponses=0;
13634: #
13635: # Is this a recursive call for a library?
13636: #
13637: #	if (! exists($metacache{$uri})) {
13638: #	    $metacache{$uri}={};
13639: #	}
13640: 	my $cachetime = 60*60;
13641:         if ($liburi) {
13642: 	    $liburi=&declutter($liburi);
13643:             $filename=$liburi;
13644:         } else {
13645: 	    &devalidate_cache_new('meta',$uri);
13646: 	    undef(%metaentry);
13647: 	}
13648:         my %metathesekeys=();
13649:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
13650: 	my $metastring;
13651: 	if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
13652: 	    my $which = &hreflocation('','/'.($liburi || $uri));
13653: 	    $metastring = 
13654: 		&Apache::lonnet::ssi_body($which,
13655: 					  ('grade_target' => 'meta'));
13656: 	    $cachetime = 1; # only want this cached in the child not long term
13657: 	} elsif (($uri !~ m -^(editupload)/-) && 
13658:                  ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
13659: 	    my $file=&filelocation('',&clutter($filename));
13660: 	    #push(@{$metaentry{$uri.'.file'}},$file);
13661: 	    $metastring=&getfile($file);
13662: 	}
13663:         my $parser=HTML::LCParser->new(\$metastring);
13664:         my $token;
13665:         undef %metathesekeys;
13666:         while ($token=$parser->get_token) {
13667: 	    if ($token->[0] eq 'S') {
13668: 		if (defined($token->[2]->{'package'})) {
13669: #
13670: # This is a package - get package info
13671: #
13672: 		    my $package=$token->[2]->{'package'};
13673: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
13674: 		    if (defined($token->[2]->{'id'})) { 
13675: 			$keyroot.='_'.$token->[2]->{'id'}; 
13676: 		    }
13677: 		    if ($metaentry{':packages'}) {
13678: 			$metaentry{':packages'}.=','.$package.$keyroot;
13679: 		    } else {
13680: 			$metaentry{':packages'}=$package.$keyroot;
13681: 		    }
13682: 		    foreach my $pack_entry (keys(%packagetab)) {
13683: 			my $part=$keyroot;
13684: 			$part=~s/^\_//;
13685: 			if ($pack_entry=~/^\Q$package\E\&/ || 
13686: 			    $pack_entry=~/^\Q$package\E_0\&/) {
13687: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
13688: 			    # ignore package.tab specified default values
13689:                             # here &package_tab_default() will fetch those
13690: 			    if ($subp eq 'default') { next; }
13691: 			    my $value=$packagetab{$pack_entry};
13692: 			    my $unikey;
13693: 			    if ($pack =~ /_0$/) {
13694: 				$unikey='parameter_0_'.$name;
13695: 				$part=0;
13696: 			    } else {
13697: 				$unikey='parameter'.$keyroot.'_'.$name;
13698: 			    }
13699: 			    if ($subp eq 'display') {
13700: 				$value.=' [Part: '.$part.']';
13701: 			    }
13702: 			    $metaentry{':'.$unikey.'.part'}=$part;
13703: 			    $metathesekeys{$unikey}=1;
13704: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
13705: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
13706: 			    }
13707: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
13708: 				$metaentry{':'.$unikey}=
13709: 				    $metaentry{':'.$unikey.'.default'};
13710: 			    }
13711: 			}
13712: 		    }
13713: 		} else {
13714: #
13715: # This is not a package - some other kind of start tag
13716: #
13717: 		    my $entry=$token->[1];
13718: 		    my $unikey='';
13719: 
13720: 		    if ($entry eq 'import') {
13721: #
13722: # Importing a library here
13723: #
13724:                         my $location=$parser->get_text('/import');
13725:                         my $dir=$filename;
13726:                         $dir=~s|[^/]*$||;
13727:                         $location=&filelocation($dir,$location);
13728: 
13729:                         my $importid=$token->[2]->{'id'};
13730:                         my $importmode=$token->[2]->{'importmode'};
13731: #
13732: # Check metadata for imported file to
13733: # see if it contained response items
13734: #
13735:                         my ($origfile,@libfilekeys);
13736:                         my %currmetaentry = %metaentry;
13737:                         @libfilekeys = split(/,/,&metadata($location,'keys',undef,undef,undef,
13738:                                                            $depthcount+1));
13739:                         if (grep(/^responseorder$/,@libfilekeys)) {
13740:                             my $libresponseorder = &metadata($location,'responseorder',undef,undef,
13741:                                                              undef,$depthcount+1);
13742:                             if ($libresponseorder ne '') {
13743:                                 if ($#origfiletagids<0) {
13744:                                     undef(%importedrespids);
13745:                                     undef(%importedpartids);
13746:                                 }
13747:                                 my @respids = split(/\s*,\s*/,$libresponseorder);
13748:                                 if (@respids) {
13749:                                     $importedrespids{$importid} = join(',',map { $importid.'_'.$_ } @respids);
13750:                                 }
13751:                                 if ($importedrespids{$importid} ne '') {
13752:                                     $importedresponses = 1;
13753: # We need to get the original file and the imported file to get the response order correct
13754: # Load and inspect original file
13755:                                     if ($#origfiletagids<0) {
13756:                                         my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
13757:                                         $origfile=&getfile($origfilelocation);
13758:                                         @origfiletagids=($origfile=~/<((?:\w+)response|import|part)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
13759:                                     }
13760:                                 }
13761:                             }
13762:                         }
13763: # Do not overwrite contents of %metaentry hash for resource itself with 
13764: # hash populated for imported library file
13765:                         %metaentry = %currmetaentry;
13766:                         undef(%currmetaentry);
13767:                         if ($importmode eq 'part') {
13768: # Import as part(s)
13769:                            $importedparts=1;
13770: # We need to get the original file and the imported file to get the part order correct
13771: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
13772: # Load and inspect original file if we didn't do that already
13773:                            if ($#origfiletagids<0) {
13774:                                undef(%importedrespids);
13775:                                undef(%importedpartids);
13776:                                if ($origfile eq '') {
13777:                                    my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
13778:                                    $origfile=&getfile($origfilelocation);
13779:                                    @origfiletagids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
13780:                                }
13781:                            }
13782:                            my @impfilepartids;
13783: # If <partorder> tag is included in metadata for the imported file
13784: # get the parts in the imported file from that.
13785:                            if (grep(/^partorder$/,@libfilekeys)) {
13786:                                %currmetaentry = %metaentry;
13787:                                my $libpartorder = &metadata($location,'partorder',undef,undef,undef,
13788:                                                             $depthcount+1);
13789:                                %metaentry = %currmetaentry;
13790:                                undef(%currmetaentry);
13791:                                if ($libpartorder ne '') {
13792:                                    @impfilepartids=split(/\s*,\s*/,$libpartorder);
13793:                                }
13794:                            } else {
13795: # If no <partorder> tag available, load and inspect imported file
13796:                                my $impfile=&getfile($location);
13797:                                @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
13798:                            }
13799:                            if ($#impfilepartids>=0) {
13800: # This problem had parts
13801:                                $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
13802:                            } else {
13803: # Importing by turning a single problem into a problem part
13804: # It gets the import-tags ID as part-ID
13805:                                $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
13806:                                $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
13807:                            }
13808:                         } else {
13809: # Import as problem or as normal import
13810:                             $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
13811:                             unless ($importmode eq 'problem') {
13812: # Normal import
13813:                                 if (defined($token->[2]->{'id'})) {
13814:                                     $unikey.='_'.$token->[2]->{'id'};
13815:                                 }
13816:                             }
13817: # Check metadata for imported file to
13818: # see if it contained parts
13819:                             if (grep(/^partorder$/,@libfilekeys)) {
13820:                                 %currmetaentry = %metaentry;
13821:                                 my $libpartorder = &metadata($location,'partorder',undef,undef,undef,
13822:                                                              $depthcount+1);
13823:                                 %metaentry = %currmetaentry;
13824:                                 undef(%currmetaentry);
13825:                                 if ($libpartorder ne '') {
13826:                                     $importedparts = 1;
13827:                                     $importedpartids{$token->[2]->{'id'}}=$libpartorder;
13828:                                 }
13829:                             }
13830:                         }
13831: 			if ($depthcount<20) {
13832: 			    my $metadata = 
13833: 				&metadata($uri,'keys',$toolsymb,$location,$unikey,
13834: 					  $depthcount+1);
13835: 			    foreach my $meta (split(',',$metadata)) {
13836: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
13837: 				$metathesekeys{$meta}=1;
13838: 			    }
13839:                         }
13840: 		    } else {
13841: #
13842: # Not importing, some other kind of non-package, non-library start tag
13843: # 
13844:                         $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
13845:                         if (defined($token->[2]->{'id'})) {
13846:                             $unikey.='_'.$token->[2]->{'id'};
13847:                         }
13848: 			if (defined($token->[2]->{'name'})) { 
13849: 			    $unikey.='_'.$token->[2]->{'name'}; 
13850: 			}
13851: 			$metathesekeys{$unikey}=1;
13852: 			foreach my $param (@{$token->[3]}) {
13853: 			    $metaentry{':'.$unikey.'.'.$param} =
13854: 				$token->[2]->{$param};
13855: 			}
13856: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
13857: 			my $default=$metaentry{':'.$unikey.'.default'};
13858: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
13859: 		 # only ws inside the tag, and not in default, so use default
13860: 		 # as value
13861: 			    $metaentry{':'.$unikey}=$default;
13862: 			} elsif ( $internaltext =~ /\S/ ) {
13863: 		  # something interesting inside the tag
13864: 			    $metaentry{':'.$unikey}=$internaltext;
13865: 			} else {
13866: 		  # no interesting values, don't set a default
13867: 			}
13868: # end of not-a-package not-a-library import
13869: 		    }
13870: # end of not-a-package start tag
13871: 		}
13872: # the next is the end of "start tag"
13873: 	    }
13874: 	}
13875: 	my ($extension) = ($uri =~ /\.(\w+)$/);
13876: 	$extension = lc($extension);
13877: 	if ($extension eq 'htm') { $extension='html'; }
13878: 
13879: 	foreach my $key (keys(%packagetab)) {
13880: 	    #no specific packages #how's our extension
13881: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
13882: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
13883: 					 \%metathesekeys);
13884: 	}
13885: 
13886: 	if (!exists($metaentry{':packages'})
13887: 	    || $packagetab{"import_defaults&extension_$extension"}) {
13888: 	    foreach my $key (keys(%packagetab)) {
13889: 		#no specific packages well let's get default then
13890: 		if ($key!~/^default&/) { next; }
13891: 		&metadata_create_package_def($uri,$key,'default',
13892: 					     \%metathesekeys);
13893: 	    }
13894: 	}
13895: # are there custom rights to evaluate
13896: 	if ($metaentry{':copyright'} eq 'custom') {
13897: 
13898:     #
13899:     # Importing a rights file here
13900:     #
13901: 	    unless ($depthcount) {
13902: 		my $location=$metaentry{':customdistributionfile'};
13903: 		my $dir=$filename;
13904: 		$dir=~s|[^/]*$||;
13905: 		$location=&filelocation($dir,$location);
13906: 		my $rights_metadata =
13907: 		    &metadata($uri,'keys',$toolsymb,$location,'_rights',
13908: 			      $depthcount+1);
13909: 		foreach my $rights (split(',',$rights_metadata)) {
13910: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
13911: 		    $metathesekeys{$rights}=1;
13912: 		}
13913: 	    }
13914: 	}
13915: 	# uniqifiy package listing
13916: 	my %seen;
13917: 	my @uniq_packages =
13918: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
13919: 	$metaentry{':packages'} = join(',',@uniq_packages);
13920: 
13921:         if (($importedresponses) || ($importedparts)) {
13922:             if ($importedparts) {
13923: # We had imported parts and need to rebuild partorder
13924:                 $metaentry{':partorder'}='';
13925:                 $metathesekeys{'partorder'}=1;
13926:             }
13927:             if ($importedresponses) {
13928: # We had imported responses and need to rebuil responseorder
13929:                 $metaentry{':responseorder'}='';
13930:                 $metathesekeys{'responseorder'}=1;
13931:             }
13932:             for (my $index=0;$index<$#origfiletagids;$index+=2) {
13933:                 my $origid = $origfiletagids[$index+1];
13934:                 if ($origfiletagids[$index] eq 'part') {
13935: # Original part, part of the problem
13936:                     if ($importedparts) {
13937:                         $metaentry{':partorder'}.=','.$origid;
13938:                     }
13939:                 } elsif ($origfiletagids[$index] eq 'import') {
13940:                     if ($importedparts) {
13941: # We have imported parts at this position
13942:                         if ($importedpartids{$origid} ne '') {
13943:                             $metaentry{':partorder'}.=','.$importedpartids{$origid};
13944:                         }
13945:                     }
13946:                     if ($importedresponses) {
13947: # We have imported responses at this position
13948:                         if ($importedrespids{$origid} ne '') {
13949:                             $metaentry{':responseorder'}.=','.$importedrespids{$origid};
13950:                         }
13951:                     }
13952:                 } else {
13953: # Original response item, part of the problem
13954:                     if ($importedresponses) {
13955:                         $metaentry{':responseorder'}.=','.$origid;
13956:                     }
13957:                 }
13958:             }
13959:             if ($importedparts) {
13960:                 $metaentry{':partorder'}=~s/^\,//;
13961:             }
13962:             if ($importedresponses) {
13963:                 $metaentry{':responseorder'}=~s/^\,//;
13964:             }
13965:         }
13966: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
13967: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
13968: 	$metaentry{':allpossiblekeys'}=join(',',keys(%metathesekeys));
13969:         unless ($liburi) {
13970: 	    &do_cache_new('meta',$uri,\%metaentry,$cachetime);
13971:         }
13972: # this is the end of "was not already recently cached
13973:     }
13974:     return $metaentry{':'.$what};
13975: }
13976: 
13977: sub metadata_create_package_def {
13978:     my ($uri,$key,$package,$metathesekeys)=@_;
13979:     my ($pack,$name,$subp)=split(/\&/,$key);
13980:     if ($subp eq 'default') { next; }
13981:     
13982:     if (defined($metaentry{':packages'})) {
13983: 	$metaentry{':packages'}.=','.$package;
13984:     } else {
13985: 	$metaentry{':packages'}=$package;
13986:     }
13987:     my $value=$packagetab{$key};
13988:     my $unikey;
13989:     $unikey='parameter_0_'.$name;
13990:     $metaentry{':'.$unikey.'.part'}=0;
13991:     $$metathesekeys{$unikey}=1;
13992:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
13993: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
13994:     }
13995:     if (defined($metaentry{':'.$unikey.'.default'})) {
13996: 	$metaentry{':'.$unikey}=
13997: 	    $metaentry{':'.$unikey.'.default'};
13998:     }
13999: }
14000: 
14001: sub metadata_generate_part0 {
14002:     my ($metadata,$metacache,$uri) = @_;
14003:     my %allnames;
14004:     foreach my $metakey (keys(%$metadata)) {
14005: 	if ($metakey=~/^parameter\_(.*)/) {
14006: 	  my $part=$$metacache{':'.$metakey.'.part'};
14007: 	  my $name=$$metacache{':'.$metakey.'.name'};
14008: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
14009: 	    $allnames{$name}=$part;
14010: 	  }
14011: 	}
14012:     }
14013:     foreach my $name (keys(%allnames)) {
14014:       $$metadata{"parameter_0_$name"}=1;
14015:       my $key=":parameter_0_$name";
14016:       $$metacache{"$key.part"}='0';
14017:       $$metacache{"$key.name"}=$name;
14018:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
14019: 					   $allnames{$name}.'_'.$name.
14020: 					   '.type'};
14021:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
14022: 			     '.display'};
14023:       my $expr='[Part: '.$allnames{$name}.']';
14024:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
14025:       $$metacache{"$key.display"}=$olddis;
14026:     }
14027: }
14028: 
14029: # ------------------------------------------------------ Devalidate title cache
14030: 
14031: sub devalidate_title_cache {
14032:     my ($url)=@_;
14033:     if (!$env{'request.course.id'}) { return; }
14034:     my $symb=&symbread($url);
14035:     if (!$symb) { return; }
14036:     my $key=$env{'request.course.id'}."\0".$symb;
14037:     &devalidate_cache_new('title',$key);
14038: }
14039: 
14040: # ------------------------------------------------- Get the title of a course
14041: 
14042: sub current_course_title {
14043:     return $env{ 'course.' . $env{'request.course.id'} . '.description' };
14044: }
14045: # ------------------------------------------------- Get the title of a resource
14046: 
14047: sub gettitle {
14048:     my $urlsymb=shift;
14049:     my $symb=&symbread($urlsymb);
14050:     if ($symb) {
14051: 	my $key=$env{'request.course.id'}."\0".$symb;
14052: 	my ($result,$cached)=&is_cached_new('title',$key);
14053: 	if (defined($cached)) { 
14054: 	    return $result;
14055: 	}
14056: 	my ($map,$resid,$url)=&decode_symb($symb);
14057: 	my $title='';
14058: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
14059: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
14060: 	} else {
14061: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
14062: 		    &GDBM_READER(),0640)) {
14063: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
14064: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
14065: 		untie(%bighash);
14066: 	    }
14067: 	}
14068: 	$title=~s/\&colon\;/\:/gs;
14069: 	if ($title) {
14070: # Remember both $symb and $title for dynamic metadata
14071:             $accesshash{$symb.'___crstitle'}=$title;
14072:             $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
14073: # Cache this title and then return it
14074: 	    return &do_cache_new('title',$key,$title,600);
14075: 	}
14076: 	$urlsymb=$url;
14077:     }
14078:     my $title=&metadata($urlsymb,'title');
14079:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
14080:     return $title;
14081: }
14082: 
14083: sub get_slot {
14084:     my ($which,$cnum,$cdom)=@_;
14085:     if (!$cnum || !$cdom) {
14086: 	(undef,my $courseid)=&whichuser();
14087: 	$cdom=$env{'course.'.$courseid.'.domain'};
14088: 	$cnum=$env{'course.'.$courseid.'.num'};
14089:     }
14090:     my $key=join("\0",'slots',$cdom,$cnum,$which);
14091:     my %slotinfo;
14092:     if (exists($remembered{$key})) {
14093: 	$slotinfo{$which} = $remembered{$key};
14094:     } else {
14095: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
14096: 	&Apache::lonhomework::showhash(%slotinfo);
14097: 	my ($tmp)=keys(%slotinfo);
14098: 	if ($tmp=~/^error:/) { return (); }
14099: 	$remembered{$key} = $slotinfo{$which};
14100:     }
14101:     if (ref($slotinfo{$which}) eq 'HASH') {
14102: 	return %{$slotinfo{$which}};
14103:     }
14104:     return $slotinfo{$which};
14105: }
14106: 
14107: sub get_reservable_slots {
14108:     my ($cnum,$cdom,$uname,$udom) = @_;
14109:     my $now = time;
14110:     my $reservable_info;
14111:     my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
14112:     if (exists($remembered{$key})) {
14113:         $reservable_info = $remembered{$key};
14114:     } else {
14115:         my %resv;
14116:         ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
14117:         &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
14118:         $reservable_info = \%resv;
14119:         $remembered{$key} = $reservable_info;
14120:     }
14121:     return $reservable_info;
14122: }
14123: 
14124: sub get_course_slots {
14125:     my ($cnum,$cdom) = @_;
14126:     my $hashid=$cnum.':'.$cdom;
14127:     my ($result,$cached) = &is_cached_new('allslots',$hashid);
14128:     if (defined($cached)) {
14129:         if (ref($result) eq 'HASH') {
14130:             return %{$result};
14131:         }
14132:     } else {
14133:         my %slots=&dump('slots',$cdom,$cnum);
14134:         my ($tmp) = keys(%slots);
14135:         if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
14136:             &do_cache_new('allslots',$hashid,\%slots,600);
14137:             return %slots;
14138:         }
14139:     }
14140:     return;
14141: }
14142: 
14143: sub devalidate_slots_cache {
14144:     my ($cnum,$cdom)=@_;
14145:     my $hashid=$cnum.':'.$cdom;
14146:     &devalidate_cache_new('allslots',$hashid);
14147: }
14148: 
14149: sub get_coursechange {
14150:     my ($cdom,$cnum) = @_;
14151:     if ($cdom eq '' || $cnum eq '') {
14152:         return unless ($env{'request.course.id'});
14153:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
14154:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
14155:     }
14156:     my $hashid=$cdom.'_'.$cnum;
14157:     my ($change,$cached)=&is_cached_new('crschange',$hashid);
14158:     if ((defined($cached)) && ($change ne '')) {
14159:         return $change;
14160:     } else {
14161:         my %crshash;
14162:         %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
14163:         if ($crshash{'internal.contentchange'} eq '') {
14164:             $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
14165:             if ($change eq '') {
14166:                 %crshash = &get('environment',['internal.created'],$cdom,$cnum);
14167:                 $change = $crshash{'internal.created'};
14168:             }
14169:         } else {
14170:             $change = $crshash{'internal.contentchange'};
14171:         }
14172:         my $cachetime = 600;
14173:         &do_cache_new('crschange',$hashid,$change,$cachetime);
14174:     }
14175:     return $change;
14176: }
14177: 
14178: sub devalidate_coursechange_cache {
14179:     my ($cdom,$cnum)=@_;
14180:     my $hashid=$cdom.'_'.$cnum;
14181:     &devalidate_cache_new('crschange',$hashid);
14182: }
14183: 
14184: sub get_suppchange {
14185:     my ($cdom,$cnum) = @_;
14186:     if ($cdom eq '' || $cnum eq '') {
14187:         return unless ($env{'request.course.id'});
14188:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
14189:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
14190:     }
14191:     my $hashid=$cdom.'_'.$cnum;
14192:     my ($change,$cached)=&is_cached_new('suppchange',$hashid);
14193:     if ((defined($cached)) && ($change ne '')) {
14194:         return $change;
14195:     } else {
14196:         my %crshash = &get('environment',['internal.supplementalchange'],$cdom,$cnum);
14197:         if ($crshash{'internal.supplementalchange'} eq '') {
14198:             $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
14199:             if ($change eq '') {
14200:                 %crshash = &get('environment',['internal.created'],$cdom,$cnum);
14201:                 $change = $crshash{'internal.created'};
14202:             }
14203:         } else {
14204:             $change = $crshash{'internal.supplementalchange'};
14205:         }
14206:         my $cachetime = 600;
14207:         &do_cache_new('suppchange',$hashid,$change,$cachetime);
14208:     }
14209:     return $change;
14210: }
14211: 
14212: sub devalidate_suppchange_cache {
14213:     my ($cdom,$cnum)=@_;
14214:     my $hashid=$cdom.'_'.$cnum;
14215:     &devalidate_cache_new('suppchange',$hashid);
14216: }
14217: 
14218: sub update_supp_caches {
14219:     my ($cdom,$cnum) = @_;
14220:     my %servers = &internet_dom_servers($cdom);
14221:     my @ids=&current_machine_ids();
14222:     foreach my $server (keys(%servers)) {
14223:         next if (grep(/^\Q$server\E$/,@ids));
14224:         my $hashid=$cnum.':'.$cdom;
14225:         my $cachekey = &escape('showsupp').':'.&escape($hashid);
14226:         &remote_devalidate_cache($server,[$cachekey]);
14227:     }
14228:     &has_unhidden_suppfiles($cnum,$cdom,1,1);
14229:     &count_supptools($cnum,$cdom,1);
14230:     my $now = time;
14231:     if ($env{'request.course.id'} eq $cdom.'_'.$cnum) {
14232:         &Apache::lonnet::appenv({'request.course.suppupdated' => $now});
14233:     }
14234:     &put('environment',{'internal.supplementalchange' => $now},
14235:          $cdom,$cnum);
14236:     &Apache::lonnet::appenv(
14237:         {'course.'.$cdom.'_'.$cnum.'.internal.supplementalchange' => $now});
14238:     &do_cache_new('suppchange',$cdom.'_'.$cnum,$now,600);
14239: }
14240: 
14241: # ------------------------------------------------- Update symbolic store links
14242: 
14243: sub symblist {
14244:     my ($mapname,%newhash)=@_;
14245:     $mapname=&deversion(&declutter($mapname));
14246:     my %hash;
14247:     if (($env{'request.course.fn'}) && (%newhash)) {
14248:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
14249:                       &GDBM_WRCREAT(),0640)) {
14250: 	    foreach my $url (keys(%newhash)) {
14251: 		next if ($url eq 'last_known'
14252: 			 && $env{'form.no_update_last_known'});
14253: 		$hash{declutter($url)}=&encode_symb($mapname,
14254: 						    $newhash{$url}->[1],
14255: 						    $newhash{$url}->[0]);
14256:             }
14257:             if (untie(%hash)) {
14258: 		return 'ok';
14259:             }
14260:         }
14261:     }
14262:     return 'error';
14263: }
14264: 
14265: # --------------------------------------------------------------- Verify a symb
14266: 
14267: sub symbverify {
14268:     my ($symb,$thisurl,$encstate)=@_;
14269:     my $thisfn=$thisurl;
14270:     $thisfn=&declutter($thisfn);
14271: # direct jump to resource in page or to a sequence - will construct own symbs
14272:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
14273: # check URL part
14274:     my ($map,$resid,$url)=&decode_symb($symb);
14275: 
14276:     unless ($url eq $thisfn) { return 0; }
14277: 
14278:     $symb=&symbclean($symb);
14279:     $thisurl=&deversion($thisurl);
14280:     $thisfn=&deversion($thisfn);
14281: 
14282:     my %bighash;
14283:     my $okay=0;
14284: 
14285:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
14286:                             &GDBM_READER(),0640)) {
14287:         if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
14288:             $thisurl =~ s/\?.+$//;
14289:             if ($map =~ m{^uploaded/.+\.page$}) {
14290:                 $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
14291:                 $thisurl =~ s{^\Qhttp://https://\E}{https://};
14292:             }
14293:         }
14294:         my $ids;
14295:         if ($map =~ m{^uploaded/.+\.page$}) {
14296:             $ids=$bighash{'ids_'.&clutter_with_no_wrapper($thisurl)};
14297:         } else {
14298:             $ids=$bighash{'ids_'.&clutter($thisurl)};
14299:         }
14300:         unless ($ids) {
14301:             my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;  
14302:             $ids=$bighash{$idkey};
14303:         }
14304:         if ($ids) {
14305: # ------------------------------------------------------------------- Has ID(s)
14306:             if ($thisfn =~ m{^/adm/wrapper/ext/}) {
14307:                 $symb =~ s/\?.+$//;
14308:             }
14309: 	    foreach my $id (split(/\,/,$ids)) {
14310: 	       my ($mapid,$resid)=split(/\./,$id);
14311:                if (
14312:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
14313:    eq $symb) {
14314:                    if (ref($encstate)) {
14315:                        $$encstate = $bighash{'encrypted_'.$id};
14316:                    }
14317: 		   if (($env{'request.role.adv'}) ||
14318: 		       ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
14319:                        ($thisurl eq '/adm/navmaps')) {
14320: 		       $okay=1;
14321:                        last;
14322: 		   }
14323: 	       }
14324: 	   }
14325:         }
14326: 	untie(%bighash);
14327:     }
14328:     return $okay;
14329: }
14330: 
14331: # --------------------------------------------------------------- Clean-up symb
14332: 
14333: sub symbclean {
14334:     my $symb=shift;
14335:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
14336: # remove version from map
14337:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
14338: 
14339: # remove version from URL
14340:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
14341: 
14342: # remove wrapper
14343: 
14344:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
14345:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
14346:     return $symb;
14347: }
14348: 
14349: # ---------------------------------------------- Split symb to find map and url
14350: 
14351: sub encode_symb {
14352:     my ($map,$resid,$url)=@_;
14353:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
14354: }
14355: 
14356: sub decode_symb {
14357:     my $symb=shift;
14358:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
14359:     my ($map,$resid,$url)=split(/___/,$symb);
14360:     return (&fixversion($map),$resid,&fixversion($url));
14361: }
14362: 
14363: sub fixversion {
14364:     my $fn=shift;
14365:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
14366:     my %bighash;
14367:     my $uri=&clutter($fn);
14368:     my $key=$env{'request.course.id'}.'_'.$uri;
14369: # is this cached?
14370:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
14371:     if (defined($cached)) { return $result; }
14372: # unfortunately not cached, or expired
14373:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
14374: 	    &GDBM_READER(),0640)) {
14375:  	if ($bighash{'version_'.$uri}) {
14376:  	    my $version=$bighash{'version_'.$uri};
14377:  	    unless (($version eq 'mostrecent') || 
14378: 		    ($version==&getversion($uri))) {
14379:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
14380:  	    }
14381:  	}
14382:  	untie %bighash;
14383:     }
14384:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
14385: }
14386: 
14387: sub deversion {
14388:     my $url=shift;
14389:     $url=~s/\.\d+\.(\w+)$/\.$1/;
14390:     return $url;
14391: }
14392: 
14393: # ------------------------------------------------------ Return symb list entry
14394: 
14395: sub symbread {
14396:     my ($thisfn,$donotrecurse,$ignorecachednull,$checkforblock,$possibles,
14397:         $ignoresymbdb,$noenccheck)=@_;
14398:     my $cache_str='request.symbread.cached.'.$thisfn;
14399:     if (defined($env{$cache_str})) {
14400:         unless (ref($possibles) eq 'HASH') {
14401:             if ($ignorecachednull) {
14402:                 return $env{$cache_str} unless ($env{$cache_str} eq '');
14403:             } else {
14404:                 return $env{$cache_str};
14405:             }
14406:         }
14407:     }
14408: # no filename provided? try from environment
14409:     unless ($thisfn) {
14410:         if ($env{'request.symb'}) {
14411:             return $env{$cache_str}=&symbclean($env{'request.symb'});
14412: 	}
14413: 	$thisfn=$env{'request.filename'};
14414:     }
14415:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
14416: # is that filename actually a symb? Verify, clean, and return
14417:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
14418: 	if (&symbverify($thisfn,$1)) {
14419: 	    return $env{$cache_str}=&symbclean($thisfn);
14420: 	}
14421:     }
14422:     $thisfn=declutter($thisfn);
14423:     my %hash;
14424:     my %bighash;
14425:     my $syval='';
14426:     if (($env{'request.course.fn'}) && ($thisfn)) {
14427:         unless ($ignoresymbdb) {
14428:             if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
14429:                           &GDBM_READER(),0640)) {
14430: 	        $syval=$hash{$thisfn};
14431:                 untie(%hash);
14432:             }
14433:             if ($syval && $checkforblock) {
14434:                 my @blockers = &has_comm_blocking('bre',$syval,$thisfn,$ignoresymbdb,$noenccheck);
14435:                 if (@blockers) {
14436:                     $syval='';
14437:                 }
14438:             }
14439:         }
14440: # ---------------------------------------------------------- There was an entry
14441:         if ($syval) {
14442: 	    #unless ($syval=~/\_\d+$/) {
14443: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
14444: 		    #&appenv({'request.ambiguous' => $thisfn});
14445: 		    #return $env{$cache_str}='';
14446: 		#}    
14447: 		#$syval.=$1;
14448: 	    #}
14449:         } else {
14450: # ------------------------------------------------------- Was not in symb table
14451:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
14452:                             &GDBM_READER(),0640)) {
14453: # ---------------------------------------------- Get ID(s) for current resource
14454:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
14455:               unless ($ids) { 
14456:                  $ids=$bighash{'ids_/'.$thisfn};
14457:               }
14458:               unless ($ids) {
14459: # alias?
14460: 		  $ids=$bighash{'mapalias_'.$thisfn};
14461:               }
14462:               if ($ids) {
14463: # ------------------------------------------------------------------- Has ID(s)
14464:                  my @possibilities=split(/\,/,$ids);
14465:                  if ($#possibilities==0) {
14466: # ----------------------------------------------- There is only one possibility
14467: 		     my ($mapid,$resid)=split(/\./,$ids);
14468: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
14469: 						    $resid,$thisfn);
14470:                      if (ref($possibles) eq 'HASH') {
14471:                          unless ($bighash{'randomout_'.$ids} || $env{'request.role.adv'}) {
14472:                              $possibles->{$syval} = 1;
14473:                          }
14474:                      }
14475:                      if ($checkforblock) {
14476:                          unless ($bighash{'randomout_'.$ids} || $env{'request.role.adv'}) {
14477:                              my @blockers = &has_comm_blocking('bre',$syval,$bighash{'src_'.$ids},'',$noenccheck);
14478:                              if (@blockers) {
14479:                                  $syval = '';
14480:                                  untie(%bighash);
14481:                                  return $env{$cache_str}='';
14482:                              }
14483:                          }
14484:                      }
14485:                  } elsif ((!$donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) { 
14486: # ------------------------------------------ There is more than one possibility
14487:                      my $realpossible=0;
14488:                      foreach my $id (@possibilities) {
14489: 			 my $file=$bighash{'src_'.$id};
14490:                          my $canaccess;
14491:                          if (($donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
14492:                              $canaccess = 1;
14493:                          } else { 
14494:                              $canaccess = &allowed('bre',$file);
14495:                          }
14496:                          if ($canaccess) {
14497:          		     my ($mapid,$resid)=split(/\./,$id);
14498:                              if ($bighash{'map_type_'.$mapid} ne 'page') {
14499:                                  my $poss_syval=&encode_symb($bighash{'map_id_'.$mapid},
14500: 						             $resid,$thisfn);
14501:                                  next if ($bighash{'randomout_'.$id} && !$env{'request.role.adv'});
14502:                                  next unless (($noenccheck) || ($bighash{'encrypted_'.$id} eq $env{'request.enc'}));
14503:                                  if ($checkforblock) {
14504:                                      my @blockers = &has_comm_blocking('bre',$poss_syval,$file,'',$noenccheck);
14505:                                      if (@blockers > 0) {
14506:                                          $syval = '';
14507:                                      } else {
14508:                                          $syval = $poss_syval;
14509:                                          $realpossible++;
14510:                                      }
14511:                                  } else {
14512:                                      $syval = $poss_syval;
14513:                                      $realpossible++;
14514:                                  }
14515:                                  if ($syval) {
14516:                                      if (ref($possibles) eq 'HASH') {
14517:                                          $possibles->{$syval} = 1;
14518:                                      }
14519:                                  }
14520:                              }
14521: 			 }
14522:                      }
14523: 		     if ($realpossible!=1) { $syval=''; }
14524:                  } else {
14525:                      $syval='';
14526:                  }
14527: 	      }
14528:               untie(%bighash);
14529:            }
14530:         }
14531:         if ($syval) {
14532: 	    return $env{$cache_str}=$syval;
14533:         }
14534:     }
14535:     &appenv({'request.ambiguous' => $thisfn});
14536:     return $env{$cache_str}='';
14537: }
14538: 
14539: # ---------------------------------------------------------- Return random seed
14540: 
14541: sub numval {
14542:     my $txt=shift;
14543:     $txt=~tr/A-J/0-9/;
14544:     $txt=~tr/a-j/0-9/;
14545:     $txt=~tr/K-T/0-9/;
14546:     $txt=~tr/k-t/0-9/;
14547:     $txt=~tr/U-Z/0-5/;
14548:     $txt=~tr/u-z/0-5/;
14549:     $txt=~s/\D//g;
14550:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
14551:     return int($txt);
14552: }
14553: 
14554: sub numval2 {
14555:     my $txt=shift;
14556:     $txt=~tr/A-J/0-9/;
14557:     $txt=~tr/a-j/0-9/;
14558:     $txt=~tr/K-T/0-9/;
14559:     $txt=~tr/k-t/0-9/;
14560:     $txt=~tr/U-Z/0-5/;
14561:     $txt=~tr/u-z/0-5/;
14562:     $txt=~s/\D//g;
14563:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
14564:     my $total;
14565:     foreach my $val (@txts) { $total+=$val; }
14566:     if ($_64bit) { if ($total > 2**32) { return -1; } }
14567:     return int($total);
14568: }
14569: 
14570: sub numval3 {
14571:     use integer;
14572:     my $txt=shift;
14573:     $txt=~tr/A-J/0-9/;
14574:     $txt=~tr/a-j/0-9/;
14575:     $txt=~tr/K-T/0-9/;
14576:     $txt=~tr/k-t/0-9/;
14577:     $txt=~tr/U-Z/0-5/;
14578:     $txt=~tr/u-z/0-5/;
14579:     $txt=~s/\D//g;
14580:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
14581:     my $total;
14582:     foreach my $val (@txts) { $total+=$val; }
14583:     if ($_64bit) { $total=(($total<<32)>>32); }
14584:     return $total;
14585: }
14586: 
14587: sub digest {
14588:     my ($data)=@_;
14589:     my $digest=&Digest::MD5::md5($data);
14590:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
14591:     my ($e,$f);
14592:     {
14593:         use integer;
14594:         $e=($a+$b);
14595:         $f=($c+$d);
14596:         if ($_64bit) {
14597:             $e=(($e<<32)>>32);
14598:             $f=(($f<<32)>>32);
14599:         }
14600:     }
14601:     if (wantarray) {
14602: 	return ($e,$f);
14603:     } else {
14604: 	my $g;
14605: 	{
14606: 	    use integer;
14607: 	    $g=($e+$f);
14608: 	    if ($_64bit) {
14609: 		$g=(($g<<32)>>32);
14610: 	    }
14611: 	}
14612: 	return $g;
14613:     }
14614: }
14615: 
14616: sub latest_rnd_algorithm_id {
14617:     return '64bit5';
14618: }
14619: 
14620: sub get_rand_alg {
14621:     my ($courseid)=@_;
14622:     if (!$courseid) { $courseid=(&whichuser())[1]; }
14623:     if ($courseid) {
14624: 	return $env{"course.$courseid.rndseed"};
14625:     }
14626:     return &latest_rnd_algorithm_id();
14627: }
14628: 
14629: sub validCODE {
14630:     my ($CODE)=@_;
14631:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
14632:     return 0;
14633: }
14634: 
14635: sub getCODE {
14636:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
14637:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
14638: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
14639: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
14640: 	return $Apache::lonhomework::history{'resource.CODE'};
14641:     }
14642:     return undef;
14643: }
14644: #
14645: #  Determines the random seed for a specific context:
14646: #
14647: # parameters:
14648: #   symb      - in course context the symb for the seed.
14649: #   course_id - The course id of the form domain_coursenum.
14650: #   domain    - Domain for the user.
14651: #   course    - Course for the user.
14652: #   cenv      - environment of the course.
14653: #
14654: # NOTE:
14655: #   All parameters are picked out of the environment if missing
14656: #   or not defined.
14657: #   If a symb cannot be determined the current time is used instead.
14658: #
14659: #  For a given well defined symb, courside, domain, username,
14660: #  and course environment, the seed is reproducible.
14661: #
14662: sub rndseed {
14663:     my ($symb,$courseid,$domain,$username, $cenv)=@_;
14664:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
14665:     if (!defined($symb)) {
14666: 	unless ($symb=$wsymb) { return time; }
14667:     }
14668:     if (!defined $courseid) { 
14669: 	$courseid=$wcourseid; 
14670:     }
14671:     if (!defined $domain) { $domain=$wdomain; }
14672:     if (!defined $username) { $username=$wusername }
14673: 
14674:     my $which;
14675:     if (defined($cenv->{'rndseed'})) {
14676: 	$which = $cenv->{'rndseed'};
14677:     } else {
14678: 	$which =&get_rand_alg($courseid);
14679:     }
14680:     if (defined(&getCODE())) {
14681: 
14682: 	if ($which eq '64bit5') {
14683: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
14684: 	} elsif ($which eq '64bit4') {
14685: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
14686: 	} else {
14687: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
14688: 	}
14689:     } elsif ($which eq '64bit5') {
14690: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
14691:     } elsif ($which eq '64bit4') {
14692: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
14693:     } elsif ($which eq '64bit3') {
14694: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
14695:     } elsif ($which eq '64bit2') {
14696: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
14697:     } elsif ($which eq '64bit') {
14698: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
14699:     }
14700:     return &rndseed_32bit($symb,$courseid,$domain,$username);
14701: }
14702: 
14703: sub rndseed_32bit {
14704:     my ($symb,$courseid,$domain,$username)=@_;
14705:     {
14706: 	use integer;
14707: 	my $symbchck=unpack("%32C*",$symb) << 27;
14708: 	my $symbseed=numval($symb) << 22;
14709: 	my $namechck=unpack("%32C*",$username) << 17;
14710: 	my $nameseed=numval($username) << 12;
14711: 	my $domainseed=unpack("%32C*",$domain) << 7;
14712: 	my $courseseed=unpack("%32C*",$courseid);
14713: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
14714: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
14715: 	#&logthis("rndseed :$num:$symb");
14716: 	if ($_64bit) { $num=(($num<<32)>>32); }
14717: 	return $num;
14718:     }
14719: }
14720: 
14721: sub rndseed_64bit {
14722:     my ($symb,$courseid,$domain,$username)=@_;
14723:     {
14724: 	use integer;
14725: 	my $symbchck=unpack("%32S*",$symb) << 21;
14726: 	my $symbseed=numval($symb) << 10;
14727: 	my $namechck=unpack("%32S*",$username);
14728: 	
14729: 	my $nameseed=numval($username) << 21;
14730: 	my $domainseed=unpack("%32S*",$domain) << 10;
14731: 	my $courseseed=unpack("%32S*",$courseid);
14732: 	
14733: 	my $num1=$symbchck+$symbseed+$namechck;
14734: 	my $num2=$nameseed+$domainseed+$courseseed;
14735: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
14736: 	#&logthis("rndseed :$num:$symb");
14737: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
14738: 	return "$num1,$num2";
14739:     }
14740: }
14741: 
14742: sub rndseed_64bit2 {
14743:     my ($symb,$courseid,$domain,$username)=@_;
14744:     {
14745: 	use integer;
14746: 	# strings need to be an even # of cahracters long, it it is odd the
14747:         # last characters gets thrown away
14748: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
14749: 	my $symbseed=numval($symb) << 10;
14750: 	my $namechck=unpack("%32S*",$username.' ');
14751: 	
14752: 	my $nameseed=numval($username) << 21;
14753: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
14754: 	my $courseseed=unpack("%32S*",$courseid.' ');
14755: 	
14756: 	my $num1=$symbchck+$symbseed+$namechck;
14757: 	my $num2=$nameseed+$domainseed+$courseseed;
14758: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
14759: 	#&logthis("rndseed :$num:$symb");
14760: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
14761: 	return "$num1,$num2";
14762:     }
14763: }
14764: 
14765: sub rndseed_64bit3 {
14766:     my ($symb,$courseid,$domain,$username)=@_;
14767:     {
14768: 	use integer;
14769: 	# strings need to be an even # of cahracters long, it it is odd the
14770:         # last characters gets thrown away
14771: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
14772: 	my $symbseed=numval2($symb) << 10;
14773: 	my $namechck=unpack("%32S*",$username.' ');
14774: 	
14775: 	my $nameseed=numval2($username) << 21;
14776: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
14777: 	my $courseseed=unpack("%32S*",$courseid.' ');
14778: 	
14779: 	my $num1=$symbchck+$symbseed+$namechck;
14780: 	my $num2=$nameseed+$domainseed+$courseseed;
14781: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
14782: 	#&logthis("rndseed :$num1:$num2:$_64bit");
14783: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
14784: 	
14785: 	return "$num1:$num2";
14786:     }
14787: }
14788: 
14789: sub rndseed_64bit4 {
14790:     my ($symb,$courseid,$domain,$username)=@_;
14791:     {
14792: 	use integer;
14793: 	# strings need to be an even # of cahracters long, it it is odd the
14794:         # last characters gets thrown away
14795: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
14796: 	my $symbseed=numval3($symb) << 10;
14797: 	my $namechck=unpack("%32S*",$username.' ');
14798: 	
14799: 	my $nameseed=numval3($username) << 21;
14800: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
14801: 	my $courseseed=unpack("%32S*",$courseid.' ');
14802: 	
14803: 	my $num1=$symbchck+$symbseed+$namechck;
14804: 	my $num2=$nameseed+$domainseed+$courseseed;
14805: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
14806: 	#&logthis("rndseed :$num1:$num2:$_64bit");
14807: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
14808: 	
14809: 	return "$num1:$num2";
14810:     }
14811: }
14812: 
14813: sub rndseed_64bit5 {
14814:     my ($symb,$courseid,$domain,$username)=@_;
14815:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
14816:     return "$num1:$num2";
14817: }
14818: 
14819: sub rndseed_CODE_64bit {
14820:     my ($symb,$courseid,$domain,$username)=@_;
14821:     {
14822: 	use integer;
14823: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
14824: 	my $symbseed=numval2($symb);
14825: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
14826: 	my $CODEseed=numval(&getCODE());
14827: 	my $courseseed=unpack("%32S*",$courseid.' ');
14828: 	my $num1=$symbseed+$CODEchck;
14829: 	my $num2=$CODEseed+$courseseed+$symbchck;
14830: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
14831: 	#&logthis("rndseed :$num1:$num2:$symb");
14832: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
14833: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
14834: 	return "$num1:$num2";
14835:     }
14836: }
14837: 
14838: sub rndseed_CODE_64bit4 {
14839:     my ($symb,$courseid,$domain,$username)=@_;
14840:     {
14841: 	use integer;
14842: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
14843: 	my $symbseed=numval3($symb);
14844: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
14845: 	my $CODEseed=numval3(&getCODE());
14846: 	my $courseseed=unpack("%32S*",$courseid.' ');
14847: 	my $num1=$symbseed+$CODEchck;
14848: 	my $num2=$CODEseed+$courseseed+$symbchck;
14849: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
14850: 	#&logthis("rndseed :$num1:$num2:$symb");
14851: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
14852: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
14853: 	return "$num1:$num2";
14854:     }
14855: }
14856: 
14857: sub rndseed_CODE_64bit5 {
14858:     my ($symb,$courseid,$domain,$username)=@_;
14859:     my $code = &getCODE();
14860:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
14861:     return "$num1:$num2";
14862: }
14863: 
14864: sub setup_random_from_rndseed {
14865:     my ($rndseed)=@_;
14866:     if ($rndseed =~/([,:])/) {
14867:         my ($num1,$num2) = map { abs($_); } (split(/[,:]/,$rndseed));
14868:         if ((!$num1) || (!$num2) || ($num1 > 2147483562) || ($num2 > 2147483398)) {
14869:             &Math::Random::random_set_seed_from_phrase($rndseed);
14870:         } else {
14871:             &Math::Random::random_set_seed($num1,$num2);
14872:         }
14873:     } else {
14874: 	&Math::Random::random_set_seed_from_phrase($rndseed);
14875:     }
14876: }
14877: 
14878: sub latest_receipt_algorithm_id {
14879:     return 'receipt3';
14880: }
14881: 
14882: sub recunique {
14883:     my $fucourseid=shift;
14884:     my $unique;
14885:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
14886: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
14887: 	$unique=$env{"course.$fucourseid.internal.encseed"};
14888:     } else {
14889: 	$unique=$perlvar{'lonReceipt'};
14890:     }
14891:     return unpack("%32C*",$unique);
14892: }
14893: 
14894: sub recprefix {
14895:     my $fucourseid=shift;
14896:     my $prefix;
14897:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
14898: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
14899: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
14900:     } else {
14901: 	$prefix=$perlvar{'lonHostID'};
14902:     }
14903:     return unpack("%32C*",$prefix);
14904: }
14905: 
14906: sub ireceipt {
14907:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
14908: 
14909:     my $return =&recprefix($fucourseid).'-';
14910: 
14911:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
14912: 	$env{'request.state'} eq 'construct') {
14913: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
14914: 	return $return;
14915:     }
14916: 
14917:     my $cuname=unpack("%32C*",$funame);
14918:     my $cudom=unpack("%32C*",$fudom);
14919:     my $cucourseid=unpack("%32C*",$fucourseid);
14920:     my $cusymb=unpack("%32C*",$fusymb);
14921:     my $cunique=&recunique($fucourseid);
14922:     my $cpart=unpack("%32S*",$part);
14923:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
14924: 
14925: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
14926: 			       
14927: 	$return.= ($cunique%$cuname+
14928: 		   $cunique%$cudom+
14929: 		   $cusymb%$cuname+
14930: 		   $cusymb%$cudom+
14931: 		   $cucourseid%$cuname+
14932: 		   $cucourseid%$cudom+
14933: 		   $cpart%$cuname+
14934: 		   $cpart%$cudom);
14935:     } else {
14936: 	$return.= ($cunique%$cuname+
14937: 		   $cunique%$cudom+
14938: 		   $cusymb%$cuname+
14939: 		   $cusymb%$cudom+
14940: 		   $cucourseid%$cuname+
14941: 		   $cucourseid%$cudom);
14942:     }
14943:     return $return;
14944: }
14945: 
14946: sub receipt {
14947:     my ($part)=@_;
14948:     my ($symb,$courseid,$domain,$name) = &whichuser();
14949:     return &ireceipt($name,$domain,$courseid,$symb,$part);
14950: }
14951: 
14952: sub whichuser {
14953:     my ($passedsymb)=@_;
14954:     my ($symb,$courseid,$domain,$name,$publicuser);
14955:     if (defined($env{'form.grade_symb'})) {
14956: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
14957: 	my $allowed=&allowed('vgr',$tmp_courseid);
14958: 	if (!$allowed &&
14959: 	    exists($env{'request.course.sec'}) &&
14960: 	    $env{'request.course.sec'} !~ /^\s*$/) {
14961: 	    $allowed=&allowed('vgr',$tmp_courseid.
14962: 			      '/'.$env{'request.course.sec'});
14963: 	}
14964: 	if ($allowed) {
14965: 	    ($symb)=&get_env_multiple('form.grade_symb');
14966: 	    $courseid=$tmp_courseid;
14967: 	    ($domain)=&get_env_multiple('form.grade_domain');
14968: 	    ($name)=&get_env_multiple('form.grade_username');
14969: 	    return ($symb,$courseid,$domain,$name,$publicuser);
14970: 	}
14971:     }
14972:     if (!$passedsymb) {
14973: 	$symb=&symbread();
14974:     } else {
14975: 	$symb=$passedsymb;
14976:     }
14977:     $courseid=$env{'request.course.id'};
14978:     $domain=$env{'user.domain'};
14979:     $name=$env{'user.name'};
14980:     if ($name eq 'public' && $domain eq 'public') {
14981: 	if (!defined($env{'form.username'})) {
14982: 	    $env{'form.username'}.=time.rand(10000000);
14983: 	}
14984: 	$name.=$env{'form.username'};
14985:     }
14986:     return ($symb,$courseid,$domain,$name,$publicuser);
14987: 
14988: }
14989: 
14990: # ------------------------------------------------------------ Serves up a file
14991: # returns either the contents of the file or 
14992: # -1 if the file doesn't exist
14993: #
14994: # if the target is a file that was uploaded via DOCS, 
14995: # a check will be made to see if a current copy exists on the local server,
14996: # if it does this will be served, otherwise a copy will be retrieved from
14997: # the home server for the course and stored in /home/httpd/html/userfiles on
14998: # the local server.   
14999: 
15000: sub getfile {
15001:     my ($file) = @_;
15002:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
15003:     &repcopy($file);
15004:     return &readfile($file);
15005: }
15006: 
15007: sub repcopy_userfile {
15008:     my ($file)=@_;
15009:     my $londocroot = $perlvar{'lonDocRoot'};
15010:     if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
15011:     if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
15012:     my ($cdom,$cnum,$filename) = 
15013: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
15014:     my $uri="/uploaded/$cdom/$cnum/$filename";
15015:     if (-e "$file") {
15016: # we already have a local copy, check it out
15017: 	my @fileinfo = stat($file);
15018: 	my $rtncode;
15019: 	my $info;
15020: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
15021: 	if ($lwpresp ne 'ok') {
15022: # there is no such file anymore, even though we had a local copy
15023: 	    if ($rtncode eq '404') {
15024: 		unlink($file);
15025: 	    }
15026: 	    return -1;
15027: 	}
15028: 	if ($info < $fileinfo[9]) {
15029: # nice, the file we have is up-to-date, just say okay
15030: 	    return 'ok';
15031: 	} else {
15032: # the file is outdated, get rid of it
15033: 	    unlink($file);
15034: 	}
15035:     }
15036: # one way or the other, at this point, we don't have the file
15037: # construct the correct path for the file
15038:     my @parts = ($cdom,$cnum); 
15039:     if ($filename =~ m|^(.+)/[^/]+$|) {
15040: 	push @parts, split(/\//,$1);
15041:     }
15042:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
15043:     foreach my $part (@parts) {
15044: 	$path .= '/'.$part;
15045: 	if (!-e $path) {
15046: 	    mkdir($path,0770);
15047: 	}
15048:     }
15049: # now the path exists for sure
15050: # get a user agent
15051:     my $transferfile=$file.'.in.transfer';
15052: # FIXME: this should flock
15053:     if (-e $transferfile) { return 'ok'; }
15054:     my $request;
15055:     $uri=~s/^\///;
15056:     my $homeserver = &homeserver($cnum,$cdom);
15057:     my $hostname = &hostname($homeserver);
15058:     my $protocol = $protocol{$homeserver};
15059:     $protocol = 'http' if ($protocol ne 'https');
15060:     $request=new HTTP::Request('GET',$protocol.'://'.$hostname.'/raw/'.$uri);
15061:     my $response = &LONCAPA::LWPReq::makerequest($homeserver,$request,$transferfile,\%perlvar,'',0,1);
15062: # did it work?
15063:     if ($response->is_error()) {
15064: 	unlink($transferfile);
15065: 	&logthis("Userfile repcopy failed for $uri");
15066: 	return -1;
15067:     }
15068: # worked, rename the transfer file
15069:     rename($transferfile,$file);
15070:     return 'ok';
15071: }
15072: 
15073: sub tokenwrapper {
15074:     my $uri=shift;
15075:     $uri=~s|^https?\://([^/]+)||;
15076:     $uri=~s|^/||;
15077:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
15078:     my $token=$1;
15079:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
15080:     if ($udom && $uname && $file) {
15081: 	$file=~s|(\?\.*)*$||;
15082:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
15083:         my $homeserver = &homeserver($uname,$udom);
15084:         my $hostname = &hostname($homeserver);
15085:         my $protocol = $protocol{$homeserver};
15086:         $protocol = 'http' if ($protocol ne 'https');
15087:         return $protocol.'://'.$hostname.'/'.$uri.
15088:                (($uri=~/\?/)?'&':'?').'token='.$token.
15089:                                '&tokenissued='.$perlvar{'lonHostID'};
15090:     } else {
15091:         return '/adm/notfound.html';
15092:     }
15093: }
15094: 
15095: # call with reqtype HEAD: get last modification time
15096: # call with reqtype GET: get the file contents
15097: # Do not call this with reqtype GET for large files! It loads everything into memory
15098: #
15099: sub getuploaded {
15100:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
15101:     $uri=~s/^\///;
15102:     my $homeserver = &homeserver($cnum,$cdom);
15103:     my $hostname = &hostname($homeserver);
15104:     my $protocol = $protocol{$homeserver};
15105:     $protocol = 'http' if ($protocol ne 'https');
15106:     $uri = $protocol.'://'.$hostname.'/raw/'.$uri;
15107:     my $request=new HTTP::Request($reqtype,$uri);
15108:     my $response=&LONCAPA::LWPReq::makerequest($homeserver,$request,'',\%perlvar,'',0,1);
15109:     $$rtncode = $response->code;
15110:     if (! $response->is_success()) {
15111: 	return 'failed';
15112:     }      
15113:     if ($reqtype eq 'HEAD') {
15114: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
15115:     } elsif ($reqtype eq 'GET') {
15116: 	$$info = $response->content;
15117:     }
15118:     return 'ok';
15119: }
15120: 
15121: sub readfile {
15122:     my $file = shift;
15123:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
15124:     my $fh;
15125:     open($fh,"<",$file);
15126:     my $a='';
15127:     while (my $line = <$fh>) { $a .= $line; }
15128:     return $a;
15129: }
15130: 
15131: sub filelocation {
15132:     my ($dir,$file) = @_;
15133:     my $location;
15134:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
15135: 
15136:     if ($file =~ m-^/adm/-) {
15137: 	$file=~s-^/adm/wrapper/-/-;
15138: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
15139:     }
15140: 
15141:     if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
15142:         $location = $file;
15143:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
15144:         my ($udom,$uname,$filename)=
15145:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
15146:         my $home=&homeserver($uname,$udom);
15147:         my $is_me=0;
15148:         my @ids=&current_machine_ids();
15149:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
15150:         if ($is_me) {
15151:   	    $location=propath($udom,$uname).'/userfiles/'.$filename;
15152:         } else {
15153:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
15154:   	      $udom.'/'.$uname.'/'.$filename;
15155:         }
15156:     } elsif ($file =~ m-^/adm/-) {
15157: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
15158:     } else {
15159:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
15160:         $file=~s:^/(res|priv)/:/:;
15161:         my $space=$1;
15162:         if ( !( $file =~ m:^/:) ) {
15163:             $location = $dir. '/'.$file;
15164:         } else {
15165:             $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
15166:         }
15167:     }
15168:     $location=~s://+:/:g; # remove duplicate /
15169:     while ($location=~m{/\.\./}) {
15170: 	if ($location =~ m{/[^/]+/\.\./}) {
15171: 	    $location=~ s{/[^/]+/\.\./}{/}g;
15172: 	} else {
15173: 	    $location=~ s{/\.\./}{/}g;
15174: 	}
15175:     } #remove dir/..
15176:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
15177:     return $location;
15178: }
15179: 
15180: sub hreflocation {
15181:     my ($dir,$file)=@_;
15182:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
15183: 	$file=filelocation($dir,$file);
15184:     } elsif ($file=~m-^/adm/-) {
15185: 	$file=~s-^/adm/wrapper/-/-;
15186: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
15187:     }
15188:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
15189: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
15190:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
15191: 	$file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
15192: 	        {/uploaded/$1/$2/}x;
15193:     }
15194:     if ($file=~ m{^/userfiles/}) {
15195: 	$file =~ s{^/userfiles/}{/uploaded/};
15196:     }
15197:     return $file;
15198: }
15199: 
15200: 
15201: 
15202: 
15203: 
15204: sub current_machine_domains {
15205:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
15206: }
15207: 
15208: sub machine_domains {
15209:     my ($hostname) = @_;
15210:     my @domains;
15211:     my %hostname = &all_hostnames();
15212:     while( my($id, $name) = each(%hostname)) {
15213: #	&logthis("-$id-$name-$hostname-");
15214: 	if ($hostname eq $name) {
15215: 	    push(@domains,&host_domain($id));
15216: 	}
15217:     }
15218:     return @domains;
15219: }
15220: 
15221: sub current_machine_ids {
15222:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
15223: }
15224: 
15225: sub machine_ids {
15226:     my ($hostname) = @_;
15227:     $hostname ||= &hostname($perlvar{'lonHostID'});
15228:     my @ids;
15229:     my %name_to_host = &all_names();
15230:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
15231: 	return @{ $name_to_host{$hostname} };
15232:     }
15233:     return;
15234: }
15235: 
15236: sub additional_machine_domains {
15237:     my @domains;
15238:     if (-e "$perlvar{'lonTabDir'}/expected_domains.tab") {
15239:         if (open(my $fh,"<","$perlvar{'lonTabDir'}/expected_domains.tab")) {
15240:             while (my $line = <$fh>) {
15241:                 chomp($line);           
15242:                 $line =~ s/\s//g;
15243:                 push(@domains,$line);
15244:             }
15245:             close($fh);
15246:         }
15247:     }
15248:     return @domains;
15249: }
15250: 
15251: sub default_login_domain {
15252:     my $domain = $perlvar{'lonDefDomain'};
15253:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
15254:     foreach my $posdom (&current_machine_domains(),
15255:                         &additional_machine_domains()) {
15256:         if (lc($posdom) eq lc($testdomain)) {
15257:             $domain=$posdom;
15258:             last;
15259:         }
15260:     }
15261:     return $domain;
15262: }
15263: 
15264: sub shared_institution {
15265:     my ($dom,$lonhost) = @_;
15266:     if ($lonhost eq '') {
15267:         $lonhost = $perlvar{'lonHostID'};
15268:     }
15269:     my $same_intdom;
15270:     my $hostintdom = &internet_dom($lonhost);
15271:     if ($hostintdom ne '') {
15272:         my %iphost = &get_iphost();
15273:         my $primary_id = &domain($dom,'primary');
15274:         my $primary_ip = &get_host_ip($primary_id);
15275:         if (ref($iphost{$primary_ip}) eq 'ARRAY') {
15276:             foreach my $id (@{$iphost{$primary_ip}}) {
15277:                 my $intdom = &internet_dom($id);
15278:                 if ($intdom eq $hostintdom) {
15279:                     $same_intdom = 1;
15280:                     last;
15281:                 }
15282:             }
15283:         }
15284:     }
15285:     return $same_intdom;
15286: }
15287: 
15288: sub uses_sts {
15289:     my ($ignore_cache) = @_;
15290:     my $lonhost = $perlvar{'lonHostID'};
15291:     my $hostname = &hostname($lonhost);
15292:     my $sts_on;
15293:     if ($protocol{$lonhost} eq 'https') {
15294:         my $cachetime = 12*3600;
15295:         if (!$ignore_cache) {
15296:             ($sts_on,my $cached)=&is_cached_new('stspolicy',$lonhost);
15297:             if (defined($cached)) {
15298:                 return $sts_on;
15299:             }
15300:         }
15301:         my $url = $protocol{$lonhost}.'://'.$hostname.'/index.html';
15302:         my $request=new HTTP::Request('HEAD',$url);
15303:         my $response=&LONCAPA::LWPReq::makerequest($lonhost,$request,'',\%perlvar,'','','',1);
15304:         if ($response->is_success) {
15305:             my $has_sts = $response->header('Strict-Transport-Security');
15306:             if ($has_sts eq '') {
15307:                 $sts_on = 0;
15308:             } else {
15309:                 if ($has_sts =~ /\Qmax-age=\E(\d+)/) {
15310:                     my $maxage = $1;
15311:                     if ($maxage) {
15312:                         $sts_on = 1;
15313:                     } else {
15314:                         $sts_on = 0;
15315:                     }
15316:                 } else {
15317:                     $sts_on = 0;
15318:                 }
15319:             }
15320:             return &do_cache_new('stspolicy',$lonhost,$sts_on,$cachetime);
15321:         }
15322:     }
15323:     return;
15324: }
15325: 
15326: sub waf_allssl {
15327:     my ($host_name) = @_;
15328:     my $alias = &get_proxy_alias();
15329:     if ($host_name eq '') {
15330:         $host_name = $ENV{'SERVER_NAME'};
15331:     }
15332:     if (($host_name ne '') && ($alias eq $host_name)) {
15333:         my $serverhomedom = &host_domain($perlvar{'lonHostID'});
15334:         my %defdomdefaults = &get_domain_defaults($serverhomedom);
15335:         if ($defdomdefaults{'waf_sslopt'}) {
15336:             return $defdomdefaults{'waf_sslopt'};
15337:         }
15338:     }
15339:     return;
15340: }
15341: 
15342: sub get_requestor_ip {
15343:     my ($r,$nolookup,$noproxy) = @_;
15344:     my $from_ip;
15345:     if (ref($r)) {
15346:         if ($r->can('useragent_ip')) {
15347:             if ($noproxy && $r->can('client_ip')) {
15348:                 $from_ip = $r->client_ip();
15349:             } else {
15350:                 $from_ip = $r->useragent_ip();
15351:             }
15352:         } elsif ($r->connection->can('remote_ip')) {
15353:             $from_ip = $r->connection->remote_ip();
15354:         } else {
15355:             $from_ip = $r->get_remote_host($nolookup);
15356:         }
15357:     } else {
15358:         $from_ip = $ENV{'REMOTE_ADDR'};
15359:     }
15360:     return $from_ip if ($noproxy); 
15361:     # Who controls proxy settings for server
15362:     my $dom_in_use = $Apache::lonnet::perlvar{'lonDefDomain'};
15363:     my $proxyinfo = &get_proxy_settings($dom_in_use);
15364:     if ((ref($proxyinfo) eq 'HASH') && ($from_ip)) {
15365:         if ($proxyinfo->{'vpnint'}) {
15366:             if (&ip_match($from_ip,$proxyinfo->{'vpnint'})) {
15367:                 return $from_ip;
15368:             }
15369:         }
15370:         if ($proxyinfo->{'trusted'}) {
15371:             if (&ip_match($from_ip,$proxyinfo->{'trusted'})) {
15372:                 my $ipheader = $proxyinfo->{'ipheader'};
15373:                 my ($ip,$xfor);
15374:                 if (ref($r)) {
15375:                     if ($ipheader) {
15376:                         $ip = $r->headers_in->{$ipheader};
15377:                     }
15378:                     $xfor = $r->headers_in->{'X-Forwarded-For'};
15379:                 } else {
15380:                     if ($ipheader) {
15381:                         $ip = $ENV{'HTTP_'.uc($ipheader)};
15382:                     }
15383:                     $xfor = $ENV{'HTTP_X_FORWARDED_FOR'};
15384:                 }
15385:                 if (($ip eq '') && ($xfor ne '')) {
15386:                     foreach my $poss_ip (reverse(split(/\s*,\s*/,$xfor))) {
15387:                         unless (&ip_match($poss_ip,$proxyinfo->{'trusted'})) {
15388:                             $ip = $poss_ip;
15389:                             last;
15390:                         }
15391:                     }
15392:                 }
15393:                 if ($ip ne '') {
15394:                     return $ip;
15395:                 }
15396:             }
15397:         }
15398:     }
15399:     return $from_ip;
15400: }
15401: 
15402: sub get_proxy_settings {
15403:     my ($dom_in_use) = @_;
15404:     my %domdefaults = &get_domain_defaults($dom_in_use);
15405:     my $proxyinfo = {
15406:                        ipheader => $domdefaults{'waf_ipheader'},
15407:                        trusted  => $domdefaults{'waf_trusted'},
15408:                        vpnint   => $domdefaults{'waf_vpnint'},
15409:                        vpnext   => $domdefaults{'waf_vpnext'},
15410:                        sslopt   => $domdefaults{'waf_sslopt'},
15411:                     };
15412:     return $proxyinfo;
15413: }
15414: 
15415: sub ip_match {
15416:     my ($ip,$pattern_str) = @_;
15417:     $ip=Net::CIDR::cidrvalidate($ip);
15418:     if ($ip) {
15419:         return Net::CIDR::cidrlookup($ip,split(/\s*,\s*/,$pattern_str));
15420:     }
15421:     return;
15422: }
15423: 
15424: sub get_proxy_alias {
15425:     my ($lonid) = @_;
15426:     if ($lonid eq '') {
15427:         $lonid = $perlvar{'lonHostID'};
15428:     }
15429:     if (!defined(&hostname($lonid))) {
15430:         return;
15431:     }
15432:     if ($lonid ne '') {
15433:         my ($alias,$cached) = &is_cached_new('proxyalias',$lonid);
15434:         if ($cached) {
15435:             return $alias;
15436:         }
15437:         my $dom = &host_domain($lonid);
15438:         if ($dom ne '') {
15439:             my $cachetime = 60*60*24;
15440:             my %domconfig =
15441:                 &get_dom('configuration',['wafproxy'],$dom);
15442:             if (ref($domconfig{'wafproxy'}) eq 'HASH') {
15443:                 if (ref($domconfig{'wafproxy'}{'alias'}) eq 'HASH') {
15444:                     $alias = $domconfig{'wafproxy'}{'alias'}{$lonid};
15445:                 }
15446:             }
15447:             return &do_cache_new('proxyalias',$lonid,$alias,$cachetime);
15448:         }
15449:     }
15450:     return;
15451: }
15452: 
15453: sub use_proxy_alias {
15454:     my ($r,$lonid) = @_;
15455:     my $alias = &get_proxy_alias($lonid);
15456:     if ($alias) {
15457:         my $dom = &host_domain($lonid);
15458:         if ($dom ne '') {
15459:             my $proxyinfo = &get_proxy_settings($dom);
15460:             my ($vpnint,$remote_ip);
15461:             if (ref($proxyinfo) eq 'HASH') {
15462:                 $vpnint = $proxyinfo->{'vpnint'};
15463:                 if ($vpnint) {
15464:                     $remote_ip = &get_requestor_ip($r,1,1);
15465:                 }
15466:             }
15467:             unless ($vpnint && &ip_match($remote_ip,$vpnint)) {
15468:                 return $alias;
15469:             }
15470:         }
15471:     }
15472:     return;
15473: }
15474: 
15475: sub alias_sso {
15476:     my ($lonid) = @_;
15477:     if ($lonid eq '') {
15478:         $lonid = $perlvar{'lonHostID'};
15479:     }
15480:     if (!defined(&hostname($lonid))) {
15481:         return;
15482:     }
15483:     if ($lonid ne '') {
15484:         my ($use_alias,$cached) = &is_cached_new('proxysaml',$lonid);
15485:         if ($cached) {
15486:             return $use_alias;
15487:         }
15488:         my $dom = &host_domain($lonid);
15489:         if ($dom ne '') {
15490:             my $cachetime = 60*60*24;
15491:             my %domconfig =
15492:                 &get_dom('configuration',['wafproxy'],$dom);
15493:             if (ref($domconfig{'wafproxy'}) eq 'HASH') {
15494:                 if (ref($domconfig{'wafproxy'}{'saml'}) eq 'HASH') {
15495:                     $use_alias = $domconfig{'wafproxy'}{'saml'}{$lonid};
15496:                 }
15497:             }
15498:             return &do_cache_new('proxysaml',$lonid,$use_alias,$cachetime);
15499:         }
15500:     }
15501:     return;
15502: }
15503: 
15504: sub get_saml_landing {
15505:     my ($lonid) = @_;
15506:     if ($lonid eq '') {
15507:         my $defdom = &default_login_domain();
15508:         my @hosts = &current_machine_ids();
15509:         if (@hosts > 1) {
15510:             foreach my $hostid (@hosts) {
15511:                 if (&host_domain($hostid) eq $defdom) {
15512:                     $lonid = $hostid;
15513:                     last;
15514:                 }
15515:             }
15516:         } else {
15517:             $lonid = $perlvar{'lonHostID'};
15518:         }
15519:         if ($lonid) {
15520:             unless (&host_domain($lonid) eq $defdom) {
15521:                 return;
15522:             }
15523:         } else {
15524:             return;
15525:         }
15526:     } elsif (!defined(&hostname($lonid))) {
15527:         return;
15528:     }
15529:     my ($landing,$cached) = &is_cached_new('samllanding',$lonid);
15530:     if ($cached) {
15531:         return $landing;
15532:     }
15533:     my $dom = &host_domain($lonid);
15534:     if ($dom ne '') {
15535:         my $cachetime = 60*60*24;
15536:         my %domconfig =
15537:             &get_dom('configuration',['login'],$dom);
15538:         if (ref($domconfig{'login'}) eq 'HASH') {
15539:             if (ref($domconfig{'login'}{'saml'}) eq 'HASH') {
15540:                 if (ref($domconfig{'login'}{'saml'}{$lonid}) eq 'HASH') {
15541:                     $landing = 1;
15542:                 }
15543:             }
15544:         }
15545:         return &do_cache_new('samllanding',$lonid,$landing,$cachetime);
15546:     }
15547:     return;
15548: }
15549: 
15550: # ------------------------------------------------------------- Declutters URLs
15551: 
15552: sub declutter {
15553:     my $thisfn=shift;
15554:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
15555:     unless ($thisfn=~m{^/home/httpd/html/priv/}) {
15556:         $thisfn=~s{^/home/httpd/html}{};
15557:     }
15558:     $thisfn=~s/^\///;
15559:     $thisfn=~s|^adm/wrapper/||;
15560:     $thisfn=~s|^adm/coursedocs/showdoc/||;
15561:     $thisfn=~s/^res\///;
15562:     $thisfn=~s/^priv\///;
15563:     unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
15564:         $thisfn=~s/\?.+$//;
15565:     }
15566:     return $thisfn;
15567: }
15568: 
15569: # ------------------------------------------------------------- Clutter up URLs
15570: 
15571: sub clutter {
15572:     my $thisfn='/'.&declutter(shift);
15573:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
15574: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
15575:        $thisfn='/res'.$thisfn; 
15576:     }
15577:     if ($thisfn !~m|^/adm|) {
15578: 	if ($thisfn =~ m|^/ext/|) {
15579: 	    $thisfn='/adm/wrapper'.$thisfn;
15580: 	} else {
15581: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
15582: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
15583: 	    if ($embstyle eq 'ssi'
15584: 		|| ($embstyle eq 'hdn')
15585: 		|| ($embstyle eq 'rat')
15586: 		|| ($embstyle eq 'prv')
15587: 		|| ($embstyle eq 'ign')) {
15588: 		#do nothing with these
15589: 	    } elsif (($embstyle eq 'img') 
15590: 		|| ($embstyle eq 'emb')
15591: 		|| ($embstyle eq 'wrp')) {
15592: 		$thisfn='/adm/wrapper'.$thisfn;
15593: 	    } elsif ($embstyle eq 'unk'
15594: 		     && $thisfn!~/\.(sequence|page)$/) {
15595: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
15596: 	    } else {
15597: #		&logthis("Got a blank emb style");
15598: 	    }
15599: 	}
15600:     } elsif ($thisfn =~ m{^/adm/$match_domain/$match_courseid/\d+/ext\.tool$}) {
15601:         $thisfn='/adm/wrapper'.$thisfn;
15602:     }
15603:     return $thisfn;
15604: }
15605: 
15606: sub clutter_with_no_wrapper {
15607:     my $uri = &clutter(shift);
15608:     if ($uri =~ m-^/adm/-) {
15609: 	$uri =~ s-^/adm/wrapper/-/-;
15610: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
15611:     }
15612:     return $uri;
15613: }
15614: 
15615: sub freeze_escape {
15616:     my ($value)=@_;
15617:     if (ref($value)) {
15618: 	$value=&nfreeze($value);
15619: 	return '__FROZEN__'.&escape($value);
15620:     }
15621:     return &escape($value);
15622: }
15623: 
15624: 
15625: sub thaw_unescape {
15626:     my ($value)=@_;
15627:     if ($value =~ /^__FROZEN__/) {
15628: 	substr($value,0,10,undef);
15629: 	$value=&unescape($value);
15630: 	return &thaw($value);
15631:     }
15632:     return &unescape($value);
15633: }
15634: 
15635: sub correct_line_ends {
15636:     my ($result)=@_;
15637:     $$result =~s/\r\n/\n/mg;
15638:     $$result =~s/\r/\n/mg;
15639: }
15640: # ================================================================ Main Program
15641: 
15642: sub goodbye {
15643:    &logthis("Starting Shut down");
15644: #not converted to using infrastruture and probably shouldn't be
15645:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
15646: #converted
15647: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
15648:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
15649: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
15650: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
15651: #1.1 only
15652: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
15653: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
15654: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
15655: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
15656:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
15657:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
15658:    &logthis(sprintf("%-20s is %s",'hits',$hits));
15659:    &flushcourselogs();
15660:    &logthis("Shutting down");
15661: }
15662: 
15663: sub get_dns {
15664:     my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
15665:     if (!$ignore_cache) {
15666: 	my ($content,$cached)=
15667: 	    &is_cached_new('dns',$url);
15668: 	if ($cached) {
15669: 	    &$func($content,$hashref);
15670: 	    return;
15671: 	}
15672:     }
15673: 
15674:     my %alldns;
15675:     if (open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab")) {
15676:         foreach my $dns (<$config>) {
15677: 	    next if ($dns !~ /^\^(\S*)/x);
15678:             my $line = $1;
15679:             my ($host,$protocol) = split(/:/,$line);
15680:             if ($protocol ne 'https') {
15681:                 $protocol = 'http';
15682:             }
15683: 	    $alldns{$host} = $protocol;
15684:         }
15685:         close($config);
15686:     }
15687:     while (%alldns) {
15688: 	my ($dns) = sort { $b cmp $a } keys(%alldns);
15689:         my ($contents,@content);
15690:         if ($dns eq Sys::Hostname::FQDN::fqdn()) {
15691:             my $command = (split('/',$url))[3];
15692:             my ($dir,$file) = &parse_getdns_url($command,$url);
15693:             delete($alldns{$dns});
15694:             next if (($dir eq '') || ($file eq ''));
15695:             if (open(my $config,'<',"$dir/$file")) {
15696:                 @content = <$config>;
15697:                 close($config);
15698:             }
15699:             if ($url eq '/adm/dns/loncapaCRL') {
15700:                 $contents = join('',@content);
15701:             }
15702:         } else {
15703: 	    my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
15704:             my $response = &LONCAPA::LWPReq::makerequest('',$request,'',\%perlvar,30,0);
15705:             delete($alldns{$dns});
15706: 	    next if ($response->is_error());
15707:             if ($url eq '/adm/dns/loncapaCRL') {
15708:                 $contents = $response->content;
15709:             } else {
15710:                 @content = split("\n",$response->content);
15711:             }
15712:         }
15713:         if ($url eq '/adm/dns/loncapaCRL') {
15714:             return &$func($contents);
15715:         } else {
15716: 	    unless ($nocache) {
15717: 	        &do_cache_new('dns',$url,\@content,30*24*60*60);
15718: 	    }
15719: 	    &$func(\@content,$hashref);
15720:             return;
15721:         }
15722:     }
15723:     my $which = (split('/',$url,4))[3];
15724:     if ($which eq 'loncapaCRL') {
15725:         my $diskfile = "$perlvar{'lonCertificateDirectory'}/$perlvar{'lonnetCertRevocationList'}";
15726:         if (-e $diskfile) {
15727:             &logthis("unable to contact DNS, on disk file $diskfile not updated");
15728:         } else {
15729:             &logthis("unable to contact DNS, no on disk file $diskfile available");
15730:         }
15731:     } else {
15732:         &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
15733:         if (open(my $config,"<","$perlvar{'lonTabDir'}/dns_$which.tab")) {
15734:             my @content = <$config>;
15735:             close($config);
15736:             &$func(\@content,$hashref);
15737:         }
15738:     }
15739:     return;
15740: }
15741: 
15742: # ------------------------------------------------------Get DNS checksums file
15743: sub parse_dns_checksums_tab {
15744:     my ($lines,$hashref) = @_;
15745:     my $lonhost = $perlvar{'lonHostID'};
15746:     my $machine_dom = &host_domain($lonhost);
15747:     my $loncaparev = &get_server_loncaparev($machine_dom);
15748:     my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
15749:     my $webconfdir = '/etc/httpd/conf';
15750:     if ($distro =~ /^(ubuntu|debian)(\d+)$/) {
15751:         $webconfdir = '/etc/apache2';
15752:     } elsif ($distro =~ /^sles(\d+)$/) {
15753:         if ($1 >= 10) {
15754:             $webconfdir = '/etc/apache2';
15755:         }
15756:     } elsif ($distro =~ /^suse(\d+\.\d+)$/) {
15757:         if ($1 >= 10.0) {
15758:             $webconfdir = '/etc/apache2';
15759:         }
15760:     }
15761:     my ($release,$timestamp) = split(/\-/,$loncaparev);
15762:     my (%chksum,%revnum);
15763:     if (ref($lines) eq 'ARRAY') {
15764:         chomp(@{$lines});
15765:         my $version = shift(@{$lines});
15766:         if ($version eq $release) {  
15767:             foreach my $line (@{$lines}) {
15768:                 my ($file,$version,$shasum) = split(/,/,$line);
15769:                 if ($file =~ m{^/etc/httpd/conf}) {
15770:                     if ($webconfdir eq '/etc/apache2') {
15771:                         $file =~ s{^\Q/etc/httpd/conf/\E}{$webconfdir/};
15772:                     }
15773:                 }
15774:                 $chksum{$file} = $shasum;
15775:                 $revnum{$file} = $version;
15776:             }
15777:             if (ref($hashref) eq 'HASH') {
15778:                 %{$hashref} = (
15779:                                 sums     => \%chksum,
15780:                                 versions => \%revnum,
15781:                               );
15782:             }
15783:         }
15784:     }
15785:     return;
15786: }
15787: 
15788: sub fetch_dns_checksums {
15789:     my %checksums;
15790:     my $machine_dom = &host_domain($perlvar{'lonHostID'});
15791:     my $loncaparev = &get_server_loncaparev($machine_dom,$perlvar{'lonHostID'});
15792:     my ($release,$timestamp) = split(/\-/,$loncaparev);
15793:     &get_dns("/adm/dns/checksums/$release",\&parse_dns_checksums_tab,1,1,
15794:              \%checksums);
15795:     return \%checksums;
15796: }
15797: 
15798: sub fetch_crl_pemfile {
15799:     return &get_dns("/adm/dns/loncapaCRL",\&save_crl_pem,1,1);
15800: }
15801: 
15802: sub save_crl_pem {
15803:     my ($content) = @_;
15804:     my ($msg,$hadchanges);
15805:     if ($content ne '') {
15806:         my $now = time;
15807:         my $lonca = $perlvar{'lonCertificateDirectory'}.'/'.$perlvar{'lonnetCertificateAuthority'};
15808:         my $tmpcrl = $tmpdir.'/'.$perlvar{'lonnetCertRevocationList'}.'_'.$now.'.'.$$.'.tmp';
15809:         if (open(my $fh,'>',"$tmpcrl")) {
15810:             print $fh $content;
15811:             close($fh);
15812:             if (-e $lonca) {
15813:                 if (open(PIPE,"openssl crl -in $tmpcrl -inform pem -CAfile $lonca -noout 2>&1 |")) {
15814:                     my $check = <PIPE>;
15815:                     close(PIPE);
15816:                     chomp($check);
15817:                     if ($check eq 'verify OK') {
15818:                         my $dest = "$perlvar{'lonCertificateDirectory'}/$perlvar{'lonnetCertRevocationList'}";
15819:                         my $backup;
15820:                         if (-e $dest) {
15821:                             if (&File::Copy::move($dest,"$dest.bak")) {
15822:                                 $backup = 'ok';
15823:                             }
15824:                         }
15825:                         if (&File::Copy::move($tmpcrl,$dest)) {
15826:                             $msg = 'ok';
15827:                             if ($backup) {
15828:                                 my (%oldnums,%newnums);
15829:                                 if (open(PIPE, "openssl crl -inform PEM -text -noout -in $dest.bak |grep 'Serial Number' |")) {
15830:                                     while (<PIPE>) {
15831:                                         $oldnums{(split(/:/))[1]} = 1;
15832:                                     }
15833:                                     close(PIPE);
15834:                                 }
15835:                                 if (open(PIPE, "openssl crl -inform PEM -text -noout -in $dest |grep 'Serial Number' |")) {
15836:                                     while(<PIPE>) {
15837:                                         $newnums{(split(/:/))[1]} = 1;
15838:                                     }
15839:                                     close(PIPE);
15840:                                 }
15841:                                 foreach my $key (sort {$b <=> $a } (keys(%newnums))) {
15842:                                     unless (exists($oldnums{$key})) {
15843:                                         $hadchanges = 1;
15844:                                         last;
15845:                                     }
15846:                                 }
15847:                                 unless ($hadchanges) {
15848:                                     foreach my $key (sort {$b <=> $a } (keys(%oldnums))) {
15849:                                         unless (exists($newnums{$key})) {
15850:                                             $hadchanges = 1;
15851:                                             last;
15852:                                         }
15853:                                     }
15854:                                 }
15855:                             }
15856:                         }
15857:                     } else {
15858:                         unlink($tmpcrl);
15859:                     }
15860:                 } else {
15861:                     unlink($tmpcrl);
15862:                 }
15863:             } else {
15864:                 unlink($tmpcrl);
15865:             }
15866:         }
15867:     }
15868:     return ($msg,$hadchanges);
15869: }
15870: 
15871: sub parse_getdns_url {
15872:     my ($command,$url) = @_;
15873:     my $dir = $perlvar{'lonTabDir'};
15874:     my $file;
15875:     if ($command eq 'hosts') {
15876:         $file = 'dns_hosts.tab';
15877:     } elsif ($command eq 'domain') {
15878:         $file = 'dns_domain.tab';
15879:     } elsif ($command eq 'checksums') {
15880:         my $version = (split('/',$url))[4];
15881:         $file = "dns_checksums/$version.tab",
15882:     } elsif ($command eq 'loncapaCRL') {
15883:         $dir = $perlvar{'lonCertificateDirectory'};
15884:         $file = $perlvar{'lonnetCertRevocationList'};
15885:     }
15886:     return ($dir,$file);
15887: }
15888: 
15889: # ------------------------------------------------------------ Read domain file
15890: {
15891:     my $loaded;
15892:     my %domain;
15893: 
15894:     sub parse_domain_tab {
15895: 	my ($lines) = @_;
15896: 	foreach my $line (@$lines) {
15897: 	    next if ($line =~ /^(\#|\s*$ )/x);
15898: 
15899: 	    chomp($line);
15900: 	    my ($name,@elements) = split(/:/,$line,9);
15901: 	    my %this_domain;
15902: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
15903: 			       'lang_def', 'city', 'longi', 'lati',
15904: 			       'primary') {
15905: 		$this_domain{$field} = shift(@elements);
15906: 	    }
15907: 	    $domain{$name} = \%this_domain;
15908: 	}
15909:     }
15910: 
15911:     sub reset_domain_info {
15912: 	undef($loaded);
15913: 	undef(%domain);
15914:     }
15915: 
15916:     sub load_domain_tab {
15917: 	my ($ignore_cache,$nocache) = @_;
15918: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache,$nocache);
15919: 	my $fh;
15920: 	if (open($fh,"<",$perlvar{'lonTabDir'}.'/domain.tab')) {
15921: 	    my @lines = <$fh>;
15922: 	    &parse_domain_tab(\@lines);
15923: 	}
15924: 	close($fh);
15925: 	$loaded = 1;
15926:     }
15927: 
15928:     sub domain {
15929: 	&load_domain_tab() if (!$loaded);
15930: 
15931: 	my ($name,$what) = @_;
15932: 	return if ( !exists($domain{$name}) );
15933: 
15934: 	if (!$what) {
15935: 	    return $domain{$name}{'description'};
15936: 	}
15937: 	return $domain{$name}{$what};
15938:     }
15939: 
15940:     sub domain_info {
15941:         &load_domain_tab() if (!$loaded);
15942:         return %domain;
15943:     }
15944: 
15945: }
15946: 
15947: 
15948: # ------------------------------------------------------------- Read hosts file
15949: {
15950:     my %hostname;
15951:     my %hostdom;
15952:     my %libserv;
15953:     my $loaded;
15954:     my %name_to_host;
15955:     my %internetdom;
15956:     my %LC_dns_serv;
15957: 
15958:     sub parse_hosts_tab {
15959: 	my ($file) = @_;
15960: 	foreach my $configline (@$file) {
15961: 	    next if ($configline =~ /^(\#|\s*$ )/x);
15962:             chomp($configline);
15963: 	    if ($configline =~ /^\^/) {
15964:                 if ($configline =~ /^\^([\w.\-]+)/) {
15965:                     $LC_dns_serv{$1} = 1;
15966:                 }
15967:                 next;
15968:             }
15969: 	    my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
15970: 	    $name=~s/\s//g;
15971: 	    if ($id && $domain && $role && $name) {
15972:                 if ((exists($hostname{$id})) && ($hostname{$id} ne '')) {
15973:                     my $curr = $hostname{$id};
15974:                     my $skip;
15975:                     if (ref($name_to_host{$curr}) eq 'ARRAY') {
15976:                         if (($curr eq $name) && (@{$name_to_host{$curr}} == 1)) {
15977:                             $skip = 1;
15978:                         } else {
15979:                             @{$name_to_host{$curr}} = grep { $_ ne $id } @{$name_to_host{$curr}};
15980:                         }
15981:                     }
15982:                     unless ($skip) {
15983:                         push(@{$name_to_host{$name}},$id);
15984:                     }
15985:                 } else {
15986:                     push(@{$name_to_host{$name}},$id);
15987:                 }
15988: 		$hostname{$id}=$name;
15989: 		$hostdom{$id}=$domain;
15990: 		if ($role eq 'library') { $libserv{$id}=$name; }
15991:                 if (defined($protocol)) {
15992:                     if ($protocol eq 'https') {
15993:                         $protocol{$id} = $protocol;
15994:                     } else {
15995:                         $protocol{$id} = 'http'; 
15996:                     }
15997:                 } else {
15998:                     $protocol{$id} = 'http';
15999:                 }
16000:                 if (defined($intdom)) {
16001:                     $internetdom{$id} = $intdom;
16002:                 }
16003: 	    }
16004: 	}
16005:     }
16006:     
16007:     sub reset_hosts_info {
16008: 	&purge_remembered();
16009: 	&reset_domain_info();
16010: 	&reset_hosts_ip_info();
16011:         undef(%internetdom);
16012: 	undef(%name_to_host);
16013: 	undef(%hostname);
16014: 	undef(%hostdom);
16015: 	undef(%libserv);
16016: 	undef($loaded);
16017:     }
16018: 
16019:     sub load_hosts_tab {
16020: 	my ($ignore_cache,$nocache) = @_;
16021: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache,$nocache);
16022: 	open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab");
16023: 	my @config = <$config>;
16024: 	&parse_hosts_tab(\@config);
16025: 	close($config);
16026: 	$loaded=1;
16027:     }
16028: 
16029:     sub hostname {
16030: 	&load_hosts_tab() if (!$loaded);
16031: 
16032: 	my ($lonid) = @_;
16033: 	return $hostname{$lonid};
16034:     }
16035: 
16036:     sub all_hostnames {
16037: 	&load_hosts_tab() if (!$loaded);
16038: 
16039: 	return %hostname;
16040:     }
16041: 
16042:     sub all_names {
16043:         my ($ignore_cache,$nocache) = @_;
16044: 	&load_hosts_tab($ignore_cache,$nocache) if (!$loaded);
16045: 
16046: 	return %name_to_host;
16047:     }
16048: 
16049:     sub all_host_domain {
16050:         &load_hosts_tab() if (!$loaded);
16051:         return %hostdom;
16052:     }
16053: 
16054:     sub all_host_intdom {
16055:         &load_hosts_tab() if (!$loaded);
16056:         return %internetdom;
16057:     }
16058: 
16059:     sub is_library {
16060: 	&load_hosts_tab() if (!$loaded);
16061: 
16062: 	return exists($libserv{$_[0]});
16063:     }
16064: 
16065:     sub all_library {
16066: 	&load_hosts_tab() if (!$loaded);
16067: 
16068: 	return %libserv;
16069:     }
16070: 
16071:     sub unique_library {
16072: 	#2x reverse removes all hostnames that appear more than once
16073:         my %unique = reverse &all_library();
16074:         return reverse %unique;
16075:     }
16076: 
16077:     sub get_servers {
16078: 	&load_hosts_tab() if (!$loaded);
16079: 
16080: 	my ($domain,$type) = @_;
16081: 	my %possible_hosts = ($type eq 'library') ? %libserv
16082: 	                                          : %hostname;
16083: 	my %result;
16084: 	if (ref($domain) eq 'ARRAY') {
16085: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
16086: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
16087: 		    $result{$host} = $hostname;
16088: 		}
16089: 	    }
16090: 	} else {
16091: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
16092: 		if ($hostdom{$host} eq $domain) {
16093: 		    $result{$host} = $hostname;
16094: 		}
16095: 	    }
16096: 	}
16097: 	return %result;
16098:     }
16099: 
16100:     sub get_unique_servers {
16101:         my %unique = reverse &get_servers(@_);
16102: 	return reverse %unique;
16103:     }
16104: 
16105:     sub host_domain {
16106: 	&load_hosts_tab() if (!$loaded);
16107: 
16108: 	my ($lonid) = @_;
16109: 	return $hostdom{$lonid};
16110:     }
16111: 
16112:     sub all_domains {
16113: 	&load_hosts_tab() if (!$loaded);
16114: 
16115: 	my %seen;
16116: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
16117: 	return @uniq;
16118:     }
16119: 
16120:     sub internet_dom {
16121:         &load_hosts_tab() if (!$loaded);
16122: 
16123:         my ($lonid) = @_;
16124:         return $internetdom{$lonid};
16125:     }
16126: 
16127:     sub is_LC_dns {
16128:         &load_hosts_tab() if (!$loaded);
16129: 
16130:         my ($hostname) = @_;
16131:         return exists($LC_dns_serv{$hostname});
16132:     }
16133: 
16134: }
16135: 
16136: { 
16137:     my %iphost;
16138:     my %name_to_ip;
16139:     my %lonid_to_ip;
16140: 
16141:     sub get_hosts_from_ip {
16142: 	my ($ip) = @_;
16143: 	my %iphosts = &get_iphost();
16144: 	if (ref($iphosts{$ip})) {
16145: 	    return @{$iphosts{$ip}};
16146: 	}
16147: 	return;
16148:     }
16149:     
16150:     sub reset_hosts_ip_info {
16151: 	undef(%iphost);
16152: 	undef(%name_to_ip);
16153: 	undef(%lonid_to_ip);
16154:     }
16155: 
16156:     sub get_host_ip {
16157: 	my ($lonid) = @_;
16158: 	if (exists($lonid_to_ip{$lonid})) {
16159: 	    return $lonid_to_ip{$lonid};
16160: 	}
16161: 	my $name=&hostname($lonid);
16162:    	my $ip = gethostbyname($name);
16163: 	return if (!$ip || length($ip) ne 4);
16164: 	$ip=inet_ntoa($ip);
16165: 	$name_to_ip{$name}   = $ip;
16166: 	$lonid_to_ip{$lonid} = $ip;
16167: 	return $ip;
16168:     }
16169:     
16170:     sub get_iphost {
16171: 	my ($ignore_cache,$nocache) = @_;
16172: 
16173: 	if (!$ignore_cache) {
16174: 	    if (%iphost) {
16175: 		return %iphost;
16176: 	    }
16177: 	    my ($ip_info,$cached)=
16178: 		&is_cached_new('iphost','iphost');
16179: 	    if ($cached) {
16180: 		%iphost      = %{$ip_info->[0]};
16181: 		%name_to_ip  = %{$ip_info->[1]};
16182: 		%lonid_to_ip = %{$ip_info->[2]};
16183: 		return %iphost;
16184: 	    }
16185: 	}
16186: 
16187: 	# get yesterday's info for fallback
16188: 	my %old_name_to_ip;
16189: 	my ($ip_info,$cached)=
16190: 	    &is_cached_new('iphost','iphost');
16191: 	if ($cached) {
16192: 	    %old_name_to_ip = %{$ip_info->[1]};
16193: 	}
16194: 
16195: 	my %name_to_host = &all_names($ignore_cache,$nocache);
16196: 	foreach my $name (keys(%name_to_host)) {
16197: 	    my $ip;
16198: 	    if (!exists($name_to_ip{$name})) {
16199: 		$ip = gethostbyname($name);
16200: 		if (!$ip || length($ip) ne 4) {
16201: 		    if (defined($old_name_to_ip{$name})) {
16202: 			$ip = $old_name_to_ip{$name};
16203: 			&logthis("Can't find $name defaulting to old $ip");
16204: 		    } else {
16205: 			&logthis("Name $name no IP found");
16206: 			next;
16207: 		    }
16208: 		} else {
16209: 		    $ip=inet_ntoa($ip);
16210: 		}
16211: 		$name_to_ip{$name} = $ip;
16212: 	    } else {
16213: 		$ip = $name_to_ip{$name};
16214: 	    }
16215: 	    foreach my $id (@{ $name_to_host{$name} }) {
16216: 		$lonid_to_ip{$id} = $ip;
16217: 	    }
16218: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
16219: 	}
16220:         unless ($nocache) {
16221: 	    &do_cache_new('iphost','iphost',
16222: 		          [\%iphost,\%name_to_ip,\%lonid_to_ip],
16223: 		          48*60*60);
16224:         }
16225: 
16226: 	return %iphost;
16227:     }
16228: 
16229:     #
16230:     #  Given a DNS returns the loncapa host name for that DNS 
16231:     # 
16232:     sub host_from_dns {
16233:         my ($dns) = @_;
16234:         my @hosts;
16235:         my $ip;
16236: 
16237:         if (exists($name_to_ip{$dns})) {
16238:             $ip = $name_to_ip{$dns};
16239:         }
16240:         if (!$ip) {
16241:             $ip = gethostbyname($dns); # Initial translation to IP is in net order.
16242:             if (length($ip) == 4) { 
16243: 	        $ip   = &IO::Socket::inet_ntoa($ip);
16244:             }
16245:         }
16246:         if ($ip) {
16247: 	    @hosts = get_hosts_from_ip($ip);
16248: 	    return $hosts[0];
16249:         }
16250:         return undef;
16251:     }
16252: 
16253:     sub get_internet_names {
16254:         my ($lonid) = @_;
16255:         return if ($lonid eq '');
16256:         my ($idnref,$cached)=
16257:             &is_cached_new('internetnames',$lonid);
16258:         if ($cached) {
16259:             return $idnref;
16260:         }
16261:         my $ip = &get_host_ip($lonid);
16262:         my @hosts = &get_hosts_from_ip($ip);
16263:         my %iphost = &get_iphost();
16264:         my (@idns,%seen);
16265:         foreach my $id (@hosts) {
16266:             my $dom = &host_domain($id);
16267:             my $prim_id = &domain($dom,'primary');
16268:             my $prim_ip = &get_host_ip($prim_id);
16269:             next if ($seen{$prim_ip});
16270:             if (ref($iphost{$prim_ip}) eq 'ARRAY') {
16271:                 foreach my $id (@{$iphost{$prim_ip}}) {
16272:                     my $intdom = &internet_dom($id);
16273:                     unless (grep(/^\Q$intdom\E$/,@idns)) {
16274:                         push(@idns,$intdom);
16275:                     }
16276:                 }
16277:             }
16278:             $seen{$prim_ip} = 1;
16279:         }
16280:         return &do_cache_new('internetnames',$lonid,\@idns,12*60*60);
16281:     }
16282: 
16283: }
16284: 
16285: sub all_loncaparevs {
16286:     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);
16287: }
16288: 
16289: # ---------------------------------------------------------- Read loncaparev table
16290: {
16291:     sub load_loncaparevs { 
16292:         if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
16293:             if (open(my $config,"<","$perlvar{'lonTabDir'}/loncaparevs.tab")) {
16294:                 while (my $configline=<$config>) {
16295:                     chomp($configline);
16296:                     my ($hostid,$loncaparev)=split(/:/,$configline);
16297:                     $loncaparevs{$hostid}=$loncaparev;
16298:                 }
16299:                 close($config);
16300:             }
16301:         }
16302:     }
16303: }
16304: 
16305: # ---------------------------------------------------------- Read serverhostID table
16306: {
16307:     sub load_serverhomeIDs {
16308:         if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
16309:             if (open(my $config,"<","$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
16310:                 while (my $configline=<$config>) {
16311:                     chomp($configline);
16312:                     my ($name,$id)=split(/:/,$configline);
16313:                     $serverhomeIDs{$name}=$id;
16314:                 }
16315:                 close($config);
16316:             }
16317:         }
16318:     }
16319: }
16320: 
16321: 
16322: BEGIN {
16323: 
16324: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
16325:     unless ($readit) {
16326: {
16327:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
16328:     %perlvar = (%perlvar,%{$configvars});
16329: }
16330: 
16331: 
16332: # ------------------------------------------------------ Read spare server file
16333: {
16334:     open(my $config,"<","$perlvar{'lonTabDir'}/spare.tab");
16335: 
16336:     while (my $configline=<$config>) {
16337:        chomp($configline);
16338:        if ($configline) {
16339: 	   my ($host,$type) = split(':',$configline,2);
16340: 	   if (!defined($type) || $type eq '') { $type = 'default' };
16341: 	   push(@{ $spareid{$type} }, $host);
16342:        }
16343:     }
16344:     close($config);
16345: }
16346: # ------------------------------------------------------------ Read permissions
16347: {
16348:     open(my $config,"<","$perlvar{'lonTabDir'}/roles.tab");
16349: 
16350:     while (my $configline=<$config>) {
16351: 	chomp($configline);
16352: 	if ($configline) {
16353: 	    my ($role,$perm)=split(/ /,$configline);
16354: 	    if ($perm ne '') { $pr{$role}=$perm; }
16355: 	}
16356:     }
16357:     close($config);
16358: }
16359: 
16360: # -------------------------------------------- Read plain texts for permissions
16361: {
16362:     open(my $config,"<","$perlvar{'lonTabDir'}/rolesplain.tab");
16363: 
16364:     while (my $configline=<$config>) {
16365: 	chomp($configline);
16366: 	if ($configline) {
16367: 	    my ($short,@plain)=split(/:/,$configline);
16368:             %{$prp{$short}} = ();
16369: 	    if (@plain > 0) {
16370:                 $prp{$short}{'std'} = $plain[0];
16371:                 for (my $i=1; $i<@plain; $i++) {
16372:                     $prp{$short}{'alt'.$i} = $plain[$i];  
16373:                 }
16374:             }
16375: 	}
16376:     }
16377:     close($config);
16378: }
16379: 
16380: # ---------------------------------------------------------- Read package table
16381: {
16382:     open(my $config,"<","$perlvar{'lonTabDir'}/packages.tab");
16383: 
16384:     while (my $configline=<$config>) {
16385: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
16386: 	chomp($configline);
16387: 	my ($short,$plain)=split(/:/,$configline);
16388: 	my ($pack,$name)=split(/\&/,$short);
16389: 	if ($plain ne '') {
16390: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
16391: 	    $packagetab{$short}=$plain; 
16392: 	}
16393:     }
16394:     close($config);
16395: }
16396: 
16397: # ---------------------------------------------------------- Read loncaparev table
16398: 
16399: &load_loncaparevs();
16400: 
16401: # ---------------------------------------------------------- Read serverhostID table
16402: 
16403: &load_serverhomeIDs();
16404: 
16405: # ---------------------------------------------------------- Read releaseslist XML
16406: {
16407:     my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
16408:     if (-e $file) {
16409:         my $parser = HTML::LCParser->new($file);
16410:         while (my $token = $parser->get_token()) {
16411:             if ($token->[0] eq 'S') {
16412:                 my $item = $token->[1];
16413:                 my $name = $token->[2]{'name'};
16414:                 my $value = $token->[2]{'value'};
16415:                 my $valuematch = $token->[2]{'valuematch'};
16416:                 my $namematch = $token->[2]{'namematch'};
16417:                 if ($item eq 'parameter') {
16418:                     if (($namematch ne '') || (($name ne '') && ($value ne '' || $valuematch ne ''))) {
16419:                         my $release = $parser->get_text();
16420:                         $release =~ s/(^\s*|\s*$ )//gx;
16421:                         $needsrelease{$item.':'.$name.':'.$value.':'.$valuematch.':'.$namematch} = $release;
16422:                     }
16423:                 } elsif ($item ne '' && $name ne '') {
16424:                     my $release = $parser->get_text();
16425:                     $release =~ s/(^\s*|\s*$ )//gx;
16426:                     $needsrelease{$item.':'.$name.':'.$value} = $release;
16427:                 }
16428:             }
16429:         }
16430:     }
16431: }
16432: 
16433: # ---------------------------------------------------------- Read managers table
16434: {
16435:     if (-e "$perlvar{'lonTabDir'}/managers.tab") {
16436:         if (open(my $config,"<","$perlvar{'lonTabDir'}/managers.tab")) {
16437:             while (my $configline=<$config>) {
16438:                 chomp($configline);
16439:                 next if ($configline =~ /^\#/);
16440:                 if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
16441:                     $managerstab{$configline} = 1;
16442:                 }
16443:             }
16444:             close($config);
16445:         }
16446:     }
16447: }
16448: 
16449: # ------------- set up temporary directory
16450: {
16451:     $tmpdir = LONCAPA::tempdir();
16452: 
16453: }
16454: 
16455: # ------------- set default texengine (domain default overrides this)
16456: {
16457:     $deftex = LONCAPA::texengine();
16458: }
16459: 
16460: # ------------- set default minimum length for passwords for internal auth users
16461: {
16462:     $passwdmin = LONCAPA::passwd_min();
16463: }
16464: 
16465: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
16466: 				'compress_threshold'=> 20_000,
16467:  			        });
16468: 
16469: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
16470: $dumpcount=0;
16471: $locknum=0;
16472: 
16473: &logtouch();
16474: &logthis('<font color="yellow">INFO: Read configuration</font>');
16475: $readit=1;
16476:     {
16477: 	use integer;
16478: 	my $test=(2**32)+1;
16479: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
16480: 	&logthis(" Detected 64bit platform ($_64bit)");
16481:     }
16482: }
16483: }
16484: 
16485: 1;
16486: __END__
16487: 
16488: =pod
16489: 
16490: =head1 NAME
16491: 
16492: Apache::lonnet - Subroutines to ask questions about things in the network.
16493: 
16494: =head1 SYNOPSIS
16495: 
16496: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
16497: 
16498:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
16499: 
16500: Common parameters:
16501: 
16502: =over 4
16503: 
16504: =item *
16505: 
16506: $uname : an internal username (if $cname expecting a course Id specifically)
16507: 
16508: =item *
16509: 
16510: $udom : a domain (if $cdom expecting a course's domain specifically)
16511: 
16512: =item *
16513: 
16514: $symb : a resource instance identifier
16515: 
16516: =item *
16517: 
16518: $namespace : the name of a .db file that contains the data needed or
16519: being set.
16520: 
16521: =back
16522: 
16523: =head1 OVERVIEW
16524: 
16525: lonnet provides subroutines which interact with the
16526: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
16527: about classes, users, and resources.
16528: 
16529: For many of these objects you can also use this to store data about
16530: them or modify them in various ways.
16531: 
16532: =head2 Symbs
16533: 
16534: To identify a specific instance of a resource, LON-CAPA uses symbols
16535: or "symbs"X<symb>. These identifiers are built from the URL of the
16536: map, the resource number of the resource in the map, and the URL of
16537: the resource itself. The latter is somewhat redundant, but might help
16538: if maps change.
16539: 
16540: An example is
16541: 
16542:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
16543: 
16544: The respective map entry is
16545: 
16546:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
16547:   title="Problem 2">
16548:  </resource>
16549: 
16550: Symbs are used by the random number generator, as well as to store and
16551: restore data specific to a certain instance of for example a problem.
16552: 
16553: =head2 Storing And Retrieving Data
16554: 
16555: X<store()>X<cstore()>X<restore()>Three of the most important functions
16556: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
16557: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
16558: is is the non-critical message twin of cstore. These functions are for
16559: handlers to store a perl hash to a user's permanent data space in an
16560: easy manner, and to retrieve it again on another call. It is expected
16561: that a handler would use this once at the beginning to retrieve data,
16562: and then again once at the end to send only the new data back.
16563: 
16564: The data is stored in the user's data directory on the user's
16565: homeserver under the ID of the course.
16566: 
16567: The hash that is returned by restore will have all of the previous
16568: value for all of the elements of the hash.
16569: 
16570: Example:
16571: 
16572:  #creating a hash
16573:  my %hash;
16574:  $hash{'foo'}='bar';
16575: 
16576:  #storing it
16577:  &Apache::lonnet::cstore(\%hash);
16578: 
16579:  #changing a value
16580:  $hash{'foo'}='notbar';
16581: 
16582:  #adding a new value
16583:  $hash{'bar'}='foo';
16584:  &Apache::lonnet::cstore(\%hash);
16585: 
16586:  #retrieving the hash
16587:  my %history=&Apache::lonnet::restore();
16588: 
16589:  #print the hash
16590:  foreach my $key (sort(keys(%history))) {
16591:    print("\%history{$key} = $history{$key}");
16592:  }
16593: 
16594: Will print out:
16595: 
16596:  %history{1:foo} = bar
16597:  %history{1:keys} = foo:timestamp
16598:  %history{1:timestamp} = 990455579
16599:  %history{2:bar} = foo
16600:  %history{2:foo} = notbar
16601:  %history{2:keys} = foo:bar:timestamp
16602:  %history{2:timestamp} = 990455580
16603:  %history{bar} = foo
16604:  %history{foo} = notbar
16605:  %history{timestamp} = 990455580
16606:  %history{version} = 2
16607: 
16608: Note that the special hash entries C<keys>, C<version> and
16609: C<timestamp> were added to the hash. C<version> will be equal to the
16610: total number of versions of the data that have been stored. The
16611: C<timestamp> attribute will be the UNIX time the hash was
16612: stored. C<keys> is available in every historical section to list which
16613: keys were added or changed at a specific historical revision of a
16614: hash.
16615: 
16616: B<Warning>: do not store the hash that restore returns directly. This
16617: will cause a mess since it will restore the historical keys as if the
16618: were new keys. I.E. 1:foo will become 1:1:foo etc.
16619: 
16620: Calling convention:
16621: 
16622:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname);
16623:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$laststore);
16624: 
16625: For more detailed information, see lonnet specific documentation.
16626: 
16627: =head1 RETURN MESSAGES
16628: 
16629: =over 4
16630: 
16631: =item * B<con_lost>: unable to contact remote host
16632: 
16633: =item * B<con_delayed>: unable to contact remote host, message will be delivered
16634: when the connection is brought back up
16635: 
16636: =item * B<con_failed>: unable to contact remote host and unable to save message
16637: for later delivery
16638: 
16639: =item * B<error:>: an error a occurred, a description of the error follows the :
16640: 
16641: =item * B<no_such_host>: unable to fund a host associated with the user/domain
16642: that was requested
16643: 
16644: =back
16645: 
16646: =head1 PUBLIC SUBROUTINES
16647: 
16648: =head2 Session Environment Functions
16649: 
16650: =over 4
16651: 
16652: =item * 
16653: X<appenv()>
16654: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
16655: the user envirnoment file, and will be restored for each access this
16656: user makes during this session, also modifies the %env for the current
16657: process. Optional rolesarrayref - if defined contains a reference to an array
16658: of roles which are exempt from the restriction on modifying user.role entries 
16659: in the user's environment.db and in %env.    
16660: 
16661: =item *
16662: X<delenv()>
16663: B<delenv($delthis,$regexp)>: removes all items from the session
16664: environment file that begin with $delthis. If the 
16665: optional second arg - $regexp - is true, $delthis is treated as a 
16666: regular expression, otherwise \Q$delthis\E is used. 
16667: The values are also deleted from the current processes %env.
16668: 
16669: =item * get_env_multiple($name) 
16670: 
16671: gets $name from the %env hash, it seemlessly handles the cases where multiple
16672: values may be defined and end up as an array ref.
16673: 
16674: returns an array of values
16675: 
16676: =back
16677: 
16678: =head2 User Information
16679: 
16680: =over 4
16681: 
16682: =item *
16683: X<queryauthenticate()>
16684: B<queryauthenticate($uname,$udom)>: try to determine user's current 
16685: authentication scheme
16686: 
16687: =item *
16688: X<authenticate()>
16689: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
16690: authenticate user from domain's lib servers (first use the current
16691: one). C<$upass> should be the users password.
16692: $checkdefauth is optional (value is 1 if a check should be made to
16693:    authenticate user using default authentication method, and allow
16694:    account creation if username does not have account in the domain).
16695: $clientcancheckhost is optional (value is 1 if checking whether the
16696:    server can host will occur on the client side in lonauth.pm).   
16697: 
16698: =item *
16699: X<homeserver()>
16700: B<homeserver($uname,$udom)>: find the server which has
16701: the user's directory and files (there must be only one), this caches
16702: the answer, and also caches if there is a borken connection.
16703: 
16704: =item *
16705: X<idget()>
16706: B<idget($udom,$idsref,$namespace)>: find the usernames behind either 
16707: a list of student/employee IDs or clicker IDs
16708: (student/employee IDs are a unique resource in a domain, there must be 
16709: only 1 ID per username, and only 1 username per ID in a specific domain).
16710: clickerIDs are not necessarily unique, as students might share clickers.
16711: (returns hash: id=>name,id=>name)
16712: 
16713: =item *
16714: X<idrget()>
16715: B<idrget($udom,@unames)>: find the IDs behind a list of
16716: usernames (returns hash: name=>id,name=>id)
16717: 
16718: =item *
16719: X<idput()>
16720: B<idput($udom,$idsref,$uhome,$namespace)>: store away a list of 
16721: names and associated student/employee IDs or clicker IDs.
16722: 
16723: =item *
16724: X<iddel()>
16725: B<iddel($udom,$idshashref,$uhome,$namespace)>: delete unwanted 
16726: student/employee ID or clicker ID username look-ups from domain.
16727: The homeserver ($uhome) and namespace ($namespace) are optional.
16728: If no $uhome is provided, it will be determined usig &homeserver()
16729: for each user.  If no $namespace is provided, the default is ids.
16730: 
16731: =item *
16732: X<updateclickers()>
16733: B<updateclickers($udom,$action,$idshashref,$uhome,$critical)>: update 
16734: clicker ID-to-username look-ups in clickers.db on library server.
16735: Permitted actions are add or del (i.e., add or delete). The 
16736: clickers.db contains clickerID as keys (escaped), and each corresponding
16737: value is an escaped comma-separated list of usernames (for whom the
16738: library server is the homeserver), who registered that particular ID.
16739: If $critical is true, the update will be sent via &critical, otherwise
16740: &reply() will be used.
16741: 
16742: =item *
16743: X<rolesinit()>
16744: B<rolesinit($udom,$username)>: get user privileges.
16745: returns user role, first access and timer interval hashes
16746: 
16747: =item *
16748: X<privileged()>
16749: B<privileged($username,$domain)>: returns a true if user has a
16750: privileged and active role (i.e. su or dc), false otherwise.
16751: 
16752: =item *
16753: X<getsection()>
16754: B<getsection($udom,$uname,$cname)>: finds the section of student in the
16755: course $cname, return section name/number or '' for "not in course"
16756: and '-1' for "no section"
16757: 
16758: =item *
16759: X<userenvironment()>
16760: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
16761: passed in @what from the requested user's environment, returns a hash
16762: 
16763: =item * 
16764: X<userlog_query()>
16765: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
16766: activity.log file. %filters defines filters applied when parsing the
16767: log file. These can be start or end timestamps, or the type of action
16768: - log to look for Login or Logout events, check for Checkin or
16769: Checkout, role for role selection. The response is in the form
16770: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
16771: escaped strings of the action recorded in the activity.log file.
16772: 
16773: =back
16774: 
16775: =head2 User Roles
16776: 
16777: =over 4
16778: 
16779: =item *
16780: 
16781: allowed($priv,$uri,$symb,$role,$clientip,$noblockcheck) : check for a user privilege; 
16782: returns codes for allowed actions.
16783: 
16784: The first argument is required, all others are optional.
16785: 
16786: $priv is the privilege being checked.
16787: $uri contains additional information about what is being checked for access (e.g.,
16788: URL, course ID etc.). 
16789: $symb is the unique resource instance identifier in a course; if needed,
16790: but not provided, it will be retrieved via a call to &symbread(). 
16791: $role is the role for which a priv is being checked (only used if priv is evb). 
16792: $clientip is the user's IP address (only used when checking for access to portfolio 
16793: files).
16794: $noblockcheck, if true, skips calls to &has_comm_blocking() for the bre priv. This 
16795: prevents recursive calls to &allowed.
16796: 
16797:  F: full access
16798:  U,I,K: authentication modes (cxx only)
16799:  '': forbidden
16800:  1: user needs to choose course
16801:  2: browse allowed
16802:  A: passphrase authentication needed
16803:  B: access temporarily blocked because of a blocking event in a course.
16804:  D: access blocked because access is required via session initiated via deep-link 
16805: 
16806: =item *
16807: 
16808: constructaccess($url,$setpriv) : check for access to construction space URL
16809: 
16810: See if the owner domain and name in the URL match those in the
16811: expected environment.  If so, return three element list
16812: ($ownername,$ownerdomain,$ownerhome).
16813: 
16814: Otherwise return the null string.
16815: 
16816: If second argument 'setpriv' is true, it assigns the privileges,
16817: and returns the same three element list, unless the owner has
16818: blocked "ad hoc" Domain Coordinator access to the Author Space,
16819: in which case the null string is returned.
16820: 
16821: =item *
16822: 
16823: definerole($rolename,$sysrole,$domrole,$courole,$uname,$udom) : define role;
16824: define a custom role rolename set privileges in format of lonTabs/roles.tab
16825: for system, domain, and course level. $uname and $udom are optional (current
16826: user's username and domain will be used when either of $uname or $udom are absent.
16827: 
16828: =item *
16829: 
16830: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
16831: (rolesplain.tab); plain text explanation of a user role term.
16832: $type is Course (default) or Community.
16833: If $forcedefault evaluates to true, text returned will be default 
16834: text for $type. Otherwise, if this is a course, the text returned 
16835: will be a custom name for the role (if defined in the course's 
16836: environment).  If no custom name is defined the default is returned.
16837:    
16838: =item *
16839: 
16840: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv) :
16841: All arguments are optional. Returns a hash of a roles, either for
16842: co-author/assistant author roles for a user's Construction Space
16843: (default), or if $context is 'userroles', roles for the user himself,
16844: In the hash, keys are set to colon-separated $uname,$udom,$role, and
16845: (optionally) if $withsec is true, a fourth colon-separated item - $section.
16846: For each key, value is set to colon-separated start and end times for
16847: the role.  If no username and domain are specified, will default to
16848: current user/domain. Types, roles, and roledoms are references to arrays
16849: of role statuses (active, future or previous), roles 
16850: (e.g., cc,in, st etc.) and domains of the roles which can be used
16851: to restrict the list of roles reported. If no array ref is 
16852: provided for types, will default to return only active roles.
16853: 
16854: =item *
16855: 
16856: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
16857: user: $uname:$udom has a role in the course: $cdom_$cnum. 
16858: 
16859: Additional optional arguments are: $type (if role checking is to be restricted 
16860: to certain user status types -- previous (expired roles), active (currently
16861: available roles) or future (roles available in the future), and
16862: $hideprivileged -- if true will not report course roles for users who
16863: have active Domain Coordinator role in course's domain or in additional
16864: domains (specified in 'Domains to check for privileged users' in course
16865: environment -- set via:  Course Settings -> Classlists and staff listing).
16866: 
16867: =item *
16868: 
16869: privileged($username,$domain,$possdomains,$possroles) : returns 1 if user
16870: $username:$domain is a privileged user (e.g., Domain Coordinator or Super User)
16871: $possdomains and $possroles are optional array refs -- to domains to check and
16872: roles to check.  If $possdomains is not specified, a dump will be done of the
16873: users' roles.db to check for a dc or su role in any domain. This can be
16874: time consuming if &privileged is called repeatedly (e.g., when displaying a
16875: classlist), so in such cases, supplying a $possdomains array is preferred, as
16876: this then allows &privileged_by_domain() to be used, which caches the identity
16877: of privileged users, eliminating the need for repeated calls to &dump().
16878: 
16879: =item *
16880: 
16881: privileged_by_domain($possdomains,$roles) : returns a hash of a hash of a hash,
16882: where the outer hash keys are domains specified in the $possdomains array ref,
16883: next inner hash keys are privileged roles specified in the $roles array ref,
16884: and the innermost hash contains key = value pairs for username:domain = end:start
16885: for active or future "privileged" users with that role in that domain. To avoid
16886: repeated dumps of domain roles -- via &get_domain_roles() -- contents of the
16887: innerhash are cached using priv_$role and $dom as the identifiers.
16888: 
16889: =back
16890: 
16891: =head2 User Modification
16892: 
16893: =over 4
16894: 
16895: =item *
16896: 
16897: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
16898: user for the level given by URL.  Optional start and end dates (leave empty
16899: string or zero for "no date")
16900: 
16901: =item *
16902: 
16903: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
16904: change a users, password, possible return values are: ok,
16905: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
16906: refused
16907: 
16908: =item *
16909: 
16910: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
16911: 
16912: =item *
16913: 
16914: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
16915:            $forceid,$desiredhome,$email,$inststatus,$candelete) :
16916: 
16917: will update user information (firstname,middlename,lastname,generation,
16918: permanentemail), and if forceid is true, student/employee ID also.
16919: A user's institutional affiliation(s) can also be updated.
16920: User information fields will not be overwritten with empty entries 
16921: unless the field is included in the $candelete array reference.
16922: This array is included when a single user is modified via "Manage Users",
16923: or when Autoupdate.pl is run by cron in a domain.
16924: 
16925: =item *
16926: 
16927: modifystudent
16928: 
16929: modify a student's enrollment and identification information.
16930: The course id is resolved based on the current user's environment.  
16931: This means the invoking user must be a course coordinator or otherwise
16932: associated with a course.
16933: 
16934: This call is essentially a wrapper for lonnet::modifyuser and
16935: lonnet::modify_student_enrollment
16936: 
16937: Inputs: 
16938: 
16939: =over 4
16940: 
16941: =item B<$udom> Student's loncapa domain
16942: 
16943: =item B<$uname> Student's loncapa login name
16944: 
16945: =item B<$uid> Student/Employee ID
16946: 
16947: =item B<$umode> Student's authentication mode
16948: 
16949: =item B<$upass> Student's password
16950: 
16951: =item B<$first> Student's first name
16952: 
16953: =item B<$middle> Student's middle name
16954: 
16955: =item B<$last> Student's last name
16956: 
16957: =item B<$gene> Student's generation
16958: 
16959: =item B<$usec> Student's section in course
16960: 
16961: =item B<$end> Unix time of the roles expiration
16962: 
16963: =item B<$start> Unix time of the roles start date
16964: 
16965: =item B<$forceid> If defined, allow $uid to be changed
16966: 
16967: =item B<$desiredhome> server to use as home server for student
16968: 
16969: =item B<$email> Student's permanent e-mail address
16970: 
16971: =item B<$type> Type of enrollment (auto or manual)
16972: 
16973: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
16974: 
16975: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
16976: 
16977: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
16978: 
16979: =item B<$context> role change context (shown in User Management Logs display in a course)
16980: 
16981: =item B<$inststatus> institutional status of user - : separated string of escaped status types
16982: 
16983: =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.
16984: 
16985: =back
16986: 
16987: =item *
16988: 
16989: modify_student_enrollment
16990: 
16991: Change a student's enrollment status in a class.  The environment variable
16992: 'role.request.course' must be defined for this function to proceed.
16993: 
16994: Inputs:
16995: 
16996: =over 4
16997: 
16998: =item $udom, student's domain
16999: 
17000: =item $uname, student's name
17001: 
17002: =item $uid, student's user id
17003: 
17004: =item $first, student's first name
17005: 
17006: =item $middle
17007: 
17008: =item $last
17009: 
17010: =item $gene
17011: 
17012: =item $usec
17013: 
17014: =item $end
17015: 
17016: =item $start
17017: 
17018: =item $type
17019: 
17020: =item $locktype
17021: 
17022: =item $cid
17023: 
17024: =item $selfenroll
17025: 
17026: =item $context
17027: 
17028: =item $credits, number of credits student will earn from this class
17029: 
17030: =item $instsec, institutional course section code for student
17031: 
17032: =back
17033: 
17034: 
17035: =item *
17036: 
17037: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
17038: custom role; give a custom role to a user for the level given by URL.  Specify
17039: name and domain of role author, and role name
17040: 
17041: =item *
17042: 
17043: revokerole($udom,$uname,$url,$role) : revoke a role for url
17044: 
17045: =item *
17046: 
17047: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
17048: 
17049: =back
17050: 
17051: =head2 Course Infomation
17052: 
17053: =over 4
17054: 
17055: =item *
17056: 
17057: coursedescription($courseid,$options) : returns a hash of information about the
17058: specified course id, including all environment settings for the
17059: course, the description of the course will be in the hash under the
17060: key 'description'
17061: 
17062: $options is an optional parameter that if supplied is a hash reference that controls
17063: what how this function works.  It has the following key/values:
17064: 
17065: =over 4
17066: 
17067: =item freshen_cache
17068: 
17069: If defined, and the environment cache for the course is valid, it is 
17070: returned in the returned hash.
17071: 
17072: =item one_time
17073: 
17074: If defined, the last cache time is set to _now_
17075: 
17076: =item user
17077: 
17078: If defined, the supplied username is used instead of the current user.
17079: 
17080: 
17081: =back
17082: 
17083: =item *
17084: 
17085: resdata($name,$domain,$type,@which) : request for current parameter
17086: setting for a specific $type, where $type is either 'course' or 'user',
17087: @what should be a list of parameters to ask about. This routine caches
17088: answers for 10 minutes.
17089: 
17090: =item *
17091: 
17092: get_courseresdata($courseid, $domain) : dump the entire course resource
17093: data base, returning a hash that is keyed by the resource name and has
17094: values that are the resource value.  I believe that the timestamps and
17095: versions are also returned.
17096: 
17097: =back
17098: 
17099: =head2 Course Modification
17100: 
17101: =over 4
17102: 
17103: =item *
17104: 
17105: writecoursepref($courseid,%prefs) : write preferences (environment
17106: database) for a course
17107: 
17108: =item *
17109: 
17110: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
17111: 
17112: =item *
17113: 
17114: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
17115: 
17116: =item *
17117: 
17118: is_course($courseid), is_course($cdom, $cnum)
17119: 
17120: Accepts either a combined $courseid (in the form of domain_courseid) or the
17121: two component version $cdom, $cnum. It checks if the specified course exists.
17122: 
17123: Returns:
17124:     undef if the course doesn't exist, otherwise
17125:     in scalar context the combined courseid.
17126:     in list context the two components of the course identifier, domain and 
17127:     courseid.    
17128: 
17129: =back
17130: 
17131: =head2 Bubblesheet Configuration
17132: 
17133: =over 4
17134: 
17135: =item *
17136: 
17137: get_scantron_config($which)
17138: 
17139: $which - the name of the configuration to parse from the file.
17140: 
17141: Parses and returns the bubblesheet configuration line selected as a
17142: hash of configuration file fields.
17143: 
17144: 
17145: Returns:
17146:     If the named configuration is not in the file, an empty
17147:     hash is returned.
17148: 
17149:     a hash with the fields
17150:       name         - internal name for the this configuration setup
17151:       description  - text to display to operator that describes this config
17152:       CODElocation - if 0 or the string 'none'
17153:                           - no CODE exists for this config
17154:                      if -1 || the string 'letter'
17155:                           - a CODE exists for this config and is
17156:                             a string of letters
17157:                      Unsupported value (but planned for future support)
17158:                           if a positive integer
17159:                                - The CODE exists as the first n items from
17160:                                  the question section of the form
17161:                           if the string 'number'
17162:                                - The CODE exists for this config and is
17163:                                  a string of numbers
17164:       CODEstart   - (only matter if a CODE exists) column in the line where
17165:                      the CODE starts
17166:       CODElength  - length of the CODE
17167:       IDstart     - column where the student/employee ID starts
17168:       IDlength    - length of the student/employee ID info
17169:       Qstart      - column where the information from the bubbled
17170:                     'questions' start
17171:       Qlength     - number of columns comprising a single bubble line from
17172:                     the sheet. (usually either 1 or 10)
17173:       Qon         - either a single character representing the character used
17174:                     to signal a bubble was chosen in the positional setup, or
17175:                     the string 'letter' if the letter of the chosen bubble is
17176:                     in the final, or 'number' if a number representing the
17177:                     chosen bubble is in the file (1->A 0->J)
17178:       Qoff        - the character used to represent that a bubble was
17179:                     left blank
17180:       PaperID     - if the scanning process generates a unique number for each
17181:                     sheet scanned the column that this ID number starts in
17182:       PaperIDlength - number of columns that comprise the unique ID number
17183:                       for the sheet of paper
17184:       FirstName   - column that the first name starts in
17185:       FirstNameLength - number of columns that the first name spans
17186:       LastName    - column that the last name starts in
17187:       LastNameLength - number of columns that the last name spans
17188:       BubblesPerRow - number of bubbles available in each row used to
17189:                       bubble an answer. (If not specified, 10 assumed).
17190: 
17191: 
17192: =item *
17193: 
17194: get_scantronformat_file($cdom)
17195: 
17196: $cdom - the course's domain (optional); if not supplied, uses
17197: domain for current $env{'request.course.id'}.
17198: 
17199: Returns an array containing lines from the scantron format file for
17200: the domain of the course.
17201: 
17202: If a url for a custom.tab file is listed in domain's configuration.db,
17203: lines are from this file.
17204: 
17205: Otherwise, if a default.tab has been published in RES space by the
17206: domainconfig user, lines are from this file.
17207: 
17208: Otherwise, fall back to getting lines from the legacy file on the
17209: local server:  /home/httpd/lonTabs/default_scantronformat.tab
17210: 
17211: =back
17212: 
17213: =head2 Resource Subroutines
17214: 
17215: =over 4
17216: 
17217: =item *
17218: 
17219: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
17220: 
17221: =item *
17222: 
17223: repcopy($filename) : subscribes to the requested file, and attempts to
17224: replicate from the owning library server, Might return
17225: 'unavailable', 'not_found', 'forbidden', 'ok', or
17226: 'bad_request', also attempts to grab the metadata for the
17227: resource. Expects the local filesystem pathname
17228: (/home/httpd/html/res/....)
17229: 
17230: =back
17231: 
17232: =head2 Resource Information
17233: 
17234: =over 4
17235: 
17236: =item *
17237: 
17238: EXT($varname,$symb,$udom,$uname,$usection,$recurse,$cid) : evaluates 
17239: and returns the value of a variety of different possible values,
17240: $varname should be a request string, and the other parameters can be
17241: used to specify who and what one is asking about. Ordinarily, $cid 
17242: does not need to be specified, as it is retrived from 
17243: $env{'request.course.id'}, but &Apache::lonnet::EXT() is called
17244: within lonuserstate::loadmap() when initializing a course, before
17245: $env{'request.course.id'} has been set, so it needs to be provided
17246: in that one case.
17247: 
17248: Possible values for $varname are environment.lastname (or other item
17249: from the envirnment hash), user.name (or someother aspect about the
17250: user), resource.0.maxtries (or some other part and parameter of a
17251: resource)
17252: 
17253: =item *
17254: 
17255: directcondval($number) : get current value of a condition; reads from a state
17256: string
17257: 
17258: =item *
17259: 
17260: condval($condidx) : value of condition index based on state
17261: 
17262: =item *
17263: 
17264: metadata($uri,$what,$toolsymb,$liburi,$prefix,$depthcount) : request a
17265: resource's metadata, $what should be either a specific key, or either
17266: 'keys' (to get a list of possible keys) or 'packages' to get a list of
17267: packages that this resource currently uses, the last 3 arguments are 
17268: only used internally for recursive metadata.
17269: 
17270: the toolsymb is only used where the uri is for an external tool (for which
17271: the uri as well as the symb are guaranteed to be unique).
17272: 
17273: this function automatically caches all requests except any made recursively
17274: to retrieve a list of metadata keys for an imported library file ($liburi is 
17275: defined).
17276: 
17277: =item *
17278: 
17279: metadata_query($query,$custom,$customshow) : make a metadata query against the
17280: network of library servers; returns file handle of where SQL and regex results
17281: will be stored for query
17282: 
17283: =item *
17284: 
17285: symbread($filename,$donotrecurse,$ignorecachednull,$checkforblock,$possibles) : 
17286: return symbolic list entry (all arguments optional). 
17287: 
17288: Args: filename is the filename (including path) for the file for which a symb 
17289: is required; donotrecurse, if true will prevent calls to allowed() being made 
17290: to check access status if more than one resource was found in the bighash 
17291: (see rev. 1.249) to avoid an infinite loop if an ambiguous resource is part of 
17292: a randompick); ignorecachednull, if true will prevent a symb of '' being 
17293: returned if $env{$cache_str} is defined as ''; checkforblock if true will
17294: cause possible symbs to be checked to determine if they are subject to content
17295: blocking, if so they will not be included as possible symbs; possibles is a
17296: ref to a hash, which, as a side effect, will be populated with all possible 
17297: symbs (content blocking not tested).
17298:  
17299: returns the data handle
17300: 
17301: =item *
17302: 
17303: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
17304: and is a possible symb for the URL in $thisfn, and if is an encrypted
17305: resource that the user accessed using /enc/ returns a 1 on success, 0
17306: on failure, user must be in a course, as it assumes the existence of
17307: the course initial hash, and uses $env('request.course.id'}.  The third
17308: arg is an optional reference to a scalar.  If this arg is passed in the 
17309: call to symbverify, it will be set to 1 if the symb has been set to be 
17310: encrypted; otherwise it will be null.  
17311: 
17312: =item *
17313: 
17314: symbclean($symb) : removes versions numbers from a symb, returns the
17315: cleaned symb
17316: 
17317: =item *
17318: 
17319: is_on_map($uri) : checks if the $uri is somewhere on the current
17320: course map, user must be in a course for it to work.
17321: 
17322: =item *
17323: 
17324: numval($salt) : return random seed value (addend for rndseed)
17325: 
17326: =item *
17327: 
17328: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
17329: a random seed, all arguments are optional, if they aren't sent it uses the
17330: environment to derive them. Note: if symb isn't sent and it can't get one
17331: from &symbread it will use the current time as its return value
17332: 
17333: =item *
17334: 
17335: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
17336: unfakeable, receipt
17337: 
17338: =item *
17339: 
17340: receipt() : API to ireceipt working off of env values; given out to users
17341: 
17342: =item *
17343: 
17344: countacc($url) : count the number of accesses to a given URL
17345: 
17346: =item *
17347: 
17348: 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
17349: 
17350: =item *
17351: 
17352: 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)
17353: 
17354: =item *
17355: 
17356: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
17357: 
17358: =item *
17359: 
17360: devalidate($symb) : devalidate temporary spreadsheet calculations,
17361: forcing spreadsheet to reevaluate the resource scores next time.
17362: 
17363: =item * 
17364: 
17365: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
17366: when viewing in course context.
17367: 
17368:  input: six args -- filename (decluttered), course number, course domain,
17369:                     url, symb (if registered) and group (if this is a 
17370:                     group item -- e.g., bulletin board, group page etc.).
17371: 
17372:  output: array of five scalars --
17373:          $cfile -- url for file editing if editable on current server
17374:          $home -- homeserver of resource (i.e., for author if published,
17375:                                           or course if uploaded.).
17376:          $switchserver --  1 if server switch will be needed.
17377:          $forceedit -- 1 if icon/link should be to go to edit mode 
17378:          $forceview -- 1 if icon/link should be to go to view mode
17379: 
17380: =item *
17381: 
17382: is_course_upload($file,$cnum,$cdom)
17383: 
17384: Used in course context to determine if current file was uploaded to 
17385: the course (i.e., would be found in /userfiles/docs on the course's 
17386: homeserver.
17387: 
17388:   input: 3 args -- filename (decluttered), course number and course domain.
17389:   output: boolean -- 1 if file was uploaded.
17390: 
17391: =back
17392: 
17393: =head2 Storing/Retreiving Data
17394: 
17395: =over 4
17396: 
17397: =item *
17398: 
17399: store($storehash,$symb,$namespace,$udom,$uname,$laststore) : stores hash
17400: permanently for this url; hashref needs to be given and should be a \%hashname;
17401: the remaining args aren't required and if they aren't passed or are '' they will
17402: be derived from the env (with the exception of $laststore, which is an 
17403: optional arg used when a user's submission is stored in grading).
17404: $laststore is $version=$timestamp, where $version is the most recent version
17405: number retrieved for the corresponding $symb in the $namespace db file, and
17406: $timestamp is the timestamp for that transaction (UNIX time).
17407: $laststore is currently only passed when cstore() is called by 
17408: structuretags::finalize_storage().
17409: 
17410: =item *
17411: 
17412: cstore($storehash,$symb,$namespace,$udom,$uname,$laststore) : same as store
17413: but uses critical subroutine
17414: 
17415: =item *
17416: 
17417: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
17418: all args are optional
17419: 
17420: =item *
17421: 
17422: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
17423: dumps the complete (or key matching regexp) namespace into a hash
17424: ($udom, $uname, $regexp, $range are optional) for a namespace that is
17425: normally &store()ed into
17426: 
17427: $range should be either an integer '100' (give me the first 100
17428:                                            matching records)
17429:               or be  two integers sperated by a - with no spaces
17430:                  '30-50' (give me the 30th through the 50th matching
17431:                           records)
17432: 
17433: 
17434: =item *
17435: 
17436: putstore($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog) :
17437: replaces a &store() version of data with a replacement set of data
17438: for a particular resource in a namespace passed in the $storehash hash 
17439: reference. If $tolog is true, the transaction is logged in the courselog
17440: with an action=PUTSTORE.
17441: 
17442: =item *
17443: 
17444: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
17445: works very similar to store/cstore, but all data is stored in a
17446: temporary location and can be reset using tmpreset, $storehash should
17447: be a hash reference, returns nothing on success
17448: 
17449: =item *
17450: 
17451: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
17452: similar to restore, but all data is stored in a temporary location and
17453: can be reset using tmpreset. Returns a hash of values on success,
17454: error string otherwise.
17455: 
17456: =item *
17457: 
17458: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
17459: deltes all keys for $symb form the temporary storage hash.
17460: 
17461: =item *
17462: 
17463: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
17464: reference filled in from namesp ($udom and $uname are optional)
17465: 
17466: =item *
17467: 
17468: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
17469: namesp ($udom and $uname are optional)
17470: 
17471: =item *
17472: 
17473: dump($namespace,$udom,$uname,$regexp,$range) : 
17474: dumps the complete (or key matching regexp) namespace into a hash
17475: ($udom, $uname, $regexp, $range are optional)
17476: 
17477: $range should be either an integer '100' (give me the first 100
17478:                                            matching records)
17479:               or be  two integers sperated by a - with no spaces
17480:                  '30-50' (give me the 30th through the 50th matching
17481:                           records)
17482: =item *
17483: 
17484: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
17485: $store can be a scalar, an array reference, or if the amount to be 
17486: incremented is > 1, a hash reference.
17487: 
17488: ($udom and $uname are optional)
17489: 
17490: =item *
17491: 
17492: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
17493: ($udom and $uname are optional)
17494: 
17495: =item *
17496: 
17497: cput($namespace,$storehash,$udom,$uname) : critical put
17498: ($udom and $uname are optional)
17499: 
17500: =item *
17501: 
17502: newput($namespace,$storehash,$udom,$uname) :
17503: 
17504: Attempts to store the items in the $storehash, but only if they don't
17505: currently exist, if this succeeds you can be certain that you have 
17506: successfully created a new key value pair in the $namespace db.
17507: 
17508: 
17509: Args:
17510:  $namespace: name of database to store values to
17511:  $storehash: hashref to store to the db
17512:  $udom: (optional) domain of user containing the db
17513:  $uname: (optional) name of user caontaining the db
17514: 
17515: Returns:
17516:  'ok' -> succeeded in storing all keys of $storehash
17517:  'key_exists: <key>' -> failed to anything out of $storehash, as at
17518:                         least <key> already existed in the db (other
17519:                         requested keys may also already exist)
17520:  'error: <msg>' -> unable to tie the DB or other error occurred
17521:  'con_lost' -> unable to contact request server
17522:  'refused' -> action was not allowed by remote machine
17523: 
17524: 
17525: =item *
17526: 
17527: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
17528: reference filled in from namesp (encrypts the return communication)
17529: ($udom and $uname are optional)
17530: 
17531: =item *
17532: 
17533: log($udom,$name,$home,$message) : write to permanent log for user; use
17534: critical subroutine
17535: 
17536: =item *
17537: 
17538: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
17539: array reference filled in from namespace found in domain level on either
17540: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
17541: 
17542: =item *
17543: 
17544: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
17545: domain level either on specified domain server ($uhome) or primary domain 
17546: server ($udom and $uhome are optional)
17547: 
17548: =item * 
17549: 
17550: get_domain_defaults($target_domain,$ignore_cache) : returns hash with defaults 
17551: for: authentication, language, quotas, timezone, date locale, and portal URL in
17552: the target domain.
17553: 
17554: May also include additional key => value pairs for the following groups:
17555: 
17556: =over
17557: 
17558: =item
17559: disk quotas (MB allocated by default to portfolios and authoring spaces).
17560: 
17561: =over
17562: 
17563: =item defaultquota, authorquota
17564: 
17565: =back
17566: 
17567: =item
17568: tools (availability of aboutme page, blog, webDAV access for authoring spaces,
17569: portfolio for users).
17570: 
17571: =over
17572: 
17573: =item
17574: aboutme, blog, webdav, portfolio
17575: 
17576: =back
17577: 
17578: =item
17579: requestcourses: ability to request courses, and how requests are processed.
17580: 
17581: =over
17582: 
17583: =item
17584: official, unofficial, community, textbook, placement
17585: 
17586: =back
17587: 
17588: =item
17589: inststatus: types of institutional affiliation, and order in which they are displayed.
17590: 
17591: =over
17592: 
17593: =item
17594: inststatustypes, inststatusorder, inststatusguest
17595: 
17596: =back
17597: 
17598: =item
17599: coursedefaults: can PDF forms can be created, default credits for courses, default quotas (MB)
17600: for course's uploaded content.
17601: 
17602: =over
17603: 
17604: =item
17605: canuse_pdfforms, officialcredits, unofficialcredits, textbookcredits, officialquota, unofficialquota, 
17606: communityquota, textbookquota, placementquota
17607: 
17608: =back
17609: 
17610: =item
17611: usersessions: set options for hosting of your users in other domains, and hosting of users from other domains
17612: on your servers.
17613: 
17614: =over
17615: 
17616: =item 
17617: remotesessions, hostedsessions
17618: 
17619: =back
17620: 
17621: =back
17622: 
17623: In cases where a domain coordinator has never used the "Set Domain Configuration"
17624: utility to create a configuration.db file on a domain's primary library server 
17625: only the following domain defaults: auth_def, auth_arg_def, lang_def
17626: -- corresponding values are authentication type (internal, krb4, krb5,
17627: or localauth), initial password or a kerberos realm, language (e.g., en-us) -- 
17628: will be available. Values are retrieved from cache (if current), unless the
17629: optional $ignore_cache arg is true, or from domain's configuration.db (if available),
17630: or lastly from values in lonTabs/dns_domain,tab, or lonTabs/domain.tab.
17631: 
17632: Typical usage:
17633: 
17634: %domdefaults = &get_domain_defaults($target_domain);
17635: 
17636: =back
17637: 
17638: =head2 Network Status Functions
17639: 
17640: =over 4
17641: 
17642: =item *
17643: 
17644: dirlist() : return directory list based on URI (first arg).
17645: 
17646: Inputs: 1 required, 5 optional.
17647: 
17648: =over
17649: 
17650: =item 
17651: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
17652: 
17653: =item
17654: $userdomain - domain of user/course to be listed. Extracted from $uri if absent. 
17655: 
17656: =item
17657: $username -  username of user/course to be listed. Extracted from $uri if absent. 
17658: 
17659: =item
17660: $getpropath - boolean: 1 if prepend path using &propath(). 
17661: 
17662: =item
17663: $getuserdir - boolean: 1 if prepend path for "userfiles".
17664: 
17665: =item 
17666: $alternateRoot - path to prepend in place of path from $uri.
17667: 
17668: =back
17669: 
17670: Returns: Array of up to two items.
17671: 
17672: =over
17673: 
17674: a reference to an array of files/subdirectories
17675: 
17676: =over
17677: 
17678: Each element in the array of files/subdirectories is a & separated list of
17679: item name and the result of running stat on the item.  If dirlist was requested
17680: for a file instead of a directory, the item name will be ''. For a directory 
17681: listing, if the item is a metadata file, the element will end &N&M 
17682: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
17683: default copyright set (1).  
17684: 
17685: =back
17686: 
17687: a scalar containing error condition (if encountered).
17688: 
17689: =over
17690: 
17691: =item 
17692: no_host (no homeserver identified for $username:$domain).
17693: 
17694: =item 
17695: no_such_host (server contacted for listing not identified as valid host).
17696: 
17697: =item 
17698: con_lost (connection to remote server failed).
17699: 
17700: =item 
17701: refused (invalid $username:$domain received on lond side).
17702: 
17703: =item 
17704: no_such_dir (directory at specified path on lond side does not exist). 
17705: 
17706: =item 
17707: empty (directory at specified path on lond side is empty).
17708: 
17709: =over
17710: 
17711: This is currently not encountered because the &ls3, &ls2, 
17712: &ls (_handler) routines on the lond side do not filter out
17713: . and .. from a directory listing. 
17714: 
17715: =back
17716: 
17717: =back
17718: 
17719: =back
17720: 
17721: =item *
17722: 
17723: spareserver() : find server with least workload from spare.tab
17724: 
17725: 
17726: =item *
17727: 
17728: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
17729: if there is no corresponding loncapa host.
17730: 
17731: =back
17732: 
17733: 
17734: =head2 Apache Request
17735: 
17736: =over 4
17737: 
17738: =item *
17739: 
17740: ssi($url,%hash) : server side include, does a complete request cycle on url to
17741: localhost, posts hash
17742: 
17743: =back
17744: 
17745: =head2 Data to String to Data
17746: 
17747: =over 4
17748: 
17749: =item *
17750: 
17751: hash2str(%hash) : convert a hash into a string complete with escaping and '='
17752: and '&' separators, supports elements that are arrayrefs and hashrefs
17753: 
17754: =item *
17755: 
17756: hashref2str($hashref) : convert a hashref into a string complete with
17757: escaping and '=' and '&' separators, supports elements that are
17758: arrayrefs and hashrefs
17759: 
17760: =item *
17761: 
17762: arrayref2str($arrayref) : convert an arrayref into a string complete
17763: with escaping and '&' separators, supports elements that are arrayrefs
17764: and hashrefs
17765: 
17766: =item *
17767: 
17768: str2hash($string) : convert string to hash using unescaping and
17769: splitting on '=' and '&', supports elements that are arrayrefs and
17770: hashrefs
17771: 
17772: =item *
17773: 
17774: str2array($string) : convert string to hash using unescaping and
17775: splitting on '&', supports elements that are arrayrefs and hashrefs
17776: 
17777: =back
17778: 
17779: =head2 Logging Routines
17780: 
17781: 
17782: These routines allow one to make log messages in the lonnet.log and
17783: lonnet.perm logfiles.
17784: 
17785: =over 4
17786: 
17787: =item *
17788: 
17789: logtouch() : make sure the logfile, lonnet.log, exists
17790: 
17791: =item *
17792: 
17793: logthis() : append message to the normal lonnet.log file, it gets
17794: preiodically rolled over and deleted.
17795: 
17796: =item *
17797: 
17798: logperm() : append a permanent message to lonnet.perm.log, this log
17799: file never gets deleted by any automated portion of the system, only
17800: messages of critical importance should go in here.
17801: 
17802: 
17803: =back
17804: 
17805: =head2 General File Helper Routines
17806: 
17807: =over 4
17808: 
17809: =item *
17810: 
17811: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
17812: (a) files in /uploaded
17813:   (i) If a local copy of the file exists - 
17814:       compares modification date of local copy with last-modified date for 
17815:       definitive version stored on home server for course. If local copy is 
17816:       stale, requests a new version from the home server and stores it. 
17817:       If the original has been removed from the home server, then local copy 
17818:       is unlinked.
17819:   (ii) If local copy does not exist -
17820:       requests the file from the home server and stores it. 
17821:   
17822:   If $caller is 'uploadrep':  
17823:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
17824:     for request for files originally uploaded via DOCS. 
17825:      - returns 'ok' if fresh local copy now available, -1 otherwise.
17826:   
17827:   Otherwise:
17828:      This indicates a call from the content generation phase of the request.
17829:      -  returns the entire contents of the file or -1.
17830:      
17831: (b) files in /res
17832:    - returns the entire contents of a file or -1; 
17833:    it properly subscribes to and replicates the file if neccessary.
17834: 
17835: 
17836: =item *
17837: 
17838: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
17839:                   reference
17840: 
17841: returns either a stat() list of data about the file or an empty list
17842: if the file doesn't exist or couldn't find out about it (connection
17843: problems or user unknown)
17844: 
17845: =item *
17846: 
17847: filelocation($dir,$file) : returns file system location of a file
17848: based on URI; meant to be "fairly clean" absolute reference, $dir is a
17849: directory that relative $file lookups are to looked in ($dir of /a/dir
17850: and a file of ../bob will become /a/bob)
17851: 
17852: =item *
17853: 
17854: hreflocation($dir,$file) : returns file system location or a URL; same as
17855: filelocation except for hrefs
17856: 
17857: =item *
17858: 
17859: declutter() : declutters URLs -- remove beginning slashes, 'res' etc.
17860: also removes beginning /home/httpd/html unless /priv/ follows it.
17861: 
17862: =back
17863: 
17864: =head2 Usererfile file routines (/uploaded*)
17865: 
17866: =over 4
17867: 
17868: =item *
17869: 
17870: userfileupload(): main rotine for putting a file in a user or course's
17871:                   filespace, arguments are,
17872: 
17873:  formname - required - this is the name of the element in $env where the
17874:            filename, and the contents of the file to create/modifed exist
17875:            the filename is in $env{'form.'.$formname.'.filename'} and the
17876:            contents of the file is located in $env{'form.'.$formname}
17877:  context - if coursedoc, store the file in the course of the active role
17878:              of the current user; 
17879:            if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
17880:            if 'canceloverwrite': delete file in tmp/overwrites directory
17881:  subdir - required - subdirectory to put the file in under ../userfiles/
17882:          if undefined, it will be placed in "unknown"
17883: 
17884:  (This routine calls clean_filename() to remove any dangerous
17885:  characters from the filename, and then calls finuserfileupload() to
17886:  complete the transaction)
17887: 
17888:  returns either the url of the uploaded file (/uploaded/....) if successful
17889:  and /adm/notfound.html if unsuccessful
17890: 
17891: =item *
17892: 
17893: clean_filename(): routine for cleaing a filename up for storage in
17894:                  userfile space, argument is:
17895: 
17896:  filename - proposed filename
17897: 
17898: returns: the new clean filename
17899: 
17900: =item *
17901: 
17902: finishuserfileupload(): routine that creates and sends the file to
17903: userspace, probably shouldn't be called directly
17904: 
17905:   docuname: username or courseid of destination for the file
17906:   docudom: domain of user/course of destination for the file
17907:   formname: same as for userfileupload()
17908:   fname: filename (including subdirectories) for the file
17909:   parser: if 'parse', will parse (html) file to extract references to objects, links etc.
17910:           if hashref, and context is scantron, will convert csv format to standard format
17911:   allfiles: reference to hash used to store objects found by parser
17912:   codebase: reference to hash used for codebases of java objects found by parser
17913:   thumbwidth: width (pixels) of thumbnail to be created for uploaded image
17914:   thumbheight: height (pixels) of thumbnail to be created for uploaded image
17915:   resizewidth: width to be used to resize image using resizeImage from ImageMagick
17916:   resizeheight: height to be used to resize image using resizeImage from ImageMagick
17917:   context: if 'overwrite', will move the uploaded file from its temporary location to
17918:             userfiles to facilitate overwriting a previously uploaded file with same name.
17919:   mimetype: reference to scalar to accommodate mime type determined
17920:             from File::MMagic if $parser = parse.
17921: 
17922:  returns either the url of the uploaded file (/uploaded/....) if successful
17923:  and /adm/notfound.html if unsuccessful (or an error message if context 
17924:  was 'overwrite').
17925:  
17926: 
17927: =item *
17928: 
17929: renameuserfile(): renames an existing userfile to a new name
17930: 
17931:   Args:
17932:    docuname: username or courseid of destination for the file
17933:    docudom: domain of user/course of destination for the file
17934:    old: current file name (including any subdirs under userfiles)
17935:    new: desired file name (including any subdirs under userfiles)
17936: 
17937: =item *
17938: 
17939: mkdiruserfile(): creates a directory is a userfiles dir
17940: 
17941:   Args:
17942:    docuname: username or courseid of destination for the file
17943:    docudom: domain of user/course of destination for the file
17944:    dir: dir to create (including any subdirs under userfiles)
17945: 
17946: =item *
17947: 
17948: removeuserfile(): removes a file that exists in userfiles
17949: 
17950:   Args:
17951:    docuname: username or courseid of destination for the file
17952:    docudom: domain of user/course of destination for the file
17953:    fname: filname to delete (including any subdirs under userfiles)
17954: 
17955: =item *
17956: 
17957: removeuploadedurl(): convience function for removeuserfile()
17958: 
17959:   Args:
17960:    url:  a full /uploaded/... url to delete
17961: 
17962: =item * 
17963: 
17964: get_portfile_permissions():
17965:   Args:
17966:     domain: domain of user or course contain the portfolio files
17967:     user: name of user or num of course contain the portfolio files
17968:   Returns:
17969:     hashref of a dump of the proper file_permissions.db
17970:    
17971: 
17972: =item * 
17973: 
17974: get_access_controls():
17975: 
17976: Args:
17977:   current_permissions: the hash ref returned from get_portfile_permissions()
17978:   group: (optional) the group you want the files associated with
17979:   file: (optional) the file you want access info on
17980: 
17981: Returns:
17982:     a hash (keys are file names) of hashes containing
17983:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
17984:         values are XML containing access control settings (see below) 
17985: 
17986: Internal notes:
17987: 
17988:  access controls are stored in file_permissions.db as key=value pairs.
17989:     key -> path to file/file_name\0uniqueID:scope_end_start
17990:         where scope -> public,guest,course,group,domains or users.
17991:               end -> UNIX time for end of access (0 -> no end date)
17992:               start -> UNIX time for start of access
17993: 
17994:     value -> XML description of access control
17995:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
17996:             <start></start>
17997:             <end></end>
17998: 
17999:             <password></password>  for scope type = guest
18000: 
18001:             <domain></domain>     for scope type = course or group
18002:             <number></number>
18003:             <roles id="">
18004:              <role></role>
18005:              <access></access>
18006:              <section></section>
18007:              <group></group>
18008:             </roles>
18009: 
18010:             <dom></dom>         for scope type = domains
18011: 
18012:             <users>             for scope type = users
18013:              <user>
18014:               <uname></uname>
18015:               <udom></udom>
18016:              </user>
18017:             </users>
18018:            </scope> 
18019:               
18020:  Access data is also aggregated for each file in an additional key=value pair:
18021:  key -> path to file/file_name\0accesscontrol 
18022:  value -> reference to hash
18023:           hash contains key = value pairs
18024:           where key = uniqueID:scope_end_start
18025:                 value = UNIX time record was last updated
18026: 
18027:           Used to improve speed of look-ups of access controls for each file.  
18028:  
18029:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
18030: 
18031: =item *
18032: 
18033: modify_access_controls():
18034: 
18035: Modifies access controls for a portfolio file
18036: Args
18037: 1. file name
18038: 2. reference to hash of required changes,
18039: 3. domain
18040: 4. username
18041:   where domain,username are the domain of the portfolio owner 
18042:   (either a user or a course) 
18043: 
18044: Returns:
18045: 1. result of additions or updates ('ok' or 'error', with error message). 
18046: 2. result of deletions ('ok' or 'error', with error message).
18047: 3. reference to hash of any new or updated access controls.
18048: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
18049:    key = integer (inbound ID)
18050:    value = uniqueID
18051: 
18052: =item *
18053: 
18054: get_timebased_id():
18055: 
18056: Attempts to get a unique timestamp-based suffix for use with items added to a 
18057: course via the Course Editor (e.g., folders, composite pages, 
18058: group bulletin boards).
18059: 
18060: Args: (first three required; six others optional)
18061: 
18062: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
18063:    docssequence, or name of group
18064: 
18065: 2. keyid (alphanumeric): name of temporary locking key in hash,
18066:    e.g., num, boardids
18067: 
18068: 3. namespace: name of gdbm file used to store suffixes already assigned;  
18069:    file will be named nohist_namespace.db
18070: 
18071: 4. cdom: domain of course; default is current course domain from %env
18072: 
18073: 5. cnum: course number; default is current course number from %env
18074: 
18075: 6. idtype: set to concat if an additional digit is to be appended to the 
18076:    unix timestamp to form the suffix, if the plain timestamp is already
18077:    in use.  Default is to not do this, but simply increment the unix 
18078:    timestamp by 1 until a unique key is obtained.
18079: 
18080: 7. who: holder of locking key; defaults to user:domain for user.
18081: 
18082: 8. locktries: number of attempts to obtain a lock (sleep of 1s before 
18083:    retrying); default is 3.
18084: 
18085: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.  
18086: 
18087: Returns:
18088: 
18089: 1. suffix obtained (numeric)
18090: 
18091: 2. result of deleting locking key (ok if deleted, or lock never obtained)
18092: 
18093: 3. error: contains (localized) error message if an error occurred.
18094: 
18095: 
18096: =back
18097: 
18098: =head2 HTTP Helper Routines
18099: 
18100: =over 4
18101: 
18102: =item *
18103: 
18104: escape() : unpack non-word characters into CGI-compatible hex codes
18105: 
18106: =item *
18107: 
18108: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
18109: 
18110: =back
18111: 
18112: =head1 PRIVATE SUBROUTINES
18113: 
18114: =head2 Underlying communication routines (Shouldn't call)
18115: 
18116: =over 4
18117: 
18118: =item *
18119: 
18120: subreply() : tries to pass a message to lonc, returns con_lost if incapable
18121: 
18122: =item *
18123: 
18124: reply() : uses subreply to send a message to remote machine, logs all failures
18125: 
18126: =item *
18127: 
18128: critical() : passes a critical message to another server; if cannot
18129: get through then place message in connection buffer directory and
18130: returns con_delayed, if incapable of saving message, returns
18131: con_failed
18132: 
18133: =item *
18134: 
18135: reconlonc() : tries to reconnect lonc client processes.
18136: 
18137: =back
18138: 
18139: =head2 Resource Access Logging
18140: 
18141: =over 4
18142: 
18143: =item *
18144: 
18145: flushcourselogs() : flush (save) buffer logs and access logs
18146: 
18147: =item *
18148: 
18149: courselog($what) : save message for course in hash
18150: 
18151: =item *
18152: 
18153: courseacclog($what) : save message for course using &courselog().  Perform
18154: special processing for specific resource types (problems, exams, quizzes, etc).
18155: 
18156: =item *
18157: 
18158: goodbye() : flush course logs and log shutting down; it is called in srm.conf
18159: as a PerlChildExitHandler
18160: 
18161: =back
18162: 
18163: =head2 Other
18164: 
18165: =over 4
18166: 
18167: =item *
18168: 
18169: symblist($mapname,%newhash) : update symbolic storage links
18170: 
18171: =back
18172: 
18173: =cut
18174: 

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