File:  [LON-CAPA] / loncom / lonnet / perl / lonnet.pm
Revision 1.1525: download - view: text, annotated - select for diffs
Sun Apr 14 17:12:29 2024 UTC (3 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Available editors in Course Authoring Space, or when editing an html file
  created in a course folder using the Course Editor is a domain default,
  which can be overridden in specific course(s) by a Domain Coordinator.

    1: # The LearningOnline Network
    2: # TCP networking package
    3: #
    4: # $Id: lonnet.pm,v 1.1525 2024/04/14 17:12:29 raeburn Exp $
    5: #
    6: # Copyright Michigan State University Board of Trustees
    7: #
    8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
    9: #
   10: # LON-CAPA is free software; you can redistribute it and/or modify
   11: # it under the terms of the GNU General Public License as published by
   12: # the Free Software Foundation; either version 2 of the License, or
   13: # (at your option) any later version.
   14: #
   15: # LON-CAPA is distributed in the hope that it will be useful,
   16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
   17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   18: # GNU General Public License for more details.
   19: #
   20: # You should have received a copy of the GNU General Public License
   21: # along with LON-CAPA; if not, write to the Free Software
   22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
   23: #
   24: # /home/httpd/html/adm/gpl.txt
   25: #
   26: # http://www.lon-capa.org/
   27: #
   28: ###
   29: 
   30: =pod
   31: 
   32: =head1 NAME
   33: 
   34: Apache::lonnet.pm
   35: 
   36: =head1 SYNOPSIS
   37: 
   38: This file is an interface to the lonc processes of
   39: the LON-CAPA network as well as set of elaborated functions for handling information
   40: necessary for navigating through a given cluster of LON-CAPA machines within a
   41: domain. There are over 40 specialized functions in this module which handle the
   42: reading and transmission of metadata, user information (ids, names, environments, roles,
   43: logs), file information (storage, reading, directories, extensions, replication, embedded
   44: styles and descriptors), educational resources (course descriptions, section names and
   45: numbers), url hashing (to assign roles on a url basis), and translating abbreviated symbols to
   46: and from more descriptive phrases or explanations.
   47: 
   48: This is part of the LearningOnline Network with CAPA project
   49: described at http://www.lon-capa.org.
   50: 
   51: =head1 Package Variables
   52: 
   53: These are largely undocumented, so if you decipher one please note it here.
   54: 
   55: =over 4
   56: 
   57: =item $processmarker
   58: 
   59: Contains the time this process was started and this servers host id.
   60: 
   61: =item $dumpcount
   62: 
   63: Counts the number of times a message log flush has been attempted (regardless
   64: of success) by this process.  Used as part of the filename when messages are
   65: delayed.
   66: 
   67: =back
   68: 
   69: =cut
   70: 
   71: package Apache::lonnet;
   72: 
   73: use strict;
   74: use HTTP::Date;
   75: use Image::Magick;
   76: use CGI::Cookie;
   77: 
   78: use Encode;
   79: 
   80: use vars qw(%perlvar %spareid %pr %prp $memcache %packagetab $tmpdir $deftex
   81:             $_64bit %env %protocol %loncaparevs %serverhomeIDs %needsrelease
   82:             %managerstab $passwdmin);
   83: 
   84: my (%badServerCache, $memcache, %courselogs, %accesshash, %domainrolehash,
   85:     %userrolehash, $processmarker, $dumpcount, %coursedombuf,
   86:     %coursenumbuf, %coursehombuf, %coursedescrbuf, %courseinstcodebuf,
   87:     %courseownerbuf, %coursetypebuf,$locknum);
   88: 
   89: use IO::Socket;
   90: use GDBM_File;
   91: use HTML::LCParser;
   92: use Fcntl qw(:flock);
   93: use Storable qw(thaw nfreeze);
   94: use Time::HiRes qw( sleep gettimeofday tv_interval );
   95: use Cache::Memcached;
   96: use Digest::MD5;
   97: use Math::Random;
   98: use File::MMagic;
   99: use Net::CIDR;
  100: use Sys::Hostname::FQDN();
  101: use LONCAPA qw(:DEFAULT :match);
  102: use LONCAPA::Configuration;
  103: use LONCAPA::lonmetadata;
  104: use LONCAPA::Lond;
  105: use LONCAPA::LWPReq;
  106: use LONCAPA::transliterate;
  107: 
  108: use File::Copy;
  109: 
  110: my $readit;
  111: my $max_connection_retries = 20;     # Or some such value.
  112: 
  113: require Exporter;
  114: 
  115: our @ISA = qw (Exporter);
  116: our @EXPORT = qw(%env);
  117: 
  118: 
  119: # ------------------------------------ Logging (parameters, docs, slots, roles)
  120: {
  121:     my $logid;
  122:     sub write_log {
  123: 	my ($context,$hash_name,$storehash,$delflag,$uname,$udom,$cnum,$cdom)=@_;
  124:         if ($context eq 'course') {
  125:             if (($cnum eq '') || ($cdom eq '')) {
  126:                 $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
  127:                 $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
  128:             }
  129:         }
  130: 	$logid ++;
  131:         my $now = time();
  132: 	my $id=$now.'00000'.$$.'00000'.$logid;
  133:         my $ip = &get_requestor_ip();
  134:         my $logentry = { 
  135:                           $id => {
  136:                                    'exe_uname' => $env{'user.name'},
  137:                                    'exe_udom'  => $env{'user.domain'},
  138:                                    'exe_time'  => $now,
  139:                                    'exe_ip'    => $ip,
  140:                                    'delflag'   => $delflag,
  141:                                    'logentry'  => $storehash,
  142:                                    'uname'     => $uname,
  143:                                    'udom'      => $udom,
  144:                                   }
  145:                        };
  146: 	return &put('nohist_'.$hash_name,$logentry,$cdom,$cnum);
  147:     }
  148: }
  149: 
  150: sub logtouch {
  151:     my $execdir=$perlvar{'lonDaemons'};
  152:     unless (-e "$execdir/logs/lonnet.log") {	
  153: 	open(my $fh,">>","$execdir/logs/lonnet.log");
  154: 	close $fh;
  155:     }
  156:     my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
  157:     chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
  158: }
  159: 
  160: sub logthis {
  161:     my $message=shift;
  162:     my $execdir=$perlvar{'lonDaemons'};
  163:     my $now=time;
  164:     my $local=localtime($now);
  165:     if (open(my $fh,">>","$execdir/logs/lonnet.log")) {
  166: 	my $logstring = $local. " ($$): ".$message."\n"; # Keep any \'s in string.
  167: 	print $fh $logstring;
  168: 	close($fh);
  169:     }
  170:     return 1;
  171: }
  172: 
  173: sub logperm {
  174:     my $message=shift;
  175:     my $execdir=$perlvar{'lonDaemons'};
  176:     my $now=time;
  177:     my $local=localtime($now);
  178:     if (open(my $fh,">>","$execdir/logs/lonnet.perm.log")) {
  179: 	print $fh "$now:$message:$local\n";
  180: 	close($fh);
  181:     }
  182:     return 1;
  183: }
  184: 
  185: sub create_connection {
  186:     my ($hostname,$lonid) = @_;
  187:     my $client=IO::Socket::UNIX->new(Peer    => $perlvar{'lonSockCreate'},
  188: 				     Type    => SOCK_STREAM,
  189: 				     Timeout => 10);
  190:     return 0 if (!$client);
  191:     print $client (join(':',$hostname,$lonid,&machine_ids($hostname),$loncaparevs{$lonid})."\n");
  192:     my $result = <$client>;
  193:     chomp($result);
  194:     return 1 if ($result eq 'done');
  195:     return 0;
  196: }
  197: 
  198: sub get_server_timezone {
  199:     my ($cnum,$cdom) = @_;
  200:     my $home=&homeserver($cnum,$cdom);
  201:     if ($home ne 'no_host') {
  202:         my $cachetime = 24*3600;
  203:         my ($timezone,$cached)=&is_cached_new('servertimezone',$home);
  204:         if (defined($cached)) {
  205:             return $timezone;
  206:         } else {
  207:             my $timezone = &reply('servertimezone',$home);
  208:             return &do_cache_new('servertimezone',$home,$timezone,$cachetime);
  209:         }
  210:     }
  211: }
  212: 
  213: sub get_server_distarch {
  214:     my ($lonhost,$ignore_cache) = @_;
  215:     if (defined($lonhost)) {
  216:         if (!defined(&hostname($lonhost))) {
  217:             return;
  218:         }
  219:         my $cachetime = 12*3600;
  220:         if (!$ignore_cache) {
  221:             my ($distarch,$cached)=&is_cached_new('serverdistarch',$lonhost);
  222:             if (defined($cached)) {
  223:                 return $distarch;
  224:             }
  225:         }
  226:         my $rep = &reply('serverdistarch',$lonhost);
  227:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
  228:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
  229:                 $rep eq '') {
  230:             return &do_cache_new('serverdistarch',$lonhost,$rep,$cachetime);
  231:         }
  232:     }
  233:     return;
  234: }
  235: 
  236: sub get_servercerts_info {
  237:     my ($lonhost,$hostname,$context) = @_;
  238:     return if ($lonhost eq '');
  239:     if ($hostname eq '') {
  240:         $hostname = &hostname($lonhost);
  241:     }
  242:     return if ($hostname eq '');
  243:     my ($rep,$uselocal);
  244:     if ($context eq 'install') {
  245:         $uselocal = 1;
  246:     } elsif (grep { $_ eq $lonhost } &current_machine_ids()) {
  247:         $uselocal = 1;
  248:     }
  249:     if (($context ne 'cgi') && ($context ne 'install') && ($uselocal)) {
  250:         my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
  251:         if ($distro eq '') {
  252:             $uselocal = 0;
  253:         } elsif ($distro =~ /^(?:centos|redhat|scientific)(\d+)$/) {
  254:             if ($1 < 6) {
  255:                 $uselocal = 0;
  256:             }
  257:         }  elsif ($distro =~ /^(?:sles)(\d+)$/) {
  258:             if ($1 < 12) {
  259:                 $uselocal = 0;
  260:             }
  261:         }
  262:     }
  263:     if ($uselocal) {
  264:         $rep = LONCAPA::Lond::server_certs(\%perlvar,$lonhost,$hostname);
  265:     } else {
  266:         $rep=&reply('servercerts',$lonhost);
  267:     }
  268:     my ($result,%returnhash);
  269:     if (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
  270:         ($rep eq 'unknown_cmd')) {
  271:         $result = $rep;
  272:     } else {
  273:         $result = 'ok';
  274:         my @pairs=split(/\&/,$rep);
  275:         foreach my $item (@pairs) {
  276:             my ($key,$value)=split(/=/,$item,2);
  277:             my $what = &unescape($key);
  278:             $returnhash{$what}=&thaw_unescape($value);
  279:         }
  280:     }
  281:     return ($result,\%returnhash);
  282: }
  283: 
  284: sub get_server_loncaparev {
  285:     my ($dom,$lonhost,$ignore_cache,$caller) = @_;
  286:     if (defined($lonhost)) {
  287:         if (!defined(&hostname($lonhost))) {
  288:             undef($lonhost);
  289:         }
  290:     }
  291:     if (!defined($lonhost)) {
  292:         if (defined(&domain($dom,'primary'))) {
  293:             $lonhost=&domain($dom,'primary');
  294:             if ($lonhost eq 'no_host') {
  295:                 undef($lonhost);
  296:             }
  297:         }
  298:     }
  299:     if (defined($lonhost)) {
  300:         my $cachetime = 12*3600;
  301:         if (!$ignore_cache) {
  302:             my ($loncaparev,$cached)=&is_cached_new('serverloncaparev',$lonhost);
  303:             if (defined($cached)) {
  304:                 return $loncaparev;
  305:             }
  306:         }
  307:         my ($answer,$loncaparev);
  308:         my @ids=&current_machine_ids();
  309:         if (grep(/^\Q$lonhost\E$/,@ids)) {
  310:             $answer = $perlvar{'lonVersion'};
  311:             if ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
  312:                 $loncaparev = $1;
  313:             }
  314:         } else {
  315:             $answer = &reply('serverloncaparev',$lonhost);
  316:             if (($answer eq 'unknown_cmd') || ($answer eq 'con_lost')) {
  317:                 if ($caller eq 'loncron') {
  318:                     my $hostname = &hostname($lonhost);
  319:                     my $protocol = $protocol{$lonhost};
  320:                     $protocol = 'http' if ($protocol ne 'https');
  321:                     my $url = $protocol.'://'.$hostname.'/adm/about.html';
  322:                     my $request=new HTTP::Request('GET',$url);
  323:                     my $response=&LONCAPA::LWPReq::makerequest($lonhost,$request,'',\%perlvar,4,1);
  324:                     unless ($response->is_error()) {
  325:                         my $content = $response->content;
  326:                         if ($content =~ /<p>VERSION\:\s*([\w.\-]+)<\/p>/) {
  327:                             $loncaparev = $1;
  328:                         }
  329:                     }
  330:                 } else {
  331:                     $loncaparev = $loncaparevs{$lonhost};
  332:                 }
  333:             } elsif ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
  334:                 $loncaparev = $1;
  335:             }
  336:         }
  337:         return &do_cache_new('serverloncaparev',$lonhost,$loncaparev,$cachetime);
  338:     }
  339: }
  340: 
  341: sub get_server_homeID {
  342:     my ($hostname,$ignore_cache,$caller) = @_;
  343:     unless ($ignore_cache) {
  344:         my ($serverhomeID,$cached)=&is_cached_new('serverhomeID',$hostname);
  345:         if (defined($cached)) {
  346:             return $serverhomeID;
  347:         }
  348:     }
  349:     my $cachetime = 12*3600;
  350:     my $serverhomeID;
  351:     if ($caller eq 'loncron') { 
  352:         my @machine_ids = &machine_ids($hostname);
  353:         foreach my $id (@machine_ids) {
  354:             my $response = &reply('serverhomeID',$id);
  355:             unless (($response eq 'unknown_cmd') || ($response eq 'con_lost')) {
  356:                 $serverhomeID = $response;
  357:                 last;
  358:             }
  359:         }
  360:         if ($serverhomeID eq '') {
  361:             $serverhomeID = $machine_ids[-1];
  362:         }
  363:     } else {
  364:         $serverhomeID = $serverhomeIDs{$hostname};
  365:     }
  366:     return &do_cache_new('serverhomeID',$hostname,$serverhomeID,$cachetime);
  367: }
  368: 
  369: sub get_remote_globals {
  370:     my ($lonhost,$whathash,$ignore_cache) = @_;
  371:     my ($result,%returnhash,%whatneeded);
  372:     if (ref($whathash) eq 'HASH') {
  373:         foreach my $what (sort(keys(%{$whathash}))) {
  374:             my $hashid = $lonhost.'-'.$what;
  375:             my ($response,$cached);
  376:             unless ($ignore_cache) {
  377:                 ($response,$cached)=&is_cached_new('lonnetglobal',$hashid);
  378:             }
  379:             if (defined($cached)) {
  380:                 $returnhash{$what} = $response;
  381:             } else {
  382:                 $whatneeded{$what} = 1;
  383:             }
  384:         }
  385:         if (keys(%whatneeded) == 0) {
  386:             $result = 'ok';
  387:         } else {
  388:             my $requested = &freeze_escape(\%whatneeded);
  389:             my $rep=&reply('readlonnetglobal:'.$requested,$lonhost);
  390:             if (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
  391:                 ($rep eq 'unknown_cmd')) {
  392:                 $result = $rep;
  393:             } else {
  394:                 $result = 'ok';
  395:                 my @pairs=split(/\&/,$rep);
  396:                 foreach my $item (@pairs) {
  397:                     my ($key,$value)=split(/=/,$item,2);
  398:                     my $what = &unescape($key);
  399:                     my $hashid = $lonhost.'-'.$what;
  400:                     $returnhash{$what}=&thaw_unescape($value);
  401:                     &do_cache_new('lonnetglobal',$hashid,$returnhash{$what},600);
  402:                 }
  403:             }
  404:         }
  405:     }
  406:     return ($result,\%returnhash);
  407: }
  408: 
  409: sub remote_devalidate_cache {
  410:     my ($lonhost,$cachekeys) = @_;
  411:     my $items;
  412:     return unless (ref($cachekeys) eq 'ARRAY');
  413:     my $cachestr = join('&',@{$cachekeys});
  414:     my $response = &reply('devalidatecache:'.&escape($cachestr),$lonhost);
  415:     return $response;
  416: }
  417: 
  418: sub sign_lti {
  419:     my ($cdom,$cnum,$crsdef,$type,$context,$url,$ltinum,$keynum,$paramsref,$inforef) = @_;
  420:     my $chome;
  421:     if (&domain($cdom) ne '') {
  422:         if ($crsdef) {
  423:             $chome = &homeserver($cnum,$cdom);
  424:         } else {
  425:             $chome = &domain($cdom,'primary');
  426:         }
  427:     }
  428:     if ($cdom && $chome && ($chome ne 'no_host')) {
  429:         if ((ref($paramsref) eq 'HASH') &&
  430:             (ref($inforef) eq 'HASH')) {
  431:             my $rep;
  432:             if (grep { $_ eq $chome } &current_machine_ids()) {
  433:                 # domain information is hosted on this machine
  434:                 $rep =
  435:                     &LONCAPA::Lond::sign_lti_payload($cdom,$cnum,$crsdef,$type,
  436:                                                      $context,$url,$ltinum,$keynum,
  437:                                                      $perlvar{'lonVersion'},
  438:                                                      $paramsref,$inforef);
  439:                 if (ref($rep) eq 'HASH') {
  440:                     return ('ok',$rep);
  441:                 }
  442:             } else {
  443:                 my ($escurl,$params,$info);
  444:                 $escurl = &escape($url);
  445:                 if (ref($paramsref) eq 'HASH') {
  446:                     $params = &freeze_escape($paramsref);
  447:                 }
  448:                 if (ref($inforef) eq 'HASH') {
  449:                     $info = &freeze_escape($inforef);
  450:                 }
  451:                 $rep=&reply("encrypt:signlti:$cdom:$cnum:$crsdef:$type:$context:$escurl:$ltinum:$keynum:$params:$info",$chome);
  452:             }
  453:             if (($rep eq '') || ($rep =~ /^con_lost|error|no_such_host|unknown_cmd/i)) {
  454:                 return ();
  455:             } elsif (($inforef->{'respfmt'} eq 'to_post_body') ||
  456:                      ($inforef->{'respfmt'} eq 'to_authorization_header')) {
  457:                 return ('ok',$rep);
  458:             } else {
  459:                 my %returnhash;
  460:                 foreach my $item (split(/\&/,$rep)) {
  461:                     my ($name,$value)=split(/\=/,$item);
  462:                     $returnhash{&unescape($name)}=&thaw_unescape($value);
  463:                 }
  464:                 return('ok',\%returnhash);
  465:             }
  466:         } else {
  467:             return ();
  468:         }
  469:     } else {
  470:         return ();
  471:         &logthis("sign_lti failed - no homeserver and/or domain ($cdom) ($chome)");
  472:     }
  473: }
  474: 
  475: # -------------------------------------------------- Non-critical communication
  476: sub subreply {
  477:     my ($cmd,$server)=@_;
  478:     my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
  479:     #
  480:     #  With loncnew process trimming, there's a timing hole between lonc server
  481:     #  process exit and the master server picking up the listen on the AF_UNIX
  482:     #  socket.  In that time interval, a lock file will exist:
  483: 
  484:     my $lockfile=$peerfile.".lock";
  485:     while (-e $lockfile) {	# Need to wait for the lockfile to disappear.
  486: 	sleep(0.1);
  487:     }
  488:     # At this point, either a loncnew parent is listening or an old lonc
  489:     # or loncnew child is listening so we can connect or everything's dead.
  490:     #
  491:     #   We'll give the connection a few tries before abandoning it.  If
  492:     #   connection is not possible, we'll con_lost back to the client.
  493:     #   
  494:     my $client;
  495:     for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
  496: 	$client=IO::Socket::UNIX->new(Peer    =>"$peerfile",
  497: 				      Type    => SOCK_STREAM,
  498: 				      Timeout => 10);
  499: 	if ($client) {
  500: 	    last;		# Connected!
  501: 	} else {
  502: 	    &create_connection(&hostname($server),$server);
  503: 	}
  504:         sleep(0.1);	# Try again later if failed connection.
  505:     }
  506:     my $answer;
  507:     if ($client) {
  508: 	print $client "sethost:$server:$cmd\n";
  509: 	$answer=<$client>;
  510: 	if (!$answer) { $answer="con_lost"; }
  511: 	chomp($answer);
  512:     } else {
  513: 	$answer = 'con_lost';	# Failed connection.
  514:     }
  515:     return $answer;
  516: }
  517: 
  518: sub reply {
  519:     my ($cmd,$server)=@_;
  520:     unless (defined(&hostname($server))) { return 'no_such_host'; }
  521:     my $answer=subreply($cmd,$server);
  522:     if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
  523:         my $logged = $cmd;
  524:         if ($cmd =~ /^encrypt:([^:]+):/) {
  525:             my $subcmd = $1;
  526:             if (($subcmd eq 'auth') || ($subcmd eq 'passwd') ||
  527:                 ($subcmd eq 'changeuserauth') || ($subcmd eq 'makeuser') ||
  528:                 ($subcmd eq 'putdom') || ($subcmd eq 'autoexportgrades') ||
  529:                 ($subcmd eq 'put')) {
  530:                 (undef,undef,my @rest) = split(/:/,$cmd);
  531:                 if (($subcmd eq 'auth') || ($subcmd eq 'putdom')) {
  532:                     splice(@rest,2,1,'Hidden');
  533:                 } elsif ($subcmd eq 'passwd') {
  534:                     splice(@rest,2,2,('Hidden','Hidden'));
  535:                 } elsif (($subcmd eq 'changeuserauth') || ($subcmd eq 'makeuser') ||
  536:                          ($subcmd eq 'autoexportgrades') || ($subcmd eq 'put')) {
  537:                     splice(@rest,3,1,'Hidden');
  538:                 }
  539:                 $logged = join(':',('encrypt:'.$subcmd,@rest));
  540:             }
  541:         }
  542:         &logthis("<font color=\"blue\">WARNING:".
  543:                  " $logged to $server returned $answer</font>");
  544:     }
  545:     return $answer;
  546: }
  547: 
  548: # ----------------------------------------------------------- Send USR1 to lonc
  549: 
  550: sub reconlonc {
  551:     my ($lonid) = @_;
  552:     if ($lonid) {
  553:         my $hostname = &hostname($lonid);
  554: 	my $peerfile="$perlvar{'lonSockDir'}/$hostname";
  555: 	if ($hostname && -e $peerfile) {
  556: 	    &logthis("Trying to reconnect lonc for $lonid ($hostname)");
  557: 	    my $client=IO::Socket::UNIX->new(Peer    => $peerfile,
  558: 					     Type    => SOCK_STREAM,
  559: 					     Timeout => 10);
  560: 	    if ($client) {
  561: 		print $client ("reset_retries\n");
  562: 		my $answer=<$client>;
  563: 		#reset just this one.
  564: 	    }
  565: 	}
  566: 	return;
  567:     }
  568: 
  569:     &logthis("Trying to reconnect lonc");
  570:     my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
  571:     if (open(my $fh,"<",$loncfile)) {
  572: 	my $loncpid=<$fh>;
  573:         chomp($loncpid);
  574:         if (kill 0 => $loncpid) {
  575: 	    &logthis("lonc at pid $loncpid responding, sending USR1");
  576:             kill USR1 => $loncpid;
  577:             sleep 1;
  578:         } else {
  579: 	    &logthis(
  580:                "<font color=\"blue\">WARNING:".
  581:                " lonc at pid $loncpid not responding, giving up</font>");
  582:         }
  583:     } else {
  584: 	&logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
  585:     }
  586: }
  587: 
  588: # ------------------------------------------------------ Critical communication
  589: 
  590: sub critical {
  591:     my ($cmd,$server)=@_;
  592:     unless (&hostname($server)) {
  593:         &logthis("<font color=\"blue\">WARNING:".
  594:                " Critical message to unknown server ($server)</font>");
  595:         return 'no_such_host';
  596:     }
  597:     my $answer=reply($cmd,$server);
  598:     if ($answer eq 'con_lost') {
  599: 	&reconlonc($server);
  600: 	my $answer=reply($cmd,$server);
  601:         if ($answer eq 'con_lost') {
  602:             my $now=time;
  603:             my $middlename=$cmd;
  604:             $middlename=substr($middlename,0,16);
  605:             $middlename=~s/\W//g;
  606:             my $dfilename=
  607:       "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
  608:             $dumpcount++;
  609:             {
  610: 		my $dfh;
  611: 		if (open($dfh,">",$dfilename)) {
  612: 		    print $dfh "$cmd\n"; 
  613: 		    close($dfh);
  614: 		}
  615:             }
  616:             sleep 1;
  617:             my $wcmd='';
  618:             {
  619: 		my $dfh;
  620: 		if (open($dfh,"<",$dfilename)) {
  621: 		    $wcmd=<$dfh>; 
  622: 		    close($dfh);
  623: 		}
  624:             }
  625:             chomp($wcmd);
  626:             if ($wcmd eq $cmd) {
  627: 		&logthis("<font color=\"blue\">WARNING: ".
  628:                          "Connection buffer $dfilename: $cmd</font>");
  629:                 &logperm("D:$server:$cmd");
  630: 	        return 'con_delayed';
  631:             } else {
  632:                 &logthis("<font color=\"red\">CRITICAL:"
  633:                         ." Critical connection failed: $server $cmd</font>");
  634:                 &logperm("F:$server:$cmd");
  635:                 return 'con_failed';
  636:             }
  637:         }
  638:     }
  639:     return $answer;
  640: }
  641: 
  642: # ------------------------------------------- check if return value is an error
  643: 
  644: sub error {
  645:     my ($result) = @_;
  646:     if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
  647: 	if ($2 == 2) { return undef; }
  648: 	return $1;
  649:     }
  650:     return undef;
  651: }
  652: 
  653: sub convert_and_load_session_env {
  654:     my ($lonidsdir,$handle)=@_;
  655:     my @profile;
  656:     {
  657: 	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
  658: 	if (!$opened) {
  659: 	    return 0;
  660: 	}
  661: 	flock($idf,LOCK_SH);
  662: 	@profile=<$idf>;
  663: 	close($idf);
  664:     }
  665:     my %temp_env;
  666:     foreach my $line (@profile) {
  667: 	if ($line !~ m/=/) {
  668: 	    return 0;
  669: 	}
  670: 	chomp($line);
  671: 	my ($envname,$envvalue)=split(/=/,$line,2);
  672: 	$temp_env{&unescape($envname)} = &unescape($envvalue);
  673:     }
  674:     unlink("$lonidsdir/$handle.id");
  675:     if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
  676: 	    0640)) {
  677: 	%disk_env = %temp_env;
  678: 	@env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
  679: 	untie(%disk_env);
  680:     }
  681:     return 1;
  682: }
  683: 
  684: # ------------------------------------------- Transfer profile into environment
  685: my $env_loaded;
  686: sub transfer_profile_to_env {
  687:     my ($lonidsdir,$handle,$force_transfer) = @_;
  688:     if (!$force_transfer && $env_loaded) { return; } 
  689: 
  690:     if (!defined($lonidsdir)) {
  691: 	$lonidsdir = $perlvar{'lonIDsDir'};
  692:     }
  693:     if (!defined($handle)) {
  694:         ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
  695:     }
  696: 
  697:     my $convert;
  698:     {
  699:     	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
  700: 	if (!$opened) {
  701: 	    return;
  702: 	}
  703: 	flock($idf,LOCK_SH);
  704: 	if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
  705: 		&GDBM_READER(),0640)) {
  706: 	    @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
  707: 	    untie(%disk_env);
  708: 	} else {
  709: 	    $convert = 1;
  710: 	}
  711:     }
  712:     if ($convert) {
  713: 	if (!&convert_and_load_session_env($lonidsdir,$handle)) {
  714: 	    &logthis("Failed to load session, or convert session.");
  715: 	}
  716:     }
  717: 
  718:     my %remove;
  719:     while ( my $envname = each(%env) ) {
  720:         if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
  721:             if ($time < time-300) {
  722:                 $remove{$key}++;
  723:             }
  724:         }
  725:     }
  726: 
  727:     $env{'user.environment'} = "$lonidsdir/$handle.id";
  728:     $env_loaded=1;
  729:     foreach my $expired_key (keys(%remove)) {
  730:         &delenv($expired_key);
  731:     }
  732: }
  733: 
  734: # ---------------------------------------------------- Check for valid session 
  735: sub check_for_valid_session {
  736:     my ($r,$name,$userhashref,$domref) = @_;
  737:     my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
  738:     my ($lonidsdir,$linkname,$pubname,$secure,$lonid);
  739:     if ($name eq 'lonDAV') {
  740:         $lonidsdir=$r->dir_config('lonDAVsessDir');
  741:     } else {
  742:         $lonidsdir=$r->dir_config('lonIDsDir');
  743:         if ($name eq '') {
  744:             $name = 'lonID';
  745:         }
  746:     }
  747:     if ($name eq 'lonID') {
  748:         $secure = 'lonSID';
  749:         $linkname = 'lonLinkID';
  750:         $pubname = 'lonPubID';
  751:         if (exists($cookies{$secure})) {
  752:             $lonid=$cookies{$secure};
  753:         } elsif (exists($cookies{$name})) {
  754:             $lonid=$cookies{$name};
  755:         } elsif ((exists($cookies{$linkname})) && ($ENV{'SERVER_PORT'} != 443)) {
  756:             $lonid=$cookies{$linkname};
  757:         } elsif (exists($cookies{$pubname})) {
  758:             $lonid=$cookies{$pubname};
  759:         }
  760:     } else {
  761:         $lonid=$cookies{$name};
  762:     }
  763:     return undef if (!$lonid);
  764: 
  765:     my $handle=&LONCAPA::clean_handle($lonid->value);
  766:     if (-l "$lonidsdir/$handle.id") {
  767:         my $link = readlink("$lonidsdir/$handle.id");
  768:         if ((-e $link) && ($link =~ m{^\Q$lonidsdir\E/(.+)\.id$})) {
  769:             $handle = $1;
  770:         }
  771:     }
  772:     if (!-e "$lonidsdir/$handle.id") {
  773:         if ((ref($domref)) && ($name eq 'lonID') && 
  774:             ($handle =~ /^($match_username)\_\d+\_($match_domain)\_(.+)$/)) {
  775:             my ($possuname,$possudom,$possuhome) = ($1,$2,$3);
  776:             if ((&domain($possudom) ne '') && (&homeserver($possuname,$possudom) eq $possuhome)) {
  777:                 $$domref = $possudom;
  778:             }
  779:         }
  780:         return undef;
  781:     }
  782: 
  783:     my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
  784:     return undef if (!$opened);
  785: 
  786:     flock($idf,LOCK_SH);
  787:     my %disk_env;
  788:     if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
  789: 	    &GDBM_READER(),0640)) {
  790: 	return undef;	
  791:     }
  792: 
  793:     if (!defined($disk_env{'user.name'})
  794: 	|| !defined($disk_env{'user.domain'})) {
  795:         untie(%disk_env);
  796: 	return undef;
  797:     }
  798: 
  799:     if (ref($userhashref) eq 'HASH') {
  800:         $userhashref->{'name'} = $disk_env{'user.name'};
  801:         $userhashref->{'domain'} = $disk_env{'user.domain'};
  802:         if ($disk_env{'request.role'}) {
  803:             $userhashref->{'role'} = $disk_env{'request.role'};
  804:         }
  805:         $userhashref->{'lti'} = $disk_env{'request.lti.login'};
  806:         if ($userhashref->{'lti'}) {
  807:             $userhashref->{'ltitarget'} = $disk_env{'request.lti.target'};
  808:             $userhashref->{'ltiuri'} = $disk_env{'request.lti.uri'};
  809:         }
  810:     }
  811:     untie(%disk_env);
  812: 
  813:     return $handle;
  814: }
  815: 
  816: sub timed_flock {
  817:     my ($file,$lock_type) = @_;
  818:     my $failed=0;
  819:     eval {
  820: 	local $SIG{__DIE__}='DEFAULT';
  821: 	local $SIG{ALRM}=sub {
  822: 	    $failed=1;
  823: 	    die("failed lock");
  824: 	};
  825: 	alarm(13);
  826: 	flock($file,$lock_type);
  827: 	alarm(0);
  828:     };
  829:     if ($failed) {
  830: 	return undef;
  831:     } else {
  832: 	return 1;
  833:     }
  834: }
  835: 
  836: sub get_sessionfile_vars {
  837:     my ($handle,$lonidsdir,$storearr) = @_;
  838:     my %returnhash;
  839:     unless (ref($storearr) eq 'ARRAY') {
  840:         return %returnhash;
  841:     }
  842:     if (-l "$lonidsdir/$handle.id") {
  843:         my $link = readlink("$lonidsdir/$handle.id");
  844:         if ((-e $link) && ($link =~ m{^\Q$lonidsdir\E/(.+)\.id$})) {
  845:             $handle = $1;
  846:         }
  847:     }
  848:     if ((-e "$lonidsdir/$handle.id") &&
  849:         ($handle =~ /^($match_username)\_\d+\_($match_domain)\_(.+)$/)) {
  850:         my ($possuname,$possudom,$possuhome) = ($1,$2,$3);
  851:         if ((&domain($possudom) ne '') && (&homeserver($possuname,$possudom) eq $possuhome)) {
  852:             if (open(my $idf,'+<',"$lonidsdir/$handle.id")) {
  853:                 flock($idf,LOCK_SH);
  854:                 if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
  855:                         &GDBM_READER(),0640)) {
  856:                     foreach my $item (@{$storearr}) {
  857:                         $returnhash{$item} = $disk_env{$item};
  858:                     }
  859:                     untie(%disk_env);
  860:                 }
  861:             }
  862:         }
  863:     }
  864:     return %returnhash;
  865: }
  866: 
  867: # ---------------------------------------------------------- Append Environment
  868: 
  869: sub appenv {
  870:     my ($newenv,$roles) = @_;
  871:     if (ref($newenv) eq 'HASH') {
  872:         foreach my $key (keys(%{$newenv})) {
  873:             my $refused = 0;
  874: 	    if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
  875:                 $refused = 1;
  876:                 if (ref($roles) eq 'ARRAY') {
  877:                     my ($type,$role) = ($key =~ m{^user\.(role|priv)\.(.+?)\./});
  878:                     if (grep(/^\Q$role\E$/,@{$roles})) {
  879:                         $refused = 0;
  880:                     }
  881:                 }
  882:             }
  883:             if ($refused) {
  884:                 &logthis("<font color=\"blue\">WARNING: ".
  885:                          "Attempt to modify environment ".$key." to ".$newenv->{$key}
  886:                          .'</font>');
  887: 	        delete($newenv->{$key});
  888:             } else {
  889:                 $env{$key}=$newenv->{$key};
  890:             }
  891:         }
  892:         my $lonids = $perlvar{'lonIDsDir'};
  893:         if ($env{'user.environment'} =~ m{^\Q$lonids/\E$match_username\_\d+\_$match_domain\_[\w\-.]+\.id$}) {
  894:             my $opened = open(my $env_file,'+<',$env{'user.environment'});
  895:             if ($opened
  896: 	        && &timed_flock($env_file,LOCK_EX)
  897: 	        &&
  898: 	        tie(my %disk_env,'GDBM_File',$env{'user.environment'},
  899: 	            (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
  900: 	        while (my ($key,$value) = each(%{$newenv})) {
  901: 	            $disk_env{$key} = $value;
  902: 	        }
  903: 	        untie(%disk_env);
  904:             }
  905:         }
  906:     }
  907:     return 'ok';
  908: }
  909: # ----------------------------------------------------- Delete from Environment
  910: 
  911: sub delenv {
  912:     my ($delthis,$regexp,$roles) = @_;
  913:     if (($delthis=~/^user\.role/) || ($delthis=~/^user\.priv/)) {
  914:         my $refused = 1;
  915:         if (ref($roles) eq 'ARRAY') {
  916:             my ($type,$role) = ($delthis =~ /^user\.(role|priv)\.([^.]+)\./);
  917:             if (grep(/^\Q$role\E$/,@{$roles})) {
  918:                 $refused = 0;
  919:             }
  920:         }
  921:         if ($refused) {
  922:             &logthis("<font color=\"blue\">WARNING: ".
  923:                      "Attempt to delete from environment ".$delthis);
  924:             return 'error';
  925:         }
  926:     }
  927:     my $opened = open(my $env_file,'+<',$env{'user.environment'});
  928:     if ($opened
  929: 	&& &timed_flock($env_file,LOCK_EX)
  930: 	&&
  931: 	tie(my %disk_env,'GDBM_File',$env{'user.environment'},
  932: 	    (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
  933: 	foreach my $key (keys(%disk_env)) {
  934: 	    if ($regexp) {
  935:                 if ($key=~/^$delthis/) {
  936:                     delete($env{$key});
  937:                     delete($disk_env{$key});
  938:                 } 
  939:             } else {
  940:                 if ($key=~/^\Q$delthis\E/) {
  941: 		    delete($env{$key});
  942: 		    delete($disk_env{$key});
  943: 	        }
  944:             }
  945: 	}
  946: 	untie(%disk_env);
  947:     }
  948:     return 'ok';
  949: }
  950: 
  951: sub get_env_multiple {
  952:     my ($name) = @_;
  953:     my @values;
  954:     if (defined($env{$name})) {
  955:         # exists is it an array
  956:         if (ref($env{$name})) {
  957:             @values=@{ $env{$name} };
  958:         } else {
  959:             $values[0]=$env{$name};
  960:         }
  961:     }
  962:     return(@values);
  963: }
  964: 
  965: # ------------------------------------------------------------------- Locking
  966: 
  967: sub set_lock {
  968:     my ($text)=@_;
  969:     $locknum++;
  970:     my $id=$$.'-'.$locknum;
  971:     &appenv({'session.locks' => $env{'session.locks'}.','.$id,
  972:              'session.lock.'.$id => $text});
  973:     return $id;
  974: }
  975: 
  976: sub get_locks {
  977:     my $num=0;
  978:     my %texts=();
  979:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
  980:        if ($lock=~/\w/) {
  981:           $num++;
  982:           $texts{$lock}=$env{'session.lock.'.$lock};
  983:        }
  984:    }
  985:    return ($num,%texts);
  986: }
  987: 
  988: sub remove_lock {
  989:     my ($id)=@_;
  990:     my $newlocks='';
  991:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
  992:        if (($lock=~/\w/) && ($lock ne $id)) {
  993:           $newlocks.=','.$lock;
  994:        }
  995:     }
  996:     &appenv({'session.locks' => $newlocks});
  997:     &delenv('session.lock.'.$id);
  998: }
  999: 
 1000: sub remove_all_locks {
 1001:     my $activelocks=$env{'session.locks'};
 1002:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
 1003:        if ($lock=~/\w/) {
 1004:           &remove_lock($lock);
 1005:        }
 1006:     }
 1007: }
 1008: 
 1009: 
 1010: # ------------------------------------------ Find out current server userload
 1011: sub userload {
 1012:     my $numusers=0;
 1013:     {
 1014: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
 1015: 	my $filename;
 1016: 	my $curtime=time;
 1017: 	while ($filename=readdir(LONIDS)) {
 1018: 	    next if ($filename eq '.' || $filename eq '..');
 1019: 	    next if ($filename =~ /publicuser_\d+\.id/);
 1020:             next if ($filename =~ /^[a-f0-9]+_linked\.id$/);
 1021: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
 1022: 	    if ($curtime-$mtime < 1800) { $numusers++; }
 1023: 	}
 1024: 	closedir(LONIDS);
 1025:     }
 1026:     my $userloadpercent=0;
 1027:     my $maxuserload=$perlvar{'lonUserLoadLim'};
 1028:     if ($maxuserload) {
 1029: 	$userloadpercent=100*$numusers/$maxuserload;
 1030:     }
 1031:     $userloadpercent=sprintf("%.2f",$userloadpercent);
 1032:     return $userloadpercent;
 1033: }
 1034: 
 1035: # ------------------------------ Find server with least workload from spare.tab
 1036: 
 1037: sub spareserver {
 1038:     my ($r,$loadpercent,$userloadpercent,$want_server_name,$udom) = @_;
 1039:     my $spare_server;
 1040:     if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
 1041:     my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent 
 1042:                                                      :  $userloadpercent;
 1043:     my ($uint_dom,$remotesessions);
 1044:     if (($udom ne '') && (&domain($udom) ne '')) {
 1045:         my $uprimary_id = &domain($udom,'primary');
 1046:         $uint_dom = &internet_dom($uprimary_id);
 1047:         my %udomdefaults = &get_domain_defaults($udom);
 1048:         $remotesessions = $udomdefaults{'remotesessions'};
 1049:     }
 1050:     my $spareshash = &this_host_spares($udom);
 1051:     if (ref($spareshash) eq 'HASH') {
 1052:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
 1053:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
 1054:                 next unless (&spare_can_host($udom,$uint_dom,$remotesessions,
 1055:                                              $try_server));
 1056: 	        ($spare_server, $lowest_load) =
 1057: 	            &compare_server_load($try_server, $spare_server, $lowest_load);
 1058:             }
 1059:         }
 1060: 
 1061:         my $found_server = ($spare_server ne '' && $lowest_load < 100);
 1062: 
 1063:         if (!$found_server) {
 1064:             if (ref($spareshash->{'default'}) eq 'ARRAY') { 
 1065: 	        foreach my $try_server (@{ $spareshash->{'default'} }) {
 1066:                     next unless (&spare_can_host($udom,$uint_dom,
 1067:                                                  $remotesessions,$try_server));
 1068: 	            ($spare_server, $lowest_load) =
 1069: 		        &compare_server_load($try_server, $spare_server, $lowest_load);
 1070:                 }
 1071: 	    }
 1072:         }
 1073:     }
 1074: 
 1075:     if (!$want_server_name) {
 1076:         if (defined($spare_server)) {
 1077:             my $hostname = &hostname($spare_server);
 1078:             if (defined($hostname)) {
 1079:                 my $protocol = 'http';
 1080:                 if ($protocol{$spare_server} eq 'https') {
 1081:                     $protocol = $protocol{$spare_server};
 1082:                 }
 1083:                 my $alias = &use_proxy_alias($r,$spare_server);
 1084:                 $hostname = $alias if ($alias ne '');
 1085: 	        $spare_server = $protocol.'://'.$hostname;
 1086:             }
 1087:         }
 1088:     }
 1089:     return $spare_server;
 1090: }
 1091: 
 1092: sub compare_server_load {
 1093:     my ($try_server, $spare_server, $lowest_load, $required) = @_;
 1094: 
 1095:     if ($required) {
 1096:         my ($reqdmajor,$reqdminor) = ($required =~ /^(\d+)\.(\d+)$/);
 1097:         my $remoterev = &get_server_loncaparev(undef,$try_server);
 1098:         my ($major,$minor) = ($remoterev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
 1099:         if (($major eq '' && $minor eq '') ||
 1100:             (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)))) {
 1101:             return ($spare_server,$lowest_load);
 1102:         }
 1103:     }
 1104: 
 1105:     my $loadans     = &reply('load',    $try_server);
 1106:     my $userloadans = &reply('userload',$try_server);
 1107: 
 1108:     if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
 1109: 	return ($spare_server, $lowest_load); #didn't get a number from the server
 1110:     }
 1111: 
 1112:     my $load;
 1113:     if ($loadans =~ /\d/) {
 1114: 	if ($userloadans =~ /\d/) {
 1115: 	    #both are numbers, pick the bigger one
 1116: 	    $load = ($loadans > $userloadans) ? $loadans 
 1117: 		                              : $userloadans;
 1118: 	} else {
 1119: 	    $load = $loadans;
 1120: 	}
 1121:     } else {
 1122: 	$load = $userloadans;
 1123:     }
 1124: 
 1125:     if (($load =~ /\d/) && ($load < $lowest_load)) {
 1126: 	$spare_server = $try_server;
 1127: 	$lowest_load  = $load;
 1128:     }
 1129:     return ($spare_server,$lowest_load);
 1130: }
 1131: 
 1132: # --------------------------- ask offload servers if user already has a session
 1133: sub find_existing_session {
 1134:     my ($udom,$uname) = @_;
 1135:     my $spareshash = &this_host_spares($udom);
 1136:     if (ref($spareshash) eq 'HASH') {
 1137:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
 1138:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
 1139:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
 1140:             }
 1141:         }
 1142:         if (ref($spareshash->{'default'}) eq 'ARRAY') {
 1143:             foreach my $try_server (@{ $spareshash->{'default'} }) {
 1144:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
 1145:             }
 1146:         }
 1147:     }
 1148:     return;
 1149: }
 1150: 
 1151: sub delusersession {
 1152:     my ($lonid,$udom,$uname) = @_;
 1153:     my $uprimary_id = &domain($udom,'primary');
 1154:     my $uintdom = &internet_dom($uprimary_id);
 1155:     my $intdom = &internet_dom($lonid);
 1156:     my $serverhomedom = &host_domain($lonid);
 1157:     if (($uintdom ne '') && ($uintdom eq $intdom)) {
 1158:         return &reply(join(':','delusersession',
 1159:                             map {&escape($_)} ($udom,$uname)),$lonid);
 1160:     }
 1161:     return;
 1162: }
 1163: 
 1164: # check if user's browser sent load balancer cookie and server still has session
 1165: # and is not overloaded.
 1166: sub check_for_balancer_cookie {
 1167:     my ($r,$update_mtime) = @_;
 1168:     my ($otherserver,$cookie);
 1169:     my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
 1170:     if (exists($cookies{'balanceID'})) {
 1171:         my $balid = $cookies{'balanceID'};
 1172:         $cookie=&LONCAPA::clean_handle($balid->value);
 1173:         my $balancedir=$r->dir_config('lonBalanceDir');
 1174:         if ((-d $balancedir) && (-e "$balancedir/$cookie.id")) {
 1175:             if ($cookie =~ /^($match_domain)_($match_username)_[a-f0-9]+$/) {
 1176:                 my ($possudom,$possuname) = ($1,$2);
 1177:                 my $has_session = 0;
 1178:                 if ((&domain($possudom) ne '') &&
 1179:                     (&homeserver($possuname,$possudom) ne 'no_host')) {
 1180:                     my $try_server;
 1181:                     my $opened = open(my $idf,'+<',"$balancedir/$cookie.id");
 1182:                     if ($opened) {
 1183:                         flock($idf,LOCK_SH);
 1184:                         while (my $line = <$idf>) {
 1185:                             chomp($line);
 1186:                             if (&hostname($line) ne '') {
 1187:                                 $try_server = $line;
 1188:                                 last;
 1189:                             }
 1190:                         }
 1191:                         close($idf);
 1192:                         if (($try_server) &&
 1193:                             (&has_user_session($try_server,$possudom,$possuname))) {
 1194:                             my $lowest_load = 30000;
 1195:                             ($otherserver,$lowest_load) =
 1196:                                 &compare_server_load($try_server,undef,$lowest_load);
 1197:                             if ($otherserver ne '' && $lowest_load < 100) {
 1198:                                 $has_session = 1;
 1199:                             } else {
 1200:                                 undef($otherserver);
 1201:                             }
 1202:                         }
 1203:                     }
 1204:                 }
 1205:                 if ($has_session) {
 1206:                     if ($update_mtime) {
 1207:                         my $atime = my $mtime = time;
 1208:                         utime($atime,$mtime,"$balancedir/$cookie.id");
 1209:                     }
 1210:                 } else {
 1211:                     unlink("$balancedir/$cookie.id");
 1212:                 }
 1213:             }
 1214:         }
 1215:     }
 1216:     return ($otherserver,$cookie);
 1217: }
 1218: 
 1219: sub updatebalcookie {
 1220:     my ($cookie,$balancer,$lastentry)=@_;
 1221:     if ($cookie =~ /^($match_domain)\_($match_username)\_[a-f0-9]{32}$/) {
 1222:         my ($udom,$uname) = ($1,$2);
 1223:         my $uprimary_id = &domain($udom,'primary');
 1224:         my $uintdom = &internet_dom($uprimary_id);
 1225:         my $intdom = &internet_dom($balancer);
 1226:         my $serverhomedom = &host_domain($balancer);
 1227:         if (($uintdom ne '') && ($uintdom eq $intdom)) {
 1228:             return &reply('updatebalcookie:'.&escape($cookie).':'.&escape($lastentry),$balancer);
 1229:         }
 1230:     }
 1231:     return;
 1232: }
 1233: 
 1234: sub delbalcookie {
 1235:     my ($cookie,$balancer) =@_;
 1236:     if ($cookie =~ /^($match_domain)\_($match_username)\_[a-f0-9]{32}$/) {
 1237:         my ($udom,$uname) = ($1,$2);
 1238:         my $uprimary_id = &domain($udom,'primary');
 1239:         my $uintdom = &internet_dom($uprimary_id);
 1240:         my $intdom = &internet_dom($balancer);
 1241:         my $serverhomedom = &host_domain($balancer);
 1242:         if (($uintdom ne '') && ($uintdom eq $intdom)) {
 1243:             return &reply('delbalcookie:'.&escape($cookie),$balancer);
 1244:         }
 1245:     }
 1246: }
 1247: 
 1248: # -------------------------------- ask if server already has a session for user
 1249: sub has_user_session {
 1250:     my ($lonid,$udom,$uname) = @_;
 1251:     my $result = &reply(join(':','userhassession',
 1252: 			     map {&escape($_)} ($udom,$uname)),$lonid);
 1253:     return 1 if ($result eq 'ok');
 1254: 
 1255:     return 0;
 1256: }
 1257: 
 1258: # --------- determine least loaded server in a user's domain which allows login
 1259: 
 1260: sub choose_server {
 1261:     my ($udom,$checkloginvia,$required,$skiploadbal) = @_;
 1262:     my %domconfhash = &Apache::loncommon::get_domainconf($udom);
 1263:     my %servers = &get_servers($udom);
 1264:     my $lowest_load = 30000;
 1265:     my ($login_host,$hostname,$portal_path,$isredirect,$balancers);
 1266:     if ($skiploadbal) {
 1267:         ($balancers,my $cached)=&is_cached_new('loadbalancing',$udom);
 1268:         unless (defined($cached)) {
 1269:             my $cachetime = 60*60*24;
 1270:             my %domconfig =
 1271:                 &get_dom('configuration',['loadbalancing'],$udom);
 1272:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
 1273:                 $balancers = &do_cache_new('loadbalancing',$udom,$domconfig{'loadbalancing'},
 1274:                                            $cachetime);
 1275:             }
 1276:         }
 1277:     }
 1278:     foreach my $lonhost (keys(%servers)) {
 1279:         if ($skiploadbal) {
 1280:             if (ref($balancers) eq 'HASH') {
 1281:                 next if (exists($balancers->{$lonhost}));
 1282:             }
 1283:         }
 1284:         my $loginvia;
 1285:         if ($checkloginvia) {
 1286:             $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
 1287:             if ($loginvia) {
 1288:                 my ($server,$path) = split(/:/,$loginvia);
 1289:                 ($login_host, $lowest_load) =
 1290:                     &compare_server_load($server, $login_host, $lowest_load, $required);
 1291:                 if ($login_host eq $server) {
 1292:                     $portal_path = $path;
 1293:                     $isredirect = 1;
 1294:                 }
 1295:             } else {
 1296:                 ($login_host, $lowest_load) =
 1297:                     &compare_server_load($lonhost, $login_host, $lowest_load, $required);
 1298:                 if ($login_host eq $lonhost) {
 1299:                     $portal_path = '';
 1300:                     $isredirect = ''; 
 1301:                 }
 1302:             }
 1303:         } else {
 1304:             ($login_host, $lowest_load) =
 1305:                 &compare_server_load($lonhost, $login_host, $lowest_load, $required);
 1306:         }
 1307:     }
 1308:     if ($login_host ne '') {
 1309:         $hostname = &hostname($login_host);
 1310:     }
 1311:     return ($login_host,$hostname,$portal_path,$isredirect,$lowest_load);
 1312: }
 1313: 
 1314: sub get_course_sessions {
 1315:     my ($cnum,$cdom,$lastactivity) = @_;
 1316:     my %servers = &internet_dom_servers($cdom);
 1317:     my %returnhash;
 1318:     foreach my $server (sort(keys(%servers))) {
 1319:         my $rep = &reply("coursesessions:$cdom:$cnum:$lastactivity",$server);
 1320:         my @pairs=split(/\&/,$rep);
 1321:         unless (($rep eq 'unknown_cmd') || ($rep =~ /^error/)) {
 1322:             foreach my $item (@pairs) {
 1323:                 my ($key,$value)=split(/=/,$item,2);
 1324:                 $key = &unescape($key);
 1325:                 next if ($key =~ /^error: 2 /);
 1326:                 if (exists($returnhash{$key})) {
 1327:                     next if ($value < $returnhash{$key});
 1328:                 }
 1329:                 $returnhash{$key}=$value;
 1330:             }
 1331:         }
 1332:     }
 1333:     return %returnhash;
 1334: }
 1335: 
 1336: # --------------------------------------------- Try to change a user's password
 1337: 
 1338: sub changepass {
 1339:     my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
 1340:     $currentpass = &escape($currentpass);
 1341:     $newpass     = &escape($newpass);
 1342:     my $lonhost = $perlvar{'lonHostID'};
 1343:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
 1344: 		       $server);
 1345:     if (! $answer) {
 1346: 	&logthis("No reply on password change request to $server ".
 1347: 		 "by $uname in domain $udom.");
 1348:     } elsif ($answer =~ "^ok") {
 1349:         &logthis("$uname in $udom successfully changed their password ".
 1350: 		 "on $server.");
 1351:     } elsif ($answer =~ "^pwchange_failure") {
 1352: 	&logthis("$uname in $udom was unable to change their password ".
 1353: 		 "on $server.  The action was blocked by either lcpasswd ".
 1354: 		 "or pwchange");
 1355:     } elsif ($answer =~ "^non_authorized") {
 1356:         &logthis("$uname in $udom did not get their password correct when ".
 1357: 		 "attempting to change it on $server.");
 1358:     } elsif ($answer =~ "^auth_mode_error") {
 1359:         &logthis("$uname in $udom attempted to change their password despite ".
 1360: 		 "not being locally or internally authenticated on $server.");
 1361:     } elsif ($answer =~ "^unknown_user") {
 1362:         &logthis("$uname in $udom attempted to change their password ".
 1363: 		 "on $server but were unable to because $server is not ".
 1364: 		 "their home server.");
 1365:     } elsif ($answer =~ "^refused") {
 1366: 	&logthis("$server refused to change $uname in $udom password because ".
 1367: 		 "it was sent an unencrypted request to change the password.");
 1368:     } elsif ($answer =~ "invalid_client") {
 1369:         &logthis("$server refused to change $uname in $udom password because ".
 1370:                  "it was a reset by e-mail originating from an invalid server.");
 1371:     } elsif ($answer =~ "^prioruse") {
 1372:        &logthis("$server refused to change $uname in $udom password because ".
 1373:                 "the password had been used before");
 1374:     }
 1375:     return $answer;
 1376: }
 1377: 
 1378: # ----------------------- Try to determine user's current authentication scheme
 1379: 
 1380: sub queryauthenticate {
 1381:     my ($uname,$udom)=@_;
 1382:     my $uhome=&homeserver($uname,$udom);
 1383:     if ((!$uhome) || ($uhome eq 'no_host')) {
 1384: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
 1385: 	return 'no_host';
 1386:     }
 1387:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
 1388:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
 1389: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
 1390:     }
 1391:     return $answer;
 1392: }
 1393: 
 1394: # --------- Try to authenticate user from domain's lib servers (first this one)
 1395: 
 1396: sub authenticate {
 1397:     my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
 1398:     $upass=&escape($upass);
 1399:     $uname= &LONCAPA::clean_username($uname);
 1400:     my $uhome=&homeserver($uname,$udom,1);
 1401:     my $newhome;
 1402:     if ((!$uhome) || ($uhome eq 'no_host')) {
 1403: # Maybe the machine was offline and only re-appeared again recently?
 1404:         &reconlonc();
 1405: # One more
 1406: 	$uhome=&homeserver($uname,$udom,1);
 1407:         if (($uhome eq 'no_host') && $checkdefauth) {
 1408:             if (defined(&domain($udom,'primary'))) {
 1409:                 $newhome=&domain($udom,'primary');
 1410:             }
 1411:             if ($newhome ne '') {
 1412:                 $uhome = $newhome;
 1413:             }
 1414:         }
 1415: 	if ((!$uhome) || ($uhome eq 'no_host')) {
 1416: 	    &logthis("User $uname at $udom is unknown in authenticate");
 1417: 	    return 'no_host';
 1418:         }
 1419:     }
 1420:     my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
 1421:     if ($answer eq 'authorized') {
 1422:         if ($newhome) {
 1423:             &logthis("User $uname at $udom authorized by $uhome, but needs account");
 1424:             return 'no_account_on_host'; 
 1425:         } else {
 1426:             &logthis("User $uname at $udom authorized by $uhome");
 1427:             return $uhome;
 1428:         }
 1429:     }
 1430:     if ($answer eq 'non_authorized') {
 1431: 	&logthis("User $uname at $udom rejected by $uhome");
 1432: 	return 'no_host';
 1433:     }
 1434:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
 1435:     return 'no_host';
 1436: }
 1437: 
 1438: sub can_switchserver {
 1439:     my ($udom,$home) = @_;
 1440:     my ($canswitch,@intdoms);
 1441:     my $internet_names = &get_internet_names($home);
 1442:     if (ref($internet_names) eq 'ARRAY') {
 1443:         @intdoms = @{$internet_names};
 1444:     }
 1445:     my $uint_dom = &internet_dom(&domain($udom,'primary'));
 1446:     if ($uint_dom ne '' && grep(/^\Q$uint_dom\E$/,@intdoms)) {
 1447:         $canswitch = 1;
 1448:     } else {
 1449:          my $serverhomeID = &get_server_homeID(&hostname($home));
 1450:          my $serverhomedom = &host_domain($serverhomeID);
 1451:          my %defdomdefaults = &get_domain_defaults($serverhomedom);
 1452:          my %udomdefaults = &get_domain_defaults($udom);
 1453:          my $remoterev = &get_server_loncaparev('',$home);
 1454:          $canswitch = &can_host_session($udom,$home,$remoterev,
 1455:                                         $udomdefaults{'remotesessions'},
 1456:                                         $defdomdefaults{'hostedsessions'});
 1457:     }
 1458:     return $canswitch;
 1459: }
 1460: 
 1461: sub can_host_session {
 1462:     my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
 1463:     my $canhost = 1;
 1464:     my $host_idn = &internet_dom($lonhost);
 1465:     if (ref($remotesessions) eq 'HASH') {
 1466:         if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
 1467:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
 1468:                 $canhost = 0;
 1469:             } else {
 1470:                 $canhost = 1;
 1471:             }
 1472:         }
 1473:         if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
 1474:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
 1475:                 $canhost = 1;
 1476:             } else {
 1477:                 $canhost = 0;
 1478:             }
 1479:         }
 1480:         if ($canhost) {
 1481:             if ($remotesessions->{'version'} ne '') {
 1482:                 my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
 1483:                 if ($reqmajor ne '' && $reqminor ne '') {
 1484:                     if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
 1485:                         my $major = $1;
 1486:                         my $minor = $2;
 1487:                         if (($major < $reqmajor ) ||
 1488:                             (($major == $reqmajor) && ($minor < $reqminor))) {
 1489:                             $canhost = 0;
 1490:                         }
 1491:                     } else {
 1492:                         $canhost = 0;
 1493:                     }
 1494:                 }
 1495:             }
 1496:         }
 1497:     }
 1498:     if ($canhost) {
 1499:         if (ref($hostedsessions) eq 'HASH') {
 1500:             my $uprimary_id = &domain($udom,'primary');
 1501:             my $uint_dom = &internet_dom($uprimary_id);
 1502:             if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
 1503:                 if (($uint_dom ne '') && 
 1504:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'excludedomain'}}))) {
 1505:                     $canhost = 0;
 1506:                 } else {
 1507:                     $canhost = 1;
 1508:                 }
 1509:             }
 1510:             if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
 1511:                 if (($uint_dom ne '') && 
 1512:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'includedomain'}}))) {
 1513:                     $canhost = 1;
 1514:                 } else {
 1515:                     $canhost = 0;
 1516:                 }
 1517:             }
 1518:         }
 1519:     }
 1520:     return $canhost;
 1521: }
 1522: 
 1523: sub spare_can_host {
 1524:     my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
 1525:     my $canhost=1;
 1526:     my $try_server_hostname = &hostname($try_server);
 1527:     my $serverhomeID = &get_server_homeID($try_server_hostname);
 1528:     my $serverhomedom = &host_domain($serverhomeID);
 1529:     my %defdomdefaults = &get_domain_defaults($serverhomedom);
 1530:     if (ref($defdomdefaults{'offloadnow'}) eq 'HASH') {
 1531:         if ($defdomdefaults{'offloadnow'}{$try_server}) {
 1532:             $canhost = 0;
 1533:         }
 1534:     }
 1535:     if ($canhost) {
 1536:         if (ref($defdomdefaults{'offloadoth'}) eq 'HASH') {
 1537:             if ($defdomdefaults{'offloadoth'}{$try_server}) {
 1538:                 unless (&shared_institution($udom,$try_server)) {
 1539:                     $canhost = 0;
 1540:                 }
 1541:             }
 1542:         }
 1543:     }
 1544:     if (($canhost) && ($uint_dom)) {
 1545:         my @intdoms;
 1546:         my $internet_names = &get_internet_names($try_server);
 1547:         if (ref($internet_names) eq 'ARRAY') {
 1548:             @intdoms = @{$internet_names};
 1549:         }
 1550:         unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
 1551:             my $remoterev = &get_server_loncaparev(undef,$try_server);
 1552:             $canhost = &can_host_session($udom,$try_server,$remoterev,
 1553:                                          $remotesessions,
 1554:                                          $defdomdefaults{'hostedsessions'});
 1555:         }
 1556:     }
 1557:     return $canhost;
 1558: }
 1559: 
 1560: sub this_host_spares {
 1561:     my ($dom) = @_;
 1562:     my ($dom_in_use,$lonhost_in_use,$result);
 1563:     my @hosts = &current_machine_ids();
 1564:     foreach my $lonhost (@hosts) {
 1565:         if (&host_domain($lonhost) eq $dom) {
 1566:             $dom_in_use = $dom;
 1567:             $lonhost_in_use = $lonhost;
 1568:             last;
 1569:         }
 1570:     }
 1571:     if ($dom_in_use ne '') {
 1572:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
 1573:     }
 1574:     if (ref($result) ne 'HASH') {
 1575:         $lonhost_in_use = $perlvar{'lonHostID'};
 1576:         $dom_in_use = &host_domain($lonhost_in_use);
 1577:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
 1578:         if (ref($result) ne 'HASH') {
 1579:             $result = \%spareid;
 1580:         }
 1581:     }
 1582:     return $result;
 1583: }
 1584: 
 1585: sub spares_for_offload  {
 1586:     my ($dom_in_use,$lonhost_in_use) = @_;
 1587:     my ($result,$cached)=&is_cached_new('spares',$dom_in_use);
 1588:     if (defined($cached)) {
 1589:         return $result;
 1590:     } else {
 1591:         my $cachetime = 60*60*24;
 1592:         my %domconfig =
 1593:             &get_dom('configuration',['usersessions'],$dom_in_use);
 1594:         if (ref($domconfig{'usersessions'}) eq 'HASH') {
 1595:             if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
 1596:                 if (ref($domconfig{'usersessions'}{'spares'}{$lonhost_in_use}) eq 'HASH') {
 1597:                     return &do_cache_new('spares',$dom_in_use,$domconfig{'usersessions'}{'spares'}{$lonhost_in_use},$cachetime);
 1598:                 }
 1599:             }
 1600:         }
 1601:     }
 1602:     return;
 1603: }
 1604: 
 1605: sub get_lonbalancer_config {
 1606:     my ($servers) = @_;
 1607:     my ($currbalancer,$currtargets);
 1608:     if (ref($servers) eq 'HASH') {
 1609:         foreach my $server (keys(%{$servers})) {
 1610:             my %what = (
 1611:                          spareid => 1,
 1612:                          perlvar => 1,
 1613:                        );
 1614:             my ($result,$returnhash) = &get_remote_globals($server,\%what);
 1615:             if ($result eq 'ok') {
 1616:                 if (ref($returnhash) eq 'HASH') {
 1617:                     if (ref($returnhash->{'perlvar'}) eq 'HASH') {
 1618:                         if ($returnhash->{'perlvar'}->{'lonBalancer'} eq 'yes') {
 1619:                             $currbalancer = $server;
 1620:                             $currtargets = {};
 1621:                             if (ref($returnhash->{'spareid'}) eq 'HASH') {
 1622:                                 if (ref($returnhash->{'spareid'}->{'primary'}) eq 'ARRAY') {
 1623:                                     $currtargets->{'primary'} = $returnhash->{'spareid'}->{'primary'};
 1624:                                 }
 1625:                                 if (ref($returnhash->{'spareid'}->{'default'}) eq 'ARRAY') {
 1626:                                     $currtargets->{'default'} = $returnhash->{'spareid'}->{'default'};
 1627:                                 }
 1628:                             }
 1629:                             last;
 1630:                         }
 1631:                     }
 1632:                 }
 1633:             }
 1634:         }
 1635:     }
 1636:     return ($currbalancer,$currtargets);
 1637: }
 1638: 
 1639: sub check_loadbalancing {
 1640:     my ($uname,$udom,$caller) = @_;
 1641:     my ($is_balancer,$currtargets,$currrules,$dom_in_use,$homeintdom,
 1642:         $rule_in_effect,$offloadto,$otherserver,$setcookie,$dom_balancers);
 1643:     my $lonhost = $perlvar{'lonHostID'};
 1644:     my @hosts = &current_machine_ids();
 1645:     my $uprimary_id = &domain($udom,'primary');
 1646:     my $uintdom = &internet_dom($uprimary_id);
 1647:     my $intdom = &internet_dom($lonhost);
 1648:     my $serverhomedom = &host_domain($lonhost);
 1649:     my $domneedscache;
 1650:     my $cachetime = 60*60*24;
 1651: 
 1652:     if (($uintdom ne '') && ($uintdom eq $intdom)) {
 1653:         $dom_in_use = $udom;
 1654:         $homeintdom = 1;
 1655:     } else {
 1656:         $dom_in_use = $serverhomedom;
 1657:     }
 1658:     my ($result,$cached)=&is_cached_new('loadbalancing',$dom_in_use);
 1659:     unless (defined($cached)) {
 1660:         my %domconfig =
 1661:             &get_dom('configuration',['loadbalancing'],$dom_in_use);
 1662:         if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
 1663:             $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
 1664:         } else {
 1665:             $domneedscache = $dom_in_use;
 1666:         }
 1667:     }
 1668:     if (ref($result) eq 'HASH') {
 1669:         ($is_balancer,$currtargets,$currrules,$setcookie,$dom_balancers) =
 1670:             &check_balancer_result($result,@hosts);
 1671:         if ($is_balancer) {
 1672:             if (ref($currrules) eq 'HASH') {
 1673:                 if ($homeintdom) {
 1674:                     if ($uname ne '') {
 1675:                         if (($currrules->{'_LC_adv'} ne '') || ($currrules->{'_LC_author'} ne '')) {
 1676:                             my ($is_adv,$is_author) = &is_advanced_user($udom,$uname);
 1677:                             if (($currrules->{'_LC_author'} ne '') && ($is_author)) {
 1678:                                 $rule_in_effect = $currrules->{'_LC_author'};
 1679:                             } elsif (($currrules->{'_LC_adv'} ne '') && ($is_adv)) {
 1680:                                 $rule_in_effect = $currrules->{'_LC_adv'}
 1681:                             }
 1682:                         }
 1683:                         if ($rule_in_effect eq '') {
 1684:                             my %userenv = &userenvironment($udom,$uname,'inststatus');
 1685:                             if ($userenv{'inststatus'} ne '') {
 1686:                                 my @statuses = map { &unescape($_); } split(/:/,$userenv{'inststatus'});
 1687:                                 my ($othertitle,$usertypes,$types) =
 1688:                                     &Apache::loncommon::sorted_inst_types($udom);
 1689:                                 if (ref($types) eq 'ARRAY') {
 1690:                                     foreach my $type (@{$types}) {
 1691:                                         if (grep(/^\Q$type\E$/,@statuses)) {
 1692:                                             if (exists($currrules->{$type})) {
 1693:                                                 $rule_in_effect = $currrules->{$type};
 1694:                                             }
 1695:                                         }
 1696:                                     }
 1697:                                 }
 1698:                             } else {
 1699:                                 if (exists($currrules->{'default'})) {
 1700:                                     $rule_in_effect = $currrules->{'default'};
 1701:                                 }
 1702:                             }
 1703:                         }
 1704:                     } else {
 1705:                         if (exists($currrules->{'default'})) {
 1706:                             $rule_in_effect = $currrules->{'default'};
 1707:                         }
 1708:                     }
 1709:                 } else {
 1710:                     if ($currrules->{'_LC_external'} ne '') {
 1711:                         $rule_in_effect = $currrules->{'_LC_external'};
 1712:                     }
 1713:                 }
 1714:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
 1715:                                                        $uname,$udom);
 1716:             }
 1717:         }
 1718:     } elsif (($homeintdom) && ($udom ne $serverhomedom)) {
 1719:         ($result,$cached)=&is_cached_new('loadbalancing',$serverhomedom);
 1720:         unless (defined($cached)) {
 1721:             my %domconfig =
 1722:                 &get_dom('configuration',['loadbalancing'],$serverhomedom);
 1723:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
 1724:                 $result = &do_cache_new('loadbalancing',$serverhomedom,$domconfig{'loadbalancing'},$cachetime);
 1725:             } else {
 1726:                 $domneedscache = $serverhomedom;
 1727:             }
 1728:         }
 1729:         if (ref($result) eq 'HASH') {
 1730:             ($is_balancer,$currtargets,$currrules,$setcookie,$dom_balancers) =
 1731:                 &check_balancer_result($result,@hosts);
 1732:             if ($is_balancer) {
 1733:                 if (ref($currrules) eq 'HASH') {
 1734:                     if ($currrules->{'_LC_internetdom'} ne '') {
 1735:                         $rule_in_effect = $currrules->{'_LC_internetdom'};
 1736:                     }
 1737:                 }
 1738:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
 1739:                                                        $uname,$udom);
 1740:             }
 1741:         } else {
 1742:             if ($perlvar{'lonBalancer'} eq 'yes') {
 1743:                 $is_balancer = 1;
 1744:                 $offloadto = &this_host_spares($dom_in_use);
 1745:             }
 1746:             unless (defined($cached)) {
 1747:                 $domneedscache = $serverhomedom;
 1748:             }
 1749:         }
 1750:     } else {
 1751:         if ($perlvar{'lonBalancer'} eq 'yes') {
 1752:             $is_balancer = 1;
 1753:             $offloadto = &this_host_spares($dom_in_use);
 1754:         }
 1755:         unless (defined($cached)) {
 1756:             $domneedscache = $serverhomedom;
 1757:         }
 1758:     }
 1759:     if ($domneedscache) {
 1760:         &do_cache_new('loadbalancing',$domneedscache,$is_balancer,$cachetime);
 1761:     }
 1762:     if (($is_balancer) && ($caller ne 'switchserver')) {
 1763:         my $lowest_load = 30000;
 1764:         if (ref($offloadto) eq 'HASH') {
 1765:             if (ref($offloadto->{'primary'}) eq 'ARRAY') {
 1766:                 foreach my $try_server (@{$offloadto->{'primary'}}) {
 1767:                     ($otherserver,$lowest_load) =
 1768:                         &compare_server_load($try_server,$otherserver,$lowest_load);
 1769:                 }
 1770:             }
 1771:             my $found_server = ($otherserver ne '' && $lowest_load < 100);
 1772: 
 1773:             if (!$found_server) {
 1774:                 if (ref($offloadto->{'default'}) eq 'ARRAY') {
 1775:                     foreach my $try_server (@{$offloadto->{'default'}}) {
 1776:                         ($otherserver,$lowest_load) =
 1777:                             &compare_server_load($try_server,$otherserver,$lowest_load);
 1778:                     }
 1779:                 }
 1780:             }
 1781:         } elsif (ref($offloadto) eq 'ARRAY') {
 1782:             if (@{$offloadto} == 1) {
 1783:                 $otherserver = $offloadto->[0];
 1784:             } elsif (@{$offloadto} > 1) {
 1785:                 foreach my $try_server (@{$offloadto}) {
 1786:                     ($otherserver,$lowest_load) =
 1787:                         &compare_server_load($try_server,$otherserver,$lowest_load);
 1788:                 }
 1789:             }
 1790:         }
 1791:         unless ($caller eq 'login') {
 1792:             if (($otherserver ne '') && (grep(/^\Q$otherserver\E$/,@hosts))) {
 1793:                 $is_balancer = 0;
 1794:                 if ($uname ne '' && $udom ne '') {
 1795:                     if (($env{'user.name'} eq $uname) && ($env{'user.domain'} eq $udom)) {
 1796:                         &appenv({'user.loadbalexempt'     => $lonhost,
 1797:                                  'user.loadbalcheck.time' => time});
 1798:                     }
 1799:                 }
 1800:             }
 1801:         }
 1802:     }
 1803:     if (($is_balancer) && (!$homeintdom)) {
 1804:         undef($setcookie);
 1805:     }
 1806:     return ($is_balancer,$otherserver,$setcookie,$offloadto,$dom_balancers);
 1807: }
 1808: 
 1809: sub check_balancer_result {
 1810:     my ($result,@hosts) = @_;
 1811:     my ($is_balancer,$currtargets,$currrules,$setcookie,$dom_balancers);
 1812:     if (ref($result) eq 'HASH') {
 1813:         if ($result->{'lonhost'} ne '') {
 1814:             my $currbalancer = $result->{'lonhost'};
 1815:             if (grep(/^\Q$currbalancer\E$/,@hosts)) {
 1816:                 $is_balancer = 1;
 1817:                 $currtargets = $result->{'targets'};
 1818:                 $currrules = $result->{'rules'};
 1819:             }
 1820:             $dom_balancers = $currbalancer;
 1821:         } else {
 1822:             if (keys(%{$result})) {
 1823:                 foreach my $key (keys(%{$result})) {
 1824:                     if (($key ne '') && (grep(/^\Q$key\E$/,@hosts)) &&
 1825:                         (ref($result->{$key}) eq 'HASH')) {
 1826:                         $is_balancer = 1;
 1827:                         $currrules = $result->{$key}{'rules'};
 1828:                         $currtargets = $result->{$key}{'targets'};
 1829:                         $setcookie = $result->{$key}{'cookie'};
 1830:                         last;
 1831:                     }
 1832:                 }
 1833:                 $dom_balancers = join(',',sort(keys(%{$result})));
 1834:             }
 1835:         }
 1836:     }
 1837:     return ($is_balancer,$currtargets,$currrules,$setcookie,$dom_balancers);
 1838: }
 1839: 
 1840: sub get_loadbalancer_targets {
 1841:     my ($rule_in_effect,$currtargets,$uname,$udom) = @_;
 1842:     my $offloadto;
 1843:     if ($rule_in_effect eq 'none') {
 1844:         return [$perlvar{'lonHostID'}];
 1845:     } elsif ($rule_in_effect eq '') {
 1846:         $offloadto = $currtargets;
 1847:     } else {
 1848:         if ($rule_in_effect eq 'homeserver') {
 1849:             my $homeserver = &homeserver($uname,$udom);
 1850:             if ($homeserver ne 'no_host') {
 1851:                 $offloadto = [$homeserver];
 1852:             }
 1853:         } elsif ($rule_in_effect eq 'externalbalancer') {
 1854:             my %domconfig =
 1855:                 &get_dom('configuration',['loadbalancing'],$udom);
 1856:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
 1857:                 if ($domconfig{'loadbalancing'}{'lonhost'} ne '') {
 1858:                     if (&hostname($domconfig{'loadbalancing'}{'lonhost'}) ne '') {
 1859:                         $offloadto = [$domconfig{'loadbalancing'}{'lonhost'}];
 1860:                     }
 1861:                 }
 1862:             } else {
 1863:                 my %servers = &internet_dom_servers($udom);
 1864:                 my ($remotebalancer,$remotetargets) = &get_lonbalancer_config(\%servers);
 1865:                 if (&hostname($remotebalancer) ne '') {
 1866:                     $offloadto = [$remotebalancer];
 1867:                 }
 1868:             }
 1869:         } elsif (&hostname($rule_in_effect) ne '') {
 1870:             $offloadto = [$rule_in_effect];
 1871:         }
 1872:     }
 1873:     return $offloadto;
 1874: }
 1875: 
 1876: sub internet_dom_servers {
 1877:     my ($dom) = @_;
 1878:     my (%uniqservers,%servers);
 1879:     my $primaryserver = &hostname(&domain($dom,'primary'));
 1880:     my @machinedoms = &machine_domains($primaryserver);
 1881:     foreach my $mdom (@machinedoms) {
 1882:         my %currservers = %servers;
 1883:         my %server = &get_servers($mdom);
 1884:         %servers = (%currservers,%server);
 1885:     }
 1886:     my %by_hostname;
 1887:     foreach my $id (keys(%servers)) {
 1888:         push(@{$by_hostname{$servers{$id}}},$id);
 1889:     }
 1890:     foreach my $hostname (sort(keys(%by_hostname))) {
 1891:         if (@{$by_hostname{$hostname}} > 1) {
 1892:             my $match = 0;
 1893:             foreach my $id (@{$by_hostname{$hostname}}) {
 1894:                 if (&host_domain($id) eq $dom) {
 1895:                     $uniqservers{$id} = $hostname;
 1896:                     $match = 1;
 1897:                 }
 1898:             }
 1899:             unless ($match) {
 1900:                 $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
 1901:             }
 1902:         } else {
 1903:             $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
 1904:         }
 1905:     }
 1906:     return %uniqservers;
 1907: }
 1908: 
 1909: sub trusted_domains {
 1910:     my ($cmdtype,$calldom) = @_;
 1911:     my ($trusted,$untrusted);
 1912:     if (&domain($calldom) eq '') {
 1913:         return ($trusted,$untrusted);
 1914:     }
 1915:     unless ($cmdtype =~ /^(content|shared|enroll|coaurem|othcoau|domroles|catalog|reqcrs|msg)$/) {
 1916:         return ($trusted,$untrusted);
 1917:     }
 1918:     my $callprimary = &domain($calldom,'primary');
 1919:     my $intcalldom = &internet_dom($callprimary);
 1920:     if ($intcalldom eq '') {
 1921:         return ($trusted,$untrusted);
 1922:     }
 1923: 
 1924:     my ($trustconfig,$cached)=&is_cached_new('trust',$calldom);
 1925:     unless (defined($cached)) {
 1926:         my %domconfig = &get_dom('configuration',['trust'],$calldom);
 1927:         &do_cache_new('trust',$calldom,$domconfig{'trust'},3600);
 1928:         $trustconfig = $domconfig{'trust'};
 1929:     }
 1930:     if (ref($trustconfig)) {
 1931:         my (%possexc,%possinc,@allexc,@allinc); 
 1932:         if (ref($trustconfig->{$cmdtype}) eq 'HASH') {
 1933:             if (ref($trustconfig->{$cmdtype}->{'exc'}) eq 'ARRAY') {
 1934:                 map { $possexc{$_} = 1; } @{$trustconfig->{$cmdtype}->{'exc'}}; 
 1935:             }
 1936:             if (ref($trustconfig->{$cmdtype}->{'inc'}) eq 'ARRAY') {
 1937:                 $possinc{$intcalldom} = 1;
 1938:                 map { $possinc{$_} = 1; } @{$trustconfig->{$cmdtype}->{'inc'}};
 1939:             }
 1940:         }
 1941:         if (keys(%possexc)) {
 1942:             if (keys(%possinc)) {
 1943:                 foreach my $key (sort(keys(%possexc))) {
 1944:                     next if ($key eq $intcalldom);
 1945:                     unless ($possinc{$key}) {
 1946:                         push(@allexc,$key);
 1947:                     }
 1948:                 }
 1949:             } else {
 1950:                 @allexc = sort(keys(%possexc));
 1951:             }
 1952:         }
 1953:         if (keys(%possinc)) {
 1954:             $possinc{$intcalldom} = 1;
 1955:             @allinc = sort(keys(%possinc));
 1956:         }
 1957:         if ((@allexc > 0) || (@allinc > 0)) {
 1958:             my %doms_by_intdom;
 1959:             my %allintdoms = &all_host_intdom();
 1960:             my %alldoms = &all_host_domain();
 1961:             foreach my $key (%allintdoms) {
 1962:                 if (ref($doms_by_intdom{$allintdoms{$key}}) eq 'ARRAY') {
 1963:                     unless (grep(/^\Q$alldoms{$key}\E$/,@{$doms_by_intdom{$allintdoms{$key}}})) {
 1964:                         push(@{$doms_by_intdom{$allintdoms{$key}}},$alldoms{$key});
 1965:                     }
 1966:                 } else {
 1967:                     $doms_by_intdom{$allintdoms{$key}} = [$alldoms{$key}]; 
 1968:                 }
 1969:             }
 1970:             foreach my $exc (@allexc) {
 1971:                 if (ref($doms_by_intdom{$exc}) eq 'ARRAY') {
 1972:                     push(@{$untrusted},@{$doms_by_intdom{$exc}});
 1973:                 }
 1974:             }
 1975:             foreach my $inc (@allinc) {
 1976:                 if (ref($doms_by_intdom{$inc}) eq 'ARRAY') {
 1977:                     push(@{$trusted},@{$doms_by_intdom{$inc}});
 1978:                 }
 1979:             }
 1980:         }
 1981:     }
 1982:     return ($trusted,$untrusted);
 1983: }
 1984: 
 1985: sub will_trust {
 1986:     my ($cmdtype,$domain,$possdom) = @_;
 1987:     return 1 if ($domain eq $possdom);
 1988:     my ($trustedref,$untrustedref) = &trusted_domains($cmdtype,$possdom);
 1989:     my $willtrust; 
 1990:     if ((ref($trustedref) eq 'ARRAY') && (@{$trustedref} > 0)) {
 1991:         if (grep(/^\Q$domain\E$/,@{$trustedref})) {
 1992:             $willtrust = 1;
 1993:         }
 1994:     } elsif ((ref($untrustedref) eq 'ARRAY') && (@{$untrustedref} > 0)) {
 1995:         unless (grep(/^\Q$domain\E$/,@{$untrustedref})) {
 1996:             $willtrust = 1;
 1997:         }
 1998:     } else {
 1999:         $willtrust = 1;
 2000:     }
 2001:     return $willtrust;
 2002: }
 2003: 
 2004: # ---------------------- Find the homebase for a user from domain's lib servers
 2005: 
 2006: my %homecache;
 2007: sub homeserver {
 2008:     my ($uname,$udom,$ignoreBadCache)=@_;
 2009:     my $index="$uname:$udom";
 2010: 
 2011:     if (exists($homecache{$index})) { return $homecache{$index}; }
 2012: 
 2013:     my %servers = &get_servers($udom,'library');
 2014:     foreach my $tryserver (keys(%servers)) {
 2015:         next if ($ignoreBadCache ne 'true' && 
 2016: 		 exists($badServerCache{$tryserver}));
 2017: 
 2018: 	my $answer=reply("home:$udom:$uname",$tryserver);
 2019: 	if ($answer eq 'found') {
 2020: 	    delete($badServerCache{$tryserver}); 
 2021: 	    return $homecache{$index}=$tryserver;
 2022: 	} elsif ($answer eq 'no_host') {
 2023: 	    $badServerCache{$tryserver}=1;
 2024: 	}
 2025:     }    
 2026:     return 'no_host';
 2027: }
 2028: 
 2029: # ----- Find the usernames behind a list of student/employee IDs or clicker IDs
 2030: 
 2031: sub idget {
 2032:     my ($udom,$idsref,$namespace)=@_;
 2033:     my %returnhash=();
 2034:     my @ids=(); 
 2035:     if (ref($idsref) eq 'ARRAY') {
 2036:         @ids = @{$idsref};
 2037:     } else {
 2038:         return %returnhash; 
 2039:     }
 2040:     if ($namespace eq '') {
 2041:         $namespace = 'ids';
 2042:     }
 2043:     
 2044:     my %servers = &get_servers($udom,'library');
 2045:     foreach my $tryserver (keys(%servers)) {
 2046: 	my $idlist=join('&', map { &escape($_); } @ids);
 2047: 	if ($namespace eq 'ids') {
 2048: 	    $idlist=~tr/A-Z/a-z/;
 2049: 	}
 2050: 	my $reply;
 2051: 	if ($namespace eq 'ids') {
 2052: 	    $reply=&reply("idget:$udom:".$idlist,$tryserver);
 2053: 	} else {
 2054: 	    $reply=&reply("getdom:$udom:$namespace:$idlist",$tryserver);
 2055: 	}
 2056: 	my @answer=();
 2057: 	if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
 2058: 	    @answer=split(/\&/,$reply);
 2059: 	}                    ;
 2060: 	my $i;
 2061: 	for ($i=0;$i<=$#ids;$i++) {
 2062: 	    if ($answer[$i]) {
 2063: 		$returnhash{$ids[$i]}=&unescape($answer[$i]);
 2064: 	    }
 2065: 	}
 2066:     }
 2067:     return %returnhash;
 2068: }
 2069: 
 2070: # ------------------------------------- Find the IDs behind a list of usernames
 2071: 
 2072: sub idrget {
 2073:     my ($udom,@unames)=@_;
 2074:     my %returnhash=();
 2075:     foreach my $uname (@unames) {
 2076:         $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
 2077:     }
 2078:     return %returnhash;
 2079: }
 2080: 
 2081: # Store away a list of names and associated student/employee IDs or clicker IDs
 2082: 
 2083: sub idput {
 2084:     my ($udom,$idsref,$uhom,$namespace)=@_;
 2085:     my %servers=();
 2086:     my %ids=();
 2087:     my %byid = ();
 2088:     if (ref($idsref) eq 'HASH') {
 2089:         %ids=%{$idsref};
 2090:     }
 2091:     if ($namespace eq '') {
 2092:         $namespace = 'ids'; 
 2093:     }
 2094:     foreach my $uname (keys(%ids)) {
 2095: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
 2096:         if ($uhom eq '') {
 2097:             $uhom=&homeserver($uname,$udom);
 2098:         }
 2099:         if ($uhom ne 'no_host') {
 2100:             my $esc_unam=&escape($uname);
 2101:             if ($namespace eq 'ids') {
 2102:                 my $id=&escape($ids{$uname});
 2103:                 $id=~tr/A-Z/a-z/;
 2104:                 my $esc_unam=&escape($uname);
 2105:                 $servers{$uhom}.=$id.'='.$esc_unam.'&';
 2106:             } else {
 2107:                 my @currids = split(/,/,$ids{$uname});
 2108:                 foreach my $id (@currids) {
 2109:                     $byid{$uhom}{$id} .= $uname.',';
 2110:                 }
 2111:             }
 2112:         }
 2113:     }
 2114:     if ($namespace eq 'clickers') {
 2115:         foreach my $server (keys(%byid)) {
 2116:             if (ref($byid{$server}) eq 'HASH') {
 2117:                 foreach my $id (keys(%{$byid{$server}})) {
 2118:                     $byid{$server} =~ s/,$//;
 2119:                     $servers{$uhom}.=&escape($id).'='.&escape($byid{$server}).'&'; 
 2120:                 }
 2121:             }
 2122:         }
 2123:     }
 2124:     foreach my $server (keys(%servers)) {
 2125:         $servers{$server} =~ s/\&$//;
 2126:         if ($namespace eq 'ids') {     
 2127:             &critical('idput:'.$udom.':'.$servers{$server},$server);
 2128:         } else {
 2129:             &critical('updateclickers:'.$udom.':add:'.$servers{$server},$server);
 2130:         }
 2131:     }
 2132: }
 2133: 
 2134: # ------------- Delete unwanted student/employee IDs or clicker IDs from domain
 2135: 
 2136: sub iddel {
 2137:     my ($udom,$idshashref,$uhome,$namespace)=@_;
 2138:     my %result=();
 2139:     my %ids=();
 2140:     my %byid = ();
 2141:     if (ref($idshashref) eq 'HASH') {
 2142:         %ids=%{$idshashref};
 2143:     } else {
 2144:         return %result;
 2145:     }
 2146:     if ($namespace eq '') {
 2147:         $namespace = 'ids';
 2148:     }
 2149:     my %servers=();
 2150:     while (my ($id,$unamestr) = each(%ids)) {
 2151:         if ($namespace eq 'ids') {
 2152:             my $uhom = $uhome;
 2153:             if ($uhom eq '') { 
 2154:                 $uhom=&homeserver($unamestr,$udom);
 2155:             }
 2156:             if ($uhom ne 'no_host') {
 2157:                 $servers{$uhom}.='&'.&escape($id);
 2158:             }
 2159:          } else {
 2160:             my @curritems = split(/,/,$ids{$id});
 2161:             foreach my $uname (@curritems) {
 2162:                 my $uhom = $uhome;
 2163:                 if ($uhom eq '') {
 2164:                     $uhom=&homeserver($uname,$udom);
 2165:                 }
 2166:                 if ($uhom ne 'no_host') { 
 2167:                     $byid{$uhom}{$id} .= $uname.',';
 2168:                 }
 2169:             }
 2170:         }
 2171:     }
 2172:     if ($namespace eq 'clickers') {
 2173:         foreach my $server (keys(%byid)) {
 2174:             if (ref($byid{$server}) eq 'HASH') {
 2175:                 foreach my $id (keys(%{$byid{$server}})) {
 2176:                     $byid{$server}{$id} =~ s/,$//;
 2177:                     $servers{$server}.=&escape($id).'='.&escape($byid{$server}{$id}).'&';
 2178:                 }
 2179:             }
 2180:         }
 2181:     }
 2182:     foreach my $server (keys(%servers)) {
 2183:         $servers{$server} =~ s/\&$//;
 2184:         if ($namespace eq 'ids') {
 2185:             $result{$server} = &critical('iddel:'.$udom.':'.$servers{$server},$uhome);
 2186:         } elsif ($namespace eq 'clickers') {
 2187:             $result{$server} = &critical('updateclickers:'.$udom.':del:'.$servers{$server},$server);
 2188:         }
 2189:     }
 2190:     return %result;
 2191: }
 2192: 
 2193: # ----- Update clicker ID-to-username look-ups in clickers.db on library server 
 2194: 
 2195: sub updateclickers {
 2196:     my ($udom,$action,$idshashref,$uhome,$critical) = @_;
 2197:     my %clickers;
 2198:     if (ref($idshashref) eq 'HASH') {
 2199:         %clickers=%{$idshashref};
 2200:     } else {
 2201:         return;
 2202:     }
 2203:     my $items='';
 2204:     foreach my $item (keys(%clickers)) {
 2205:         $items.=&escape($item).'='.&escape($clickers{$item}).'&';
 2206:     }
 2207:     $items=~s/\&$//;
 2208:     my $request = "updateclickers:$udom:$action:$items";
 2209:     if ($critical) {
 2210:         return &critical($request,$uhome);
 2211:     } else {
 2212:         return &reply($request,$uhome);
 2213:     }
 2214: }
 2215: 
 2216: # ------------------------------dump from db file owned by domainconfig user
 2217: sub dump_dom {
 2218:     my ($namespace, $udom, $regexp) = @_;
 2219: 
 2220:     $udom ||= $env{'user.domain'};
 2221: 
 2222:     return () unless $udom;
 2223: 
 2224:     return &dump($namespace, $udom, &get_domainconfiguser($udom), $regexp);
 2225: }
 2226: 
 2227: # ------------------------------------------ get items from domain db files   
 2228: 
 2229: sub get_dom {
 2230:     my ($namespace,$storearr,$udom,$uhome,$encrypt)=@_;
 2231:     return if ($udom eq 'public');
 2232:     my $items='';
 2233:     foreach my $item (@$storearr) {
 2234:         $items.=&escape($item).'&';
 2235:     }
 2236:     $items=~s/\&$//;
 2237:     if (!$udom) {
 2238:         $udom=$env{'user.domain'};
 2239:         return if ($udom eq 'public');
 2240:         if (defined(&domain($udom,'primary'))) {
 2241:             $uhome=&domain($udom,'primary');
 2242:         } else {
 2243:             undef($uhome);
 2244:         }
 2245:     } else {
 2246:         if (!$uhome) {
 2247:             if (defined(&domain($udom,'primary'))) {
 2248:                 $uhome=&domain($udom,'primary');
 2249:             }
 2250:         }
 2251:     }
 2252:     if ($udom && $uhome && ($uhome ne 'no_host')) {
 2253:         my $rep;
 2254:         if (grep { $_ eq $uhome } &current_machine_ids()) {
 2255:             # domain information is hosted on this machine
 2256:             $rep = &LONCAPA::Lond::get_dom("getdom:$udom:$namespace:$items");
 2257:         } else {
 2258:             if ($encrypt) {
 2259:                 $rep=&reply("encrypt:egetdom:$udom:$namespace:$items",$uhome);
 2260:             } else {
 2261:                 $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
 2262:             }
 2263:         }
 2264:         my %returnhash;
 2265:         if ($rep eq '' || $rep =~ /^error: 2 /) {
 2266:             return %returnhash;
 2267:         }
 2268:         my @pairs=split(/\&/,$rep);
 2269:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
 2270:             return @pairs;
 2271:         }
 2272:         my $i=0;
 2273:         foreach my $item (@$storearr) {
 2274:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
 2275:             $i++;
 2276:         }
 2277:         return %returnhash;
 2278:     } else {
 2279:         &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
 2280:     }
 2281: }
 2282: 
 2283: # -------------------------------------------- put items in domain db files 
 2284: 
 2285: sub put_dom {
 2286:     my ($namespace,$storehash,$udom,$uhome,$encrypt)=@_;
 2287:     if (!$udom) {
 2288:         $udom=$env{'user.domain'};
 2289:         if (defined(&domain($udom,'primary'))) {
 2290:             $uhome=&domain($udom,'primary');
 2291:         } else {
 2292:             undef($uhome);
 2293:         }
 2294:     } else {
 2295:         if (!$uhome) {
 2296:             if (defined(&domain($udom,'primary'))) {
 2297:                 $uhome=&domain($udom,'primary');
 2298:             }
 2299:         }
 2300:     } 
 2301:     if ($udom && $uhome && ($uhome ne 'no_host')) {
 2302:         my $items='';
 2303:         foreach my $item (keys(%$storehash)) {
 2304:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 2305:         }
 2306:         $items=~s/\&$//;
 2307:         if ($encrypt) {
 2308:             return &reply("encrypt:putdom:$udom:$namespace:$items",$uhome);
 2309:         } else {
 2310:             return &reply("putdom:$udom:$namespace:$items",$uhome);
 2311:         }
 2312:     } else {
 2313:         &logthis("put_dom failed - no homeserver and/or domain");
 2314:     }
 2315: }
 2316: 
 2317: # --------------------- newput for items in db file owned by domainconfig user
 2318: sub newput_dom {
 2319:     my ($namespace,$storehash,$udom) = @_;
 2320:     my $result;
 2321:     if (!$udom) {
 2322:         $udom=$env{'user.domain'};
 2323:     }
 2324:     if ($udom) {
 2325:         my $uname = &get_domainconfiguser($udom);
 2326:         $result = &newput($namespace,$storehash,$udom,$uname);
 2327:     }
 2328:     return $result;
 2329: }
 2330: 
 2331: # --------------------- delete for items in db file owned by domainconfig user
 2332: sub del_dom {
 2333:     my ($namespace,$storearr,$udom)=@_;
 2334:     if (ref($storearr) eq 'ARRAY') {
 2335:         if (!$udom) {
 2336:             $udom=$env{'user.domain'};
 2337:         }
 2338:         if ($udom) {
 2339:             my $uname = &get_domainconfiguser($udom); 
 2340:             return &del($namespace,$storearr,$udom,$uname);
 2341:         }
 2342:     }
 2343: }
 2344: 
 2345: sub store_dom {
 2346:     my ($storehash,$id,$namespace,$dom,$home,$encrypt) = @_;
 2347:     $$storehash{'ip'}=&get_requestor_ip();
 2348:     $$storehash{'host'}=$perlvar{'lonHostID'};
 2349:     my $namevalue='';
 2350:     foreach my $key (keys(%{$storehash})) {
 2351:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 2352:     }
 2353:     $namevalue=~s/\&$//;
 2354:     if (grep { $_ eq $home } current_machine_ids()) {
 2355:         return LONCAPA::Lond::store_dom("storedom:$dom:$namespace:$id:$namevalue");
 2356:     } else {
 2357:         if ($namespace eq 'private') {
 2358:             return 'refused';
 2359:         } elsif ($encrypt) {
 2360:             return reply("encrypt:storedom:$dom:$namespace:$id:$namevalue",$home);
 2361:         } else {
 2362:             return reply("storedom:$dom:$namespace:$id:$namevalue",$home);
 2363:         }
 2364:     }
 2365: }
 2366: 
 2367: sub restore_dom {
 2368:     my ($id,$namespace,$dom,$home,$encrypt) = @_;
 2369:     my $answer;
 2370:     if (grep { $_ eq $home } current_machine_ids()) {
 2371:         $answer = LONCAPA::Lond::restore_dom("restoredom:$dom:$namespace:$id");
 2372:     } elsif ($namespace ne 'private') {
 2373:         if ($encrypt) {
 2374:             $answer=&reply("encrypt:restoredom:$dom:$namespace:$id",$home);
 2375:         } else {
 2376:             $answer=&reply("restoredom:$dom:$namespace:$id",$home);
 2377:         }
 2378:     }
 2379:     my %returnhash=();
 2380:     unless (($answer eq '') || ($answer eq 'con_lost') || ($answer eq 'refused') || 
 2381:             ($answer eq 'unknown_cmd') || ($answer eq 'rejected')) {
 2382:         foreach my $line (split(/\&/,$answer)) {
 2383:             my ($name,$value)=split(/\=/,$line);
 2384:             $returnhash{&unescape($name)}=&thaw_unescape($value);
 2385:         }
 2386:         my $version;
 2387:         for ($version=1;$version<=$returnhash{'version'};$version++) {
 2388:             foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
 2389:                 $returnhash{$item}=$returnhash{$version.':'.$item};
 2390:             }
 2391:         }
 2392:     }
 2393:     return %returnhash;
 2394: }
 2395: 
 2396: # ----------------------------------construct domainconfig user for a domain 
 2397: sub get_domainconfiguser {
 2398:     my ($udom) = @_;
 2399:     return $udom.'-domainconfig';
 2400: }
 2401: 
 2402: sub retrieve_inst_usertypes {
 2403:     my ($udom) = @_;
 2404:     my (%returnhash,@order);
 2405:     my %domdefs = &get_domain_defaults($udom);
 2406:     if ((ref($domdefs{'inststatustypes'}) eq 'HASH') && 
 2407:         (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
 2408:         return ($domdefs{'inststatustypes'},$domdefs{'inststatusorder'});
 2409:     } else {
 2410:         if (defined(&domain($udom,'primary'))) {
 2411:             my $uhome=&domain($udom,'primary');
 2412:             my $rep=&reply("inst_usertypes:$udom",$uhome);
 2413:             if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
 2414:                 &logthis("retrieve_inst_usertypes failed - $rep returned from $uhome in domain: $udom");
 2415:                 return (\%returnhash,\@order);
 2416:             }
 2417:             my ($hashitems,$orderitems) = split(/:/,$rep); 
 2418:             my @pairs=split(/\&/,$hashitems);
 2419:             foreach my $item (@pairs) {
 2420:                 my ($key,$value)=split(/=/,$item,2);
 2421:                 $key = &unescape($key);
 2422:                 next if ($key =~ /^error: 2 /);
 2423:                 $returnhash{$key}=&thaw_unescape($value);
 2424:             }
 2425:             my @esc_order = split(/\&/,$orderitems);
 2426:             foreach my $item (@esc_order) {
 2427:                 push(@order,&unescape($item));
 2428:             }
 2429:         } else {
 2430:             &logthis("retrieve_inst_usertypes failed - no primary domain server for $udom");
 2431:         }
 2432:         return (\%returnhash,\@order);
 2433:     }
 2434: }
 2435: 
 2436: sub is_domainimage {
 2437:     my ($url) = @_;
 2438:     if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo|login)/+[^/]-) {
 2439:         if (&domain($1) ne '') {
 2440:             return '1';
 2441:         }
 2442:     }
 2443:     return;
 2444: }
 2445: 
 2446: sub inst_directory_query {
 2447:     my ($srch) = @_;
 2448:     my $udom = $srch->{'srchdomain'};
 2449:     my %results;
 2450:     my $homeserver = &domain($udom,'primary');
 2451:     my $outcome;
 2452:     if ($homeserver ne '') {
 2453:         unless ($homeserver eq $perlvar{'lonHostID'}) {
 2454:             if ($srch->{'srchby'} eq 'email') {
 2455:                 my $lcrev = &get_server_loncaparev($udom,$homeserver);
 2456:                 my ($major,$minor) = ($lcrev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
 2457:                 if (($major eq '' && $minor eq '') || ($major < 2) ||
 2458:                     (($major == 2) && ($minor < 12))) {
 2459:                     return;
 2460:                 }
 2461:             }
 2462:         }
 2463: 	my $queryid=&reply("querysend:instdirsearch:".
 2464: 			   &escape($srch->{'srchby'}).':'.
 2465: 			   &escape($srch->{'srchterm'}).':'.
 2466: 			   &escape($srch->{'srchtype'}),$homeserver);
 2467: 	my $host=&hostname($homeserver);
 2468: 	if ($queryid !~/^\Q$host\E\_/) {
 2469: 	    &logthis('institutional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.' in domain '.$udom);
 2470: 	    return;
 2471: 	}
 2472: 	my $response = &get_query_reply($queryid);
 2473: 	my $maxtries = 5;
 2474: 	my $tries = 1;
 2475: 	while (($response=~/^timeout/) && ($tries < $maxtries)) {
 2476: 	    $response = &get_query_reply($queryid);
 2477: 	    $tries ++;
 2478: 	}
 2479: 
 2480:         if (!&error($response) && $response ne 'refused') {
 2481:             if ($response eq 'unavailable') {
 2482:                 $outcome = $response;
 2483:             } else {
 2484:                 $outcome = 'ok';
 2485:                 my @matches = split(/\n/,$response);
 2486:                 foreach my $match (@matches) {
 2487:                     my ($key,$value) = split(/=/,$match);
 2488:                     $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
 2489:                 }
 2490:             }
 2491:         }
 2492:     }
 2493:     return ($outcome,%results);
 2494: }
 2495: 
 2496: sub usersearch {
 2497:     my ($srch) = @_;
 2498:     my $dom = $srch->{'srchdomain'};
 2499:     my %results;
 2500:     my %libserv = &all_library();
 2501:     my $query = 'usersearch';
 2502:     foreach my $tryserver (keys(%libserv)) {
 2503:         if (&host_domain($tryserver) eq $dom) {
 2504:             unless ($tryserver eq $perlvar{'lonHostID'}) {
 2505:                 if ($srch->{'srchby'} eq 'email') {
 2506:                     my $lcrev = &get_server_loncaparev($dom,$tryserver);
 2507:                     my ($major,$minor) = ($lcrev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
 2508:                     next if (($major eq '' && $minor eq '') || ($major < 2) ||
 2509:                              (($major == 2) && ($minor < 12)));
 2510:                 }
 2511:             }
 2512:             my $host=&hostname($tryserver);
 2513:             my $queryid=
 2514:                 &reply("querysend:".&escape($query).':'.
 2515:                        &escape($srch->{'srchby'}).':'.
 2516:                        &escape($srch->{'srchtype'}).':'.
 2517:                        &escape($srch->{'srchterm'}),$tryserver);
 2518:             if ($queryid !~/^\Q$host\E\_/) {
 2519:                 &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
 2520:                 next;
 2521:             }
 2522:             my $reply = &get_query_reply($queryid);
 2523:             my $maxtries = 1;
 2524:             my $tries = 1;
 2525:             while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 2526:                 $reply = &get_query_reply($queryid);
 2527:                 $tries ++;
 2528:             }
 2529:             if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 2530:                 &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') -  maxtries: '.$maxtries.' tries: '.$tries);
 2531:             } else {
 2532:                 my @matches;
 2533:                 if ($reply =~ /\n/) {
 2534:                     @matches = split(/\n/,$reply);
 2535:                 } else {
 2536:                     @matches = split(/\&/,$reply);
 2537:                 }
 2538:                 foreach my $match (@matches) {
 2539:                     my ($uname,$udom,%userhash);
 2540:                     foreach my $entry (split(/:/,$match)) {
 2541:                         my ($key,$value) =
 2542:                             map {&unescape($_);} split(/=/,$entry);
 2543:                         $userhash{$key} = $value;
 2544:                         if ($key eq 'username') {
 2545:                             $uname = $value;
 2546:                         } elsif ($key eq 'domain') {
 2547:                             $udom = $value;
 2548:                         }
 2549:                     }
 2550:                     $results{$uname.':'.$udom} = \%userhash;
 2551:                 }
 2552:             }
 2553:         }
 2554:     }
 2555:     return %results;
 2556: }
 2557: 
 2558: sub get_instuser {
 2559:     my ($udom,$uname,$id) = @_;
 2560:     my $homeserver = &domain($udom,'primary');
 2561:     my ($outcome,%results);
 2562:     if ($homeserver ne '') {
 2563:         my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
 2564:                            &escape($id).':'.&escape($udom),$homeserver);
 2565:         my $host=&hostname($homeserver);
 2566:         if ($queryid !~/^\Q$host\E\_/) {
 2567:             &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
 2568:             return;
 2569:         }
 2570:         my $response = &get_query_reply($queryid);
 2571:         my $maxtries = 5;
 2572:         my $tries = 1;
 2573:         while (($response=~/^timeout/) && ($tries < $maxtries)) {
 2574:             $response = &get_query_reply($queryid);
 2575:             $tries ++;
 2576:         }
 2577:         if (!&error($response) && $response ne 'refused') {
 2578:             if ($response eq 'unavailable') {
 2579:                 $outcome = $response;
 2580:             } else {
 2581:                 $outcome = 'ok';
 2582:                 my @matches = split(/\n/,$response);
 2583:                 foreach my $match (@matches) {
 2584:                     my ($key,$value) = split(/=/,$match);
 2585:                     $results{&unescape($key)} = &thaw_unescape($value);
 2586:                 }
 2587:             }
 2588:         }
 2589:     }
 2590:     my %userinfo;
 2591:     if (ref($results{$uname}) eq 'HASH') {
 2592:         %userinfo = %{$results{$uname}};
 2593:     } 
 2594:     return ($outcome,%userinfo);
 2595: }
 2596: 
 2597: sub get_multiple_instusers {
 2598:     my ($udom,$users,$caller) = @_;
 2599:     my ($outcome,$results);
 2600:     if (ref($users) eq 'HASH') {
 2601:         my $count = keys(%{$users}); 
 2602:         my $requested = &freeze_escape($users);
 2603:         my $homeserver = &domain($udom,'primary');
 2604:         if ($homeserver ne '') {
 2605:             my $queryid=&reply('querysend:getmultinstusers:::'.$caller.'='.$requested,$homeserver);
 2606:             my $host=&hostname($homeserver);
 2607:             if ($queryid !~/^\Q$host\E\_/) {
 2608:                 &logthis('get_multiple_instusers invalid queryid: '.$queryid.
 2609:                          ' for host: '.$homeserver.'in domain '.$udom);
 2610:                 return ($outcome,$results);
 2611:             }
 2612:             my $response = &get_query_reply($queryid);
 2613:             my $maxtries = 5;
 2614:             if ($count > 100) {
 2615:                 $maxtries = 1+int($count/20);
 2616:             }
 2617:             my $tries = 1;
 2618:             while (($response=~/^timeout/) && ($tries <= $maxtries)) {
 2619:                 $response = &get_query_reply($queryid);
 2620:                 $tries ++;
 2621:             }
 2622:             if ($response eq '') {
 2623:                 $results = {};
 2624:                 foreach my $key (keys(%{$users})) {
 2625:                     my ($uname,$id);
 2626:                     if ($caller eq 'id') {
 2627:                         $id = $key;
 2628:                     } else {
 2629:                         $uname = $key;
 2630:                     }
 2631:                     my ($resp,%info) = &get_instuser($udom,$uname,$id);
 2632:                     $outcome = $resp;
 2633:                     if ($resp eq 'ok') {
 2634:                         %{$results} = (%{$results}, %info);
 2635:                     } else {
 2636:                         last;
 2637:                     }
 2638:                 }
 2639:             } elsif(!&error($response) && ($response ne 'refused')) {
 2640:                 if (($response eq 'unavailable') || ($response eq 'invalid') || ($response eq 'timeout')) {
 2641:                     $outcome = $response;
 2642:                 } else {
 2643:                     ($outcome,my $userdata) = split(/=/,$response,2);
 2644:                     if ($outcome eq 'ok') {
 2645:                         $results = &thaw_unescape($userdata); 
 2646:                     }
 2647:                 }
 2648:             }
 2649:         }
 2650:     }
 2651:     return ($outcome,$results);
 2652: }
 2653: 
 2654: sub inst_rulecheck {
 2655:     my ($udom,$uname,$id,$item,$rules) = @_;
 2656:     my %returnhash;
 2657:     if ($udom ne '') {
 2658:         if (ref($rules) eq 'ARRAY') {
 2659:             @{$rules} = map {&escape($_);} (@{$rules});
 2660:             my $rulestr = join(':',@{$rules});
 2661:             my $homeserver=&domain($udom,'primary');
 2662:             if (($homeserver ne '') && ($homeserver ne 'no_host')) {
 2663:                 my $response;
 2664:                 if ($item eq 'username') {                
 2665:                     $response=&unescape(&reply('instrulecheck:'.&escape($udom).
 2666:                                               ':'.&escape($uname).':'.$rulestr,
 2667:                                               $homeserver));
 2668:                 } elsif ($item eq 'id') {
 2669:                     $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
 2670:                                               ':'.&escape($id).':'.$rulestr,
 2671:                                               $homeserver));
 2672:                 } elsif ($item eq 'selfcreate') {
 2673:                     $response=&unescape(&reply('instselfcreatecheck:'.
 2674:                                                &escape($udom).':'.&escape($uname).
 2675:                                               ':'.$rulestr,$homeserver));
 2676:                 } elsif ($item eq 'unamemap') {
 2677:                     $response=&unescape(&reply('instunamemapcheck:'.
 2678:                                                &escape($udom).':'.&escape($uname).
 2679:                                               ':'.$rulestr,$homeserver));
 2680:                 }
 2681:                 if ($response ne 'refused') {
 2682:                     my @pairs=split(/\&/,$response);
 2683:                     foreach my $item (@pairs) {
 2684:                         my ($key,$value)=split(/=/,$item,2);
 2685:                         $key = &unescape($key);
 2686:                         next if ($key =~ /^error: 2 /);
 2687:                         $returnhash{$key}=&thaw_unescape($value);
 2688:                     }
 2689:                 }
 2690:             }
 2691:         }
 2692:     }
 2693:     return %returnhash;
 2694: }
 2695: 
 2696: sub inst_userrules {
 2697:     my ($udom,$check) = @_;
 2698:     my (%ruleshash,@ruleorder);
 2699:     if ($udom ne '') {
 2700:         my $homeserver=&domain($udom,'primary');
 2701:         if (($homeserver ne '') && ($homeserver ne 'no_host')) {
 2702:             my $response;
 2703:             if ($check eq 'id') {
 2704:                 $response=&reply('instidrules:'.&escape($udom),
 2705:                                  $homeserver);
 2706:             } elsif ($check eq 'email') {
 2707:                 $response=&reply('instemailrules:'.&escape($udom),
 2708:                                  $homeserver);
 2709:             } elsif ($check eq 'unamemap') {
 2710:                 $response=&reply('unamemaprules:'.&escape($udom),
 2711:                                  $homeserver); 
 2712:             } else {
 2713:                 $response=&reply('instuserrules:'.&escape($udom),
 2714:                                  $homeserver);
 2715:             }
 2716:             if (($response ne 'refused') && ($response ne 'error') && 
 2717:                 ($response ne 'unknown_cmd') && 
 2718:                 ($response ne 'no_such_host')) {
 2719:                 my ($hashitems,$orderitems) = split(/:/,$response);
 2720:                 my @pairs=split(/\&/,$hashitems);
 2721:                 foreach my $item (@pairs) {
 2722:                     my ($key,$value)=split(/=/,$item,2);
 2723:                     $key = &unescape($key);
 2724:                     next if ($key =~ /^error: 2 /);
 2725:                     $ruleshash{$key}=&thaw_unescape($value);
 2726:                 }
 2727:                 my @esc_order = split(/\&/,$orderitems);
 2728:                 foreach my $item (@esc_order) {
 2729:                     push(@ruleorder,&unescape($item));
 2730:                 }
 2731:             }
 2732:         }
 2733:     }
 2734:     return (\%ruleshash,\@ruleorder);
 2735: }
 2736: 
 2737: # ------------- Get Authentication, Language and User Tools Defaults for Domain
 2738: 
 2739: sub get_domain_defaults {
 2740:     my ($domain,$ignore_cache) = @_;
 2741:     return if (($domain eq '') || ($domain eq 'public'));
 2742:     my $cachetime = 60*60*24;
 2743:     unless ($ignore_cache) {
 2744:         my ($result,$cached)=&is_cached_new('domdefaults',$domain);
 2745:         if (defined($cached)) {
 2746:             if (ref($result) eq 'HASH') {
 2747:                 return %{$result};
 2748:             }
 2749:         }
 2750:     }
 2751:     my %domdefaults;
 2752:     my %domconfig =
 2753:          &get_dom('configuration',['defaults','quotas',
 2754:                                   'requestcourses','inststatus',
 2755:                                   'coursedefaults','usersessions',
 2756:                                   'requestauthor','authordefaults',
 2757:                                   'selfenrollment','coursecategories',
 2758:                                   'ssl','autoenroll','trust',
 2759:                                   'helpsettings','wafproxy',
 2760:                                   'ltisec','toolsec','privacy'],$domain);
 2761:     my @coursetypes = ('official','unofficial','community','textbook','placement');
 2762:     if (ref($domconfig{'defaults'}) eq 'HASH') {
 2763:         $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'}; 
 2764:         $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
 2765:         $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
 2766:         $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
 2767:         $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
 2768:         $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
 2769:         $domdefaults{'portal_def_email'} = $domconfig{'defaults'}{'portal_def_email'};
 2770:         $domdefaults{'portal_def_web'} = $domconfig{'defaults'}{'portal_def_web'};
 2771:         $domdefaults{'intauth_cost'} = $domconfig{'defaults'}{'intauth_cost'};
 2772:         $domdefaults{'intauth_switch'} = $domconfig{'defaults'}{'intauth_switch'};
 2773:         $domdefaults{'intauth_check'} = $domconfig{'defaults'}{'intauth_check'};
 2774:         $domdefaults{'unamemap_rule'} = $domconfig{'defaults'}{'unamemap_rule'};
 2775:     } else {
 2776:         $domdefaults{'lang_def'} = &domain($domain,'lang_def');
 2777:         $domdefaults{'auth_def'} = &domain($domain,'auth_def');
 2778:         $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
 2779:     }
 2780:     if (ref($domconfig{'quotas'}) eq 'HASH') {
 2781:         if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
 2782:             $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
 2783:         } else {
 2784:             $domdefaults{'defaultquota'} = $domconfig{'quotas'};
 2785:         }
 2786:         my @usertools = ('aboutme','blog','webdav','portfolio','portaccess');
 2787:         foreach my $item (@usertools) {
 2788:             if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
 2789:                 $domdefaults{$item} = $domconfig{'quotas'}{$item};
 2790:             }
 2791:         }
 2792:         if (ref($domconfig{'quotas'}{'authorquota'}) eq 'HASH') {
 2793:             $domdefaults{'authorquota'} = $domconfig{'quotas'}{'authorquota'};
 2794:         }
 2795:     }
 2796:     if (ref($domconfig{'requestcourses'}) eq 'HASH') {
 2797:         foreach my $item ('official','unofficial','community','textbook','placement') {
 2798:             $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
 2799:         }
 2800:     }
 2801:     if (ref($domconfig{'requestauthor'}) eq 'HASH') {
 2802:         $domdefaults{'requestauthor'} = $domconfig{'requestauthor'};
 2803:     }
 2804:     if (ref($domconfig{'authordefaults'}) eq 'HASH') {
 2805:         foreach my $item ('nocodemirror','copyright','sourceavail','domcoordacc','editors') {
 2806:             if ($item eq 'editors') {
 2807:                 if (ref($domconfig{'authordefaults'}{'editors'}) eq 'ARRAY') {
 2808:                     $domdefaults{$item} = join(',',@{$domconfig{'authordefaults'}{'editors'}});
 2809:                 }
 2810:             } else {
 2811:                 $domdefaults{$item} = $domconfig{'authordefaults'}{$item};
 2812:             }
 2813:         }
 2814:     }
 2815:     if (ref($domconfig{'inststatus'}) eq 'HASH') {
 2816:         foreach my $item ('inststatustypes','inststatusorder','inststatusguest') {
 2817:             $domdefaults{$item} = $domconfig{'inststatus'}{$item};
 2818:         }
 2819:     }
 2820:     if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
 2821:         $domdefaults{'canuse_pdfforms'} = $domconfig{'coursedefaults'}{'canuse_pdfforms'};
 2822:         $domdefaults{'usejsme'} = $domconfig{'coursedefaults'}{'usejsme'};
 2823:         $domdefaults{'inline_chem'} = $domconfig{'coursedefaults'}{'inline_chem'};
 2824:         $domdefaults{'uselcmath'} = $domconfig{'coursedefaults'}{'uselcmath'};
 2825:         if (ref($domconfig{'coursedefaults'}{'postsubmit'}) eq 'HASH') {
 2826:             $domdefaults{'postsubmit'} = $domconfig{'coursedefaults'}{'postsubmit'}{'client'};
 2827:         }
 2828:         foreach my $type (@coursetypes) {
 2829:             if (ref($domconfig{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
 2830:                 unless ($type eq 'community') {
 2831:                     $domdefaults{$type.'credits'} = $domconfig{'coursedefaults'}{'coursecredits'}{$type};
 2832:                 }
 2833:             }
 2834:             if (ref($domconfig{'coursedefaults'}{'uploadquota'}) eq 'HASH') {
 2835:                 $domdefaults{$type.'quota'} = $domconfig{'coursedefaults'}{'uploadquota'}{$type};
 2836:             }
 2837:             if (ref($domconfig{'coursedefaults'}{'coursequota'}) eq 'HASH') {
 2838:                 $domdefaults{$type.'coursequota'} = $domconfig{'coursedefaults'}{'coursequota'}{$type};
 2839:             }
 2840:             if ($domdefaults{'postsubmit'} eq 'on') {
 2841:                 if (ref($domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}) eq 'HASH') {
 2842:                     $domdefaults{$type.'postsubtimeout'} = 
 2843:                         $domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}{$type}; 
 2844:                 }
 2845:             }
 2846:             if (ref($domconfig{'coursedefaults'}{'domexttool'}) eq 'HASH') {
 2847:                 $domdefaults{$type.'domexttool'} = $domconfig{'coursedefaults'}{'domexttool'}{$type};
 2848:             } else {
 2849:                 $domdefaults{$type.'domexttool'} = 1;
 2850:             }
 2851:             if (ref($domconfig{'coursedefaults'}{'exttool'}) eq 'HASH') {
 2852:                 $domdefaults{$type.'exttool'} = $domconfig{'coursedefaults'}{'exttool'}{$type};
 2853:             } else {
 2854:                 $domdefaults{$type.'exttool'} = 0;
 2855:             }
 2856:             if (ref($domconfig{'coursedefaults'}{'crsauthor'}) eq 'HASH') {
 2857:                 $domdefaults{$type.'crsauthor'} = $domconfig{'coursedefaults'}{'crsauthor'}{$type};
 2858:             } else {
 2859:                 $domdefaults{$type.'crsauthor'} = 1;
 2860:             }
 2861:             if (ref($domconfig{'coursedefaults'}{'crseditors'}) eq 'ARRAY') {
 2862:                 $domdefaults{'crseditors'}=join(',',@{$domconfig{'coursedefaults'}{'crseditors'}});
 2863:             }
 2864:         }
 2865:         if (ref($domconfig{'coursedefaults'}{'canclone'}) eq 'HASH') {
 2866:             if (ref($domconfig{'coursedefaults'}{'canclone'}{'instcode'}) eq 'ARRAY') {
 2867:                 my @clonecodes = @{$domconfig{'coursedefaults'}{'canclone'}{'instcode'}};
 2868:                 if (@clonecodes) {
 2869:                     $domdefaults{'canclone'} = join('+',@clonecodes);
 2870:                 }
 2871:             }
 2872:         } elsif ($domconfig{'coursedefaults'}{'canclone'}) {
 2873:             $domdefaults{'canclone'}=$domconfig{'coursedefaults'}{'canclone'};
 2874:         }
 2875:         if ($domconfig{'coursedefaults'}{'texengine'}) {
 2876:             $domdefaults{'texengine'} = $domconfig{'coursedefaults'}{'texengine'};
 2877:         }
 2878:         if (exists($domconfig{'coursedefaults'}{'ltiauth'})) {
 2879:             $domdefaults{'crsltiauth'} = $domconfig{'coursedefaults'}{'ltiauth'};
 2880:         }
 2881:     }
 2882:     if (ref($domconfig{'usersessions'}) eq 'HASH') {
 2883:         if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
 2884:             $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
 2885:         }
 2886:         if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
 2887:             $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
 2888:         }
 2889:         if (ref($domconfig{'usersessions'}{'offloadnow'}) eq 'HASH') {
 2890:             $domdefaults{'offloadnow'} = $domconfig{'usersessions'}{'offloadnow'};
 2891:         }
 2892:         if (ref($domconfig{'usersessions'}{'offloadoth'}) eq 'HASH') {
 2893:             $domdefaults{'offloadoth'} = $domconfig{'usersessions'}{'offloadoth'};
 2894:         }
 2895:     }
 2896:     if (ref($domconfig{'selfenrollment'}) eq 'HASH') {
 2897:         if (ref($domconfig{'selfenrollment'}{'admin'}) eq 'HASH') {
 2898:             my @settings = ('types','registered','enroll_dates','access_dates','section',
 2899:                             'approval','limit');
 2900:             foreach my $type (@coursetypes) {
 2901:                 if (ref($domconfig{'selfenrollment'}{'admin'}{$type}) eq 'HASH') {
 2902:                     my @mgrdc = ();
 2903:                     foreach my $item (@settings) {
 2904:                         if ($domconfig{'selfenrollment'}{'admin'}{$type}{$item} eq '0') {
 2905:                             push(@mgrdc,$item);
 2906:                         }
 2907:                     }
 2908:                     if (@mgrdc) {
 2909:                         $domdefaults{$type.'selfenrolladmdc'} = join(',',@mgrdc);
 2910:                     }
 2911:                 }
 2912:             }
 2913:         }
 2914:         if (ref($domconfig{'selfenrollment'}{'default'}) eq 'HASH') {
 2915:             foreach my $type (@coursetypes) {
 2916:                 if (ref($domconfig{'selfenrollment'}{'default'}{$type}) eq 'HASH') {
 2917:                     foreach my $item (keys(%{$domconfig{'selfenrollment'}{'default'}{$type}})) {
 2918:                         $domdefaults{$type.'selfenroll'.$item} = $domconfig{'selfenrollment'}{'default'}{$type}{$item};
 2919:                     }
 2920:                 }
 2921:             }
 2922:         }
 2923:     }
 2924:     if (ref($domconfig{'coursecategories'}) eq 'HASH') {
 2925:         $domdefaults{'catauth'} = 'std';
 2926:         $domdefaults{'catunauth'} = 'std';
 2927:         if ($domconfig{'coursecategories'}{'auth'}) {
 2928:             $domdefaults{'catauth'} = $domconfig{'coursecategories'}{'auth'};
 2929:         }
 2930:         if ($domconfig{'coursecategories'}{'unauth'}) {
 2931:             $domdefaults{'catunauth'} = $domconfig{'coursecategories'}{'unauth'};
 2932:         }
 2933:     }
 2934:     if (ref($domconfig{'ssl'}) eq 'HASH') {
 2935:         if (ref($domconfig{'ssl'}{'replication'}) eq 'HASH') {
 2936:             $domdefaults{'replication'} = $domconfig{'ssl'}{'replication'};
 2937:         }
 2938:         if (ref($domconfig{'ssl'}{'connto'}) eq 'HASH') {
 2939:             $domdefaults{'connect'} = $domconfig{'ssl'}{'connto'};
 2940:         }
 2941:         if (ref($domconfig{'ssl'}{'connfrom'}) eq 'HASH') {
 2942:             $domdefaults{'connect'} = $domconfig{'ssl'}{'connfrom'};
 2943:         }
 2944:     }
 2945:     if (ref($domconfig{'trust'}) eq 'HASH') {
 2946:         my @prefixes = qw(content shared enroll othcoau coaurem domroles catalog reqcrs msg);
 2947:         foreach my $prefix (@prefixes) {
 2948:             if (ref($domconfig{'trust'}{$prefix}) eq 'HASH') {
 2949:                 $domdefaults{'trust'.$prefix} = $domconfig{'trust'}{$prefix};
 2950:             }
 2951:         }
 2952:     }
 2953:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
 2954:         $domdefaults{'autofailsafe'} = $domconfig{'autoenroll'}{'autofailsafe'};
 2955:         $domdefaults{'failsafe'} = $domconfig{'autoenroll'}{'failsafe'};
 2956:     }
 2957:     if (ref($domconfig{'helpsettings'}) eq 'HASH') {
 2958:         $domdefaults{'submitbugs'} = $domconfig{'helpsettings'}{'submitbugs'};
 2959:         if (ref($domconfig{'helpsettings'}{'adhoc'}) eq 'HASH') {
 2960:             $domdefaults{'adhocroles'} = $domconfig{'helpsettings'}{'adhoc'};
 2961:         }
 2962:     }
 2963:     if (ref($domconfig{'wafproxy'}) eq 'HASH') {
 2964:         foreach my $item ('ipheader','trusted','vpnint','vpnext','sslopt') {
 2965:             if ($domconfig{'wafproxy'}{$item}) {
 2966:                 $domdefaults{'waf_'.$item} = $domconfig{'wafproxy'}{$item};
 2967:             }
 2968:         }
 2969:     }
 2970:     if (ref($domconfig{'ltisec'}) eq 'HASH') {
 2971:         if (ref($domconfig{'ltisec'}{'encrypt'}) eq 'HASH') {
 2972:             $domdefaults{'linkprotenc_crs'} = $domconfig{'ltisec'}{'encrypt'}{'crs'};
 2973:             $domdefaults{'linkprotenc_dom'} = $domconfig{'ltisec'}{'encrypt'}{'dom'};
 2974:             $domdefaults{'ltienc_consumers'} = $domconfig{'ltisec'}{'encrypt'}{'consumers'};
 2975:         }
 2976:         if (ref($domconfig{'ltisec'}{'private'}) eq 'HASH') {
 2977:             if (ref($domconfig{'ltisec'}{'private'}{'keys'}) eq 'ARRAY') {
 2978:                 $domdefaults{'ltiprivhosts'} = $domconfig{'ltisec'}{'private'}{'keys'};
 2979:             }
 2980:         }
 2981:         if (ref($domconfig{'ltisec'}{'suggested'}) eq 'HASH') {
 2982:             my %suggestions = %{$domconfig{'ltisec'}{'suggested'}};
 2983:             foreach my $item (keys(%{$domconfig{'ltisec'}{'suggested'}})) {
 2984:                 unless (ref($domconfig{'ltisec'}{'suggested'}{$item}) eq 'HASH') {
 2985:                     delete($suggestions{$item});
 2986:                 }
 2987:             }
 2988:             if (keys(%suggestions)) {
 2989:                 $domdefaults{'linkprotsuggested'} = \%suggestions;
 2990:             }
 2991:         }
 2992:     }
 2993:     if (ref($domconfig{'toolsec'}) eq 'HASH') {
 2994:         if (ref($domconfig{'toolsec'}{'encrypt'}) eq 'HASH') {
 2995:             $domdefaults{'toolenc_crs'} = $domconfig{'toolsec'}{'encrypt'}{'crs'};
 2996:             $domdefaults{'toolenc_dom'} = $domconfig{'toolsec'}{'encrypt'}{'dom'};
 2997:         }
 2998:         if (ref($domconfig{'toolsec'}{'private'}) eq 'HASH') {
 2999:             if (ref($domconfig{'toolsec'}{'private'}{'keys'}) eq 'ARRAY') {
 3000:                 $domdefaults{'toolprivhosts'} = $domconfig{'toolsec'}{'private'}{'keys'};
 3001:             }
 3002:         }
 3003:     }
 3004:     if (ref($domconfig{'privacy'}) eq 'HASH') {
 3005:         if (ref($domconfig{'privacy'}{'approval'}) eq 'HASH') {
 3006:             foreach my $domtype ('instdom','extdom') {
 3007:                 if (ref($domconfig{'privacy'}{'approval'}{$domtype}) eq 'HASH') {
 3008:                     foreach my $roletype ('domain','author','course','community') {
 3009:                         if ($domconfig{'privacy'}{'approval'}{$domtype}{$roletype} eq 'user') {
 3010:                             $domdefaults{'userapprovals'} = 1;
 3011:                             last;
 3012:                         }
 3013:                     }
 3014:                 }
 3015:                 last if ($domdefaults{'userapprovals'});
 3016:             }
 3017:         }
 3018:     }
 3019:     &do_cache_new('domdefaults',$domain,\%domdefaults,$cachetime);
 3020:     return %domdefaults;
 3021: }
 3022: 
 3023: sub get_dom_cats {
 3024:     my ($dom) = @_;
 3025:     return unless (&domain($dom));
 3026:     my ($cats,$cached)=&is_cached_new('cats',$dom);
 3027:     unless (defined($cached)) {
 3028:         my %domconfig = &get_dom('configuration',['coursecategories'],$dom);
 3029:         if (ref($domconfig{'coursecategories'}) eq 'HASH') {
 3030:             if (ref($domconfig{'coursecategories'}{'cats'}) eq 'HASH') {
 3031:                 %{$cats} = %{$domconfig{'coursecategories'}{'cats'}};
 3032:             } else {
 3033:                 $cats = {};
 3034:             }
 3035:         } else {
 3036:             $cats = {};
 3037:         }
 3038:         &do_cache_new('cats',$dom,$cats,3600);
 3039:     }
 3040:     return $cats;
 3041: }
 3042: 
 3043: sub get_dom_instcats {
 3044:     my ($dom) = @_;
 3045:     return unless (&domain($dom));
 3046:     my ($instcats,$cached)=&is_cached_new('instcats',$dom);
 3047:     unless (defined($cached)) {
 3048:         my (%coursecodes,%codes,@codetitles,%cat_titles,%cat_order);
 3049:         my $totcodes = &retrieve_instcodes(\%coursecodes,$dom);
 3050:         if ($totcodes > 0) {
 3051:             my $caller = 'global';
 3052:             if (&auto_instcode_format($caller,$dom,\%coursecodes,\%codes,
 3053:                                       \@codetitles,\%cat_titles,\%cat_order) eq 'ok') {
 3054:                 $instcats = {
 3055:                                 totcodes => $totcodes,
 3056:                                 codes => \%codes,
 3057:                                 codetitles => \@codetitles,
 3058:                                 cat_titles => \%cat_titles,
 3059:                                 cat_order => \%cat_order,
 3060:                             };
 3061:                 &do_cache_new('instcats',$dom,$instcats,3600);
 3062:             }
 3063:         }
 3064:     }
 3065:     return $instcats;
 3066: }
 3067: 
 3068: sub retrieve_instcodes {
 3069:     my ($coursecodes,$dom) = @_;
 3070:     my $totcodes;
 3071:     my %courses = &courseiddump($dom,'.',1,'.','.','.',undef,undef,'Course');
 3072:     foreach my $course (keys(%courses)) {
 3073:         if (ref($courses{$course}) eq 'HASH') {
 3074:             if ($courses{$course}{'inst_code'} ne '') {
 3075:                 $$coursecodes{$course} = $courses{$course}{'inst_code'};
 3076:                 $totcodes ++;
 3077:             }
 3078:         }
 3079:     }
 3080:     return $totcodes;
 3081: }
 3082: 
 3083: sub course_portal_url {
 3084:     my ($cnum,$cdom,$r) = @_;
 3085:     my $chome = &homeserver($cnum,$cdom);
 3086:     my $hostname = &hostname($chome);
 3087:     my $protocol = $protocol{$chome};
 3088:     $protocol = 'http' if ($protocol ne 'https');
 3089:     my %domdefaults = &get_domain_defaults($cdom);
 3090:     my $firsturl;
 3091:     if ($domdefaults{'portal_def'}) {
 3092:         $firsturl = $domdefaults{'portal_def'};
 3093:     } else {
 3094:         my $alias = &use_proxy_alias($r,$chome);
 3095:         $hostname = $alias if ($alias ne '');
 3096:         $firsturl = $protocol.'://'.$hostname;
 3097:     }
 3098:     return $firsturl;
 3099: }
 3100: 
 3101: sub url_prefix {
 3102:     my ($r,$dom,$home,$context) = @_;
 3103:     my $prefix;
 3104:     my %domdefs = &get_domain_defaults($dom);
 3105:     if ($domdefs{'portal_def'} && $domdefs{'portal_def_'.$context}) {
 3106:         if ($domdefs{'portal_def'} =~ m{^(https?://[^/]+)}) {
 3107:             $prefix = $1;
 3108:         }
 3109:     }
 3110:     if ($prefix eq '') {
 3111:         my $hostname = &hostname($home);
 3112:         my $protocol = $protocol{$home};
 3113:         $protocol = 'http' if ($protocol{$home} ne 'https');
 3114:         my $alias = &use_proxy_alias($r,$home);
 3115:         $hostname = $alias if ($alias ne '');
 3116:         $prefix = $protocol.'://'.$hostname;
 3117:     }
 3118:     return $prefix;
 3119: }
 3120: 
 3121: # --------------------------------------------- Get domain config for passwords
 3122: 
 3123: sub get_passwdconf {
 3124:     my ($dom) = @_;
 3125:     my (%passwdconf,$gotconf,$lookup);
 3126:     my ($result,$cached)=&is_cached_new('passwdconf',$dom);
 3127:     if (defined($cached)) {
 3128:         if (ref($result) eq 'HASH') {
 3129:             %passwdconf = %{$result};
 3130:             $gotconf = 1;
 3131:         }
 3132:     }
 3133:     unless ($gotconf) {
 3134:         my %domconfig = &get_dom('configuration',['passwords'],$dom);
 3135:         if (ref($domconfig{'passwords'}) eq 'HASH') {
 3136:             %passwdconf = %{$domconfig{'passwords'}};
 3137:         }
 3138:         my $cachetime = 24*60*60;
 3139:         &do_cache_new('passwdconf',$dom,\%passwdconf,$cachetime);
 3140:     }
 3141:     return %passwdconf;
 3142: }
 3143: 
 3144: # --------------------------------------------------- Assign a key to a student
 3145: 
 3146: sub assign_access_key {
 3147: #
 3148: # a valid key looks like uname:udom#comments
 3149: # comments are being appended
 3150: #
 3151:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
 3152:     $kdom=
 3153:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
 3154:     $knum=
 3155:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
 3156:     $cdom=
 3157:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 3158:     $cnum=
 3159:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 3160:     $udom=$env{'user.name'} unless (defined($udom));
 3161:     $uname=$env{'user.domain'} unless (defined($uname));
 3162:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
 3163:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
 3164:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
 3165:                                                   # assigned to this person
 3166:                                                   # - this should not happen,
 3167:                                                   # unless something went wrong
 3168:                                                   # the first time around
 3169: # ready to assign
 3170:         $logentry=$1.'; '.$logentry;
 3171:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
 3172:                                                  $kdom,$knum) eq 'ok') {
 3173: # key now belongs to user
 3174: 	    my $envkey='key.'.$cdom.'_'.$cnum;
 3175:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
 3176:                 &appenv({'environment.'.$envkey => $ckey});
 3177:                 return 'ok';
 3178:             } else {
 3179:                 return 
 3180:   'error: Count not permanently assign key, will need to be re-entered later.';
 3181: 	    }
 3182:         } else {
 3183:             return 'error: Could not assign key, try again later.';
 3184:         }
 3185:     } elsif (!$existing{$ckey}) {
 3186: # the key does not exist
 3187: 	return 'error: The key does not exist';
 3188:     } else {
 3189: # the key is somebody else's
 3190: 	return 'error: The key is already in use';
 3191:     }
 3192: }
 3193: 
 3194: # ------------------------------------------ put an additional comment on a key
 3195: 
 3196: sub comment_access_key {
 3197: #
 3198: # a valid key looks like uname:udom#comments
 3199: # comments are being appended
 3200: #
 3201:     my ($ckey,$cdom,$cnum,$logentry)=@_;
 3202:     $cdom=
 3203:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 3204:     $cnum=
 3205:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 3206:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
 3207:     if ($existing{$ckey}) {
 3208:         $existing{$ckey}.='; '.$logentry;
 3209: # ready to assign
 3210:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
 3211:                                                  $cdom,$cnum) eq 'ok') {
 3212: 	    return 'ok';
 3213:         } else {
 3214: 	    return 'error: Count not store comment.';
 3215:         }
 3216:     } else {
 3217: # the key does not exist
 3218: 	return 'error: The key does not exist';
 3219:     }
 3220: }
 3221: 
 3222: # ------------------------------------------------------ Generate a set of keys
 3223: 
 3224: sub generate_access_keys {
 3225:     my ($number,$cdom,$cnum,$logentry)=@_;
 3226:     $cdom=
 3227:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 3228:     $cnum=
 3229:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 3230:     unless (&allowed('mky',$cdom)) { return 0; }
 3231:     unless (($cdom) && ($cnum)) { return 0; }
 3232:     if ($number>10000) { return 0; }
 3233:     sleep(2); # make sure don't get same seed twice
 3234:     srand(time()^($$+($$<<15))); # from "Programming Perl"
 3235:     my $total=0;
 3236:     for (my $i=1;$i<=$number;$i++) {
 3237:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
 3238:                   sprintf("%lx",int(100000*rand)).'-'.
 3239:                   sprintf("%lx",int(100000*rand));
 3240:        $newkey=~s/1/g/g; # folks mix up 1 and l
 3241:        $newkey=~s/0/h/g; # and also 0 and O
 3242:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
 3243:        if ($existing{$newkey}) {
 3244:            $i--;
 3245:        } else {
 3246: 	  if (&put('accesskeys',
 3247:               { $newkey => '# generated '.localtime().
 3248:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
 3249:                            '; '.$logentry },
 3250: 		   $cdom,$cnum) eq 'ok') {
 3251:               $total++;
 3252: 	  }
 3253:        }
 3254:     }
 3255:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
 3256:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
 3257:     return $total;
 3258: }
 3259: 
 3260: # ------------------------------------------------------- Validate an accesskey
 3261: 
 3262: sub validate_access_key {
 3263:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
 3264:     $cdom=
 3265:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 3266:     $cnum=
 3267:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 3268:     $udom=$env{'user.domain'} unless (defined($udom));
 3269:     $uname=$env{'user.name'} unless (defined($uname));
 3270:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
 3271:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
 3272: }
 3273: 
 3274: # ------------------------------------- Find the section of student in a course
 3275: sub devalidate_getsection_cache {
 3276:     my ($udom,$unam,$courseid)=@_;
 3277:     my $hashid="$udom:$unam:$courseid";
 3278:     &devalidate_cache_new('getsection',$hashid);
 3279: }
 3280: 
 3281: sub courseid_to_courseurl {
 3282:     my ($courseid) = @_;
 3283:     #already url style courseid
 3284:     return $courseid if ($courseid =~ m{^/});
 3285: 
 3286:     if (exists($env{'course.'.$courseid.'.num'})) {
 3287: 	my $cnum = $env{'course.'.$courseid.'.num'};
 3288: 	my $cdom = $env{'course.'.$courseid.'.domain'};
 3289: 	return "/$cdom/$cnum";
 3290:     }
 3291: 
 3292:     my %courseinfo=&coursedescription($courseid);
 3293:     if (exists($courseinfo{'num'})) {
 3294: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
 3295:     }
 3296: 
 3297:     return undef;
 3298: }
 3299: 
 3300: sub getsection {
 3301:     my ($udom,$unam,$courseid)=@_;
 3302:     my $cachetime=1800;
 3303: 
 3304:     my $hashid="$udom:$unam:$courseid";
 3305:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
 3306:     if (defined($cached)) { return $result; }
 3307: 
 3308:     my %Pending; 
 3309:     my %Expired;
 3310:     #
 3311:     # Each role can either have not started yet (pending), be active, 
 3312:     #    or have expired.
 3313:     #
 3314:     # If there is an active role, we are done.
 3315:     #
 3316:     # If there is more than one role which has not started yet, 
 3317:     #     choose the one which will start sooner
 3318:     # If there is one role which has not started yet, return it.
 3319:     #
 3320:     # If there is more than one expired role, choose the one which ended last.
 3321:     # If there is a role which has expired, return it.
 3322:     #
 3323:     $courseid = &courseid_to_courseurl($courseid);
 3324:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
 3325:     foreach my $key (keys(%roleshash)) {
 3326:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
 3327:         my $section=$1;
 3328:         if ($key eq $courseid.'_st') { $section=''; }
 3329:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
 3330:         my $now=time;
 3331:         if (defined($end) && $end && ($now > $end)) {
 3332:             $Expired{$end}=$section;
 3333:             next;
 3334:         }
 3335:         if (defined($start) && $start && ($now < $start)) {
 3336:             $Pending{$start}=$section;
 3337:             next;
 3338:         }
 3339:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
 3340:     }
 3341:     #
 3342:     # Presumedly there will be few matching roles from the above
 3343:     # loop and the sorting time will be negligible.
 3344:     if (scalar(keys(%Pending))) {
 3345:         my ($time) = sort {$a <=> $b} keys(%Pending);
 3346:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
 3347:     } 
 3348:     if (scalar(keys(%Expired))) {
 3349:         my @sorted = sort {$a <=> $b} keys(%Expired);
 3350:         my $time = pop(@sorted);
 3351:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
 3352:     }
 3353:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
 3354: }
 3355: 
 3356: sub save_cache {
 3357:     &purge_remembered();
 3358:     #&Apache::loncommon::validate_page();
 3359:     undef(%env);
 3360:     undef($env_loaded);
 3361: }
 3362: 
 3363: my $to_remember=-1;
 3364: my %remembered;
 3365: my %accessed;
 3366: my $kicks=0;
 3367: my $hits=0;
 3368: sub make_key {
 3369:     my ($name,$id) = @_;
 3370:     if (length($id) > 65 
 3371: 	&& length(&escape($id)) > 200) {
 3372: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
 3373:     }
 3374:     return &escape($name.':'.$id);
 3375: }
 3376: 
 3377: sub devalidate_cache_new {
 3378:     my ($name,$id,$debug) = @_;
 3379:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
 3380:     my $remembered_id=$name.':'.$id;
 3381:     $id=&make_key($name,$id);
 3382:     $memcache->delete($id);
 3383:     delete($remembered{$remembered_id});
 3384:     delete($accessed{$remembered_id});
 3385: }
 3386: 
 3387: sub is_cached_new {
 3388:     my ($name,$id,$debug) = @_;
 3389:     my $remembered_id=$name.':'.$id; # this is to avoid make_key (which is slow) whenever possible
 3390:     if (exists($remembered{$remembered_id})) {
 3391: 	if ($debug) { &Apache::lonnet::logthis("Early return $remembered_id of $remembered{$remembered_id} "); }
 3392: 	$accessed{$remembered_id}=[&gettimeofday()];
 3393: 	$hits++;
 3394: 	return ($remembered{$remembered_id},1);
 3395:     }
 3396:     $id=&make_key($name,$id);
 3397:     my $value = $memcache->get($id);
 3398:     if (!(defined($value))) {
 3399: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
 3400: 	return (undef,undef);
 3401:     }
 3402:     if ($value eq '__undef__') {
 3403: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
 3404: 	$value=undef;
 3405:     }
 3406:     &make_room($remembered_id,$value,$debug);
 3407:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
 3408:     return ($value,1);
 3409: }
 3410: 
 3411: sub do_cache_new {
 3412:     my ($name,$id,$value,$time,$debug) = @_;
 3413:     my $remembered_id=$name.':'.$id;
 3414:     $id=&make_key($name,$id);
 3415:     my $setvalue=$value;
 3416:     if (!defined($setvalue)) {
 3417: 	$setvalue='__undef__';
 3418:     }
 3419:     if (!defined($time) ) {
 3420: 	$time=600;
 3421:     }
 3422:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
 3423:     my $result = $memcache->set($id,$setvalue,$time);
 3424:     if (! $result) {
 3425: 	&logthis("caching of id -> $id  failed");
 3426: 	$memcache->disconnect_all();
 3427:     }
 3428:     # need to make a copy of $value
 3429:     &make_room($remembered_id,$value,$debug);
 3430:     return $value;
 3431: }
 3432: 
 3433: sub make_room {
 3434:     my ($remembered_id,$value,$debug)=@_;
 3435: 
 3436:     $remembered{$remembered_id}= (ref($value)) ? &Storable::dclone($value)
 3437:                                     : $value;
 3438:     if ($to_remember<0) { return; }
 3439:     $accessed{$remembered_id}=[&gettimeofday()];
 3440:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
 3441:     my $to_kick;
 3442:     my $max_time=0;
 3443:     foreach my $other (keys(%accessed)) {
 3444: 	if (&tv_interval($accessed{$other}) > $max_time) {
 3445: 	    $to_kick=$other;
 3446: 	    $max_time=&tv_interval($accessed{$other});
 3447: 	}
 3448:     }
 3449:     delete($remembered{$to_kick});
 3450:     delete($accessed{$to_kick});
 3451:     $kicks++;
 3452:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
 3453:     return;
 3454: }
 3455: 
 3456: sub purge_remembered {
 3457:     #&logthis("Tossing ".scalar(keys(%remembered)));
 3458:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
 3459:     undef(%remembered);
 3460:     undef(%accessed);
 3461: }
 3462: # ------------------------------------- Read an entry from a user's environment
 3463: 
 3464: sub userenvironment {
 3465:     my ($udom,$unam,@what)=@_;
 3466:     my $items;
 3467:     foreach my $item (@what) {
 3468:         $items.=&escape($item).'&';
 3469:     }
 3470:     $items=~s/\&$//;
 3471:     my %returnhash=();
 3472:     my $uhome = &homeserver($unam,$udom);
 3473:     unless ($uhome eq 'no_host') {
 3474:         my @answer=split(/\&/, 
 3475:             &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
 3476:         if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
 3477:             return %returnhash;
 3478:         }
 3479:         my $i;
 3480:         for ($i=0;$i<=$#what;$i++) {
 3481: 	    $returnhash{$what[$i]}=&unescape($answer[$i]);
 3482:         }
 3483:     }
 3484:     return %returnhash;
 3485: }
 3486: 
 3487: # ---------------------------------------------------------- Get a studentphoto
 3488: sub studentphoto {
 3489:     my ($udom,$unam,$ext) = @_;
 3490:     my $home=&homeserver($unam,$udom);
 3491:     if (defined($env{'request.course.id'})) {
 3492:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
 3493:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
 3494:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
 3495:             } else {
 3496:                 my ($result,$perm_reqd)=
 3497: 		    &auto_photo_permission($unam,$udom);
 3498:                 if ($result eq 'ok') {
 3499:                     if (!($perm_reqd eq 'yes')) {
 3500:                         return(&retrievestudentphoto($udom,$unam,$ext));
 3501:                     }
 3502:                 }
 3503:             }
 3504:         }
 3505:     } else {
 3506:         my ($result,$perm_reqd) = 
 3507: 	    &auto_photo_permission($unam,$udom);
 3508:         if ($result eq 'ok') {
 3509:             if (!($perm_reqd eq 'yes')) {
 3510:                 return(&retrievestudentphoto($udom,$unam,$ext));
 3511:             }
 3512:         }
 3513:     }
 3514:     return '/adm/lonKaputt/lonlogo_broken.gif';
 3515: }
 3516: 
 3517: sub retrievestudentphoto {
 3518:     my ($udom,$unam,$ext,$type) = @_;
 3519:     my $home=&homeserver($unam,$udom);
 3520:     my $ret=&reply("studentphoto:$udom:$unam:$ext:$type",$home);
 3521:     if ($ret eq 'ok') {
 3522:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
 3523:         if ($type eq 'thumbnail') {
 3524:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
 3525:         }
 3526:         my $tokenurl=&tokenwrapper($url);
 3527:         return $tokenurl;
 3528:     } else {
 3529:         if ($type eq 'thumbnail') {
 3530:             return '/adm/lonKaputt/genericstudent_tn.gif';
 3531:         } else { 
 3532:             return '/adm/lonKaputt/lonlogo_broken.gif';
 3533:         }
 3534:     }
 3535: }
 3536: 
 3537: # -------------------------------------------------------------------- New chat
 3538: 
 3539: sub chatsend {
 3540:     my ($newentry,$anon,$group)=@_;
 3541:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
 3542:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 3543:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
 3544:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
 3545: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
 3546: 		   &escape($newentry)).':'.$group,$chome);
 3547: }
 3548: 
 3549: # ------------------------------------------ Find current version of a resource
 3550: 
 3551: sub getversion {
 3552:     my $fname=&clutter(shift);
 3553:     unless ($fname=~m{^(/adm/wrapper|)/res/}) { return -1; }
 3554:     return &currentversion(&filelocation('',$fname));
 3555: }
 3556: 
 3557: sub currentversion {
 3558:     my $fname=shift;
 3559:     my $author=$fname;
 3560:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 3561:     my ($udom,$uname)=split(/\//,$author);
 3562:     my $home=&homeserver($uname,$udom);
 3563:     if ($home eq 'no_host') { 
 3564:         return -1; 
 3565:     }
 3566:     my $answer=&reply("currentversion:$fname",$home);
 3567:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
 3568: 	return -1;
 3569:     }
 3570:     return $answer;
 3571: }
 3572: 
 3573: #
 3574: # Return special version number of resource if set by override, empty otherwise
 3575: #
 3576: sub usedversion {
 3577:     my $fname=shift;
 3578:     unless ($fname) { $fname=$env{'request.uri'}; }
 3579:     my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
 3580:     if ($urlversion) { return $urlversion; }
 3581:     return '';
 3582: }
 3583: 
 3584: # ----------------------------- Subscribe to a resource, return URL if possible
 3585: 
 3586: sub subscribe {
 3587:     my $fname=shift;
 3588:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
 3589:     $fname=~s/[\n\r]//g;
 3590:     my $author=$fname;
 3591:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 3592:     my ($udom,$uname)=split(/\//,$author);
 3593:     my $home=homeserver($uname,$udom);
 3594:     if ($home eq 'no_host') {
 3595:         return 'not_found';
 3596:     }
 3597:     my $answer=reply("sub:$fname",$home);
 3598:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
 3599: 	$answer.=' by '.$home;
 3600:     }
 3601:     return $answer;
 3602: }
 3603:     
 3604: # -------------------------------------------------------------- Replicate file
 3605: 
 3606: sub repcopy {
 3607:     my $filename=shift;
 3608:     $filename=~s/\/+/\//g;
 3609:     my $londocroot = $perlvar{'lonDocRoot'};
 3610:     if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
 3611:     if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
 3612:     if ($filename=~m{^\Q$londocroot/userfiles/\E} or
 3613: 	$filename=~m{^/*(uploaded|editupload)/}) {
 3614: 	return &repcopy_userfile($filename);
 3615:     }
 3616:     $filename=~s/[\n\r]//g;
 3617:     my $transname="$filename.in.transfer";
 3618: # FIXME: this should flock
 3619:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
 3620:     my $remoteurl=subscribe($filename);
 3621:     if ($remoteurl =~ /^con_lost by/) {
 3622: 	   &logthis("Subscribe returned $remoteurl: $filename");
 3623:            return 'unavailable';
 3624:     } elsif ($remoteurl eq 'not_found') {
 3625: 	   #&logthis("Subscribe returned not_found: $filename");
 3626: 	   return 'not_found';
 3627:     } elsif ($remoteurl =~ /^rejected by/) {
 3628: 	   &logthis("Subscribe returned $remoteurl: $filename");
 3629:            return 'forbidden';
 3630:     } elsif ($remoteurl eq 'directory') {
 3631:            return 'ok';
 3632:     } else {
 3633:         my $author=$filename;
 3634:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 3635:         my ($udom,$uname)=split(/\//,$author);
 3636:         my $home=homeserver($uname,$udom);
 3637:         unless ($home eq $perlvar{'lonHostID'}) {
 3638:            my @parts=split(/\//,$filename);
 3639:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
 3640:            if ($path ne "$londocroot/res") {
 3641:                &logthis("Malconfiguration for replication: $filename");
 3642: 	       return 'bad_request';
 3643:            }
 3644:            my $count;
 3645:            for ($count=5;$count<$#parts;$count++) {
 3646:                $path.="/$parts[$count]";
 3647:                if ((-e $path)!=1) {
 3648: 		   mkdir($path,0777);
 3649:                }
 3650:            }
 3651:            my $request=new HTTP::Request('GET',"$remoteurl");
 3652:            my $response;
 3653:            if ($remoteurl =~ m{/raw/}) {
 3654:                $response=&LONCAPA::LWPReq::makerequest($home,$request,$transname,\%perlvar,'',0,1);
 3655:            } else {
 3656:                $response=&LONCAPA::LWPReq::makerequest($home,$request,$transname,\%perlvar,'',1);
 3657:            }
 3658:            if ($response->is_error()) {
 3659: 	       unlink($transname);
 3660:                my $message=$response->status_line;
 3661:                &logthis("<font color=\"blue\">WARNING:"
 3662:                        ." LWP get: $message: $filename</font>");
 3663:                return 'unavailable';
 3664:            } else {
 3665: 	       if ($remoteurl!~/\.meta$/) {
 3666:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
 3667:                   my $mresponse;
 3668:                   if ($remoteurl =~ m{/raw/}) {
 3669:                       $mresponse = &LONCAPA::LWPReq::makerequest($home,$mrequest,$filename.'.meta',\%perlvar,'',0,1);
 3670:                   } else {
 3671:                       $mresponse = &LONCAPA::LWPReq::makerequest($home,$mrequest,$filename.'.meta',\%perlvar,'',1);
 3672:                   }
 3673:                   if ($mresponse->is_error()) {
 3674: 		      unlink($filename.'.meta');
 3675:                       &logthis(
 3676:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
 3677:                   }
 3678: 	       }
 3679:                rename($transname,$filename);
 3680:                return 'ok';
 3681:            }
 3682:        }
 3683:     }
 3684: }
 3685: 
 3686: # ------------------------------------------------- Unsubscribe from a resource
 3687: 
 3688: sub unsubscribe {
 3689:     my ($fname) = @_;
 3690:     my $answer;
 3691:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return $answer; }
 3692:     $fname=~s/[\n\r]//g;
 3693:     my $author=$fname;
 3694:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 3695:     my ($udom,$uname)=split(/\//,$author);
 3696:     my $home=homeserver($uname,$udom);
 3697:     if ($home eq 'no_host') {
 3698:         $answer = 'no_host';
 3699:     } elsif (grep { $_ eq $home } &current_machine_ids()) {
 3700:         $answer = 'home';
 3701:     } else {
 3702:         my $defdom = $perlvar{'lonDefDomain'};
 3703:         if (&will_trust('content',$defdom,$udom)) {
 3704:             $answer = reply("unsub:$fname",$home);
 3705:         } else {
 3706:             $answer = 'untrusted';
 3707:         }
 3708:     }
 3709:     return $answer;
 3710: }
 3711: 
 3712: # ------------------------------------------------ Get server side include body
 3713: sub ssi_body {
 3714:     my ($filelink,%form)=@_;
 3715:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
 3716:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
 3717:     }
 3718:     my $output='';
 3719:     my $response;
 3720:     if ($filelink=~/^https?\:/) {
 3721:        ($output,$response)=&externalssi($filelink);
 3722:     } else {
 3723:        $filelink .= $filelink=~/\?/ ? '&' : '?';
 3724:        $filelink .= 'inhibitmenu=yes';
 3725:        ($output,$response)=&ssi($filelink,%form);
 3726:     }
 3727:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
 3728:     $output=~s/^.*?\<body[^\>]*\>//si;
 3729:     $output=~s/\<\/body\s*\>.*?$//si;
 3730:     if (wantarray) {
 3731:         return ($output, $response);
 3732:     } else {
 3733:         return $output;
 3734:     }
 3735: }
 3736: 
 3737: # --------------------------------------------------------- Server Side Include
 3738: 
 3739: sub absolute_url {
 3740:     my ($host_name,$unalias,$keep_proto) = @_;
 3741:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
 3742:     if ($host_name eq '') {
 3743: 	$host_name = $ENV{'SERVER_NAME'};
 3744:     }
 3745:     if ($unalias) {
 3746:         my $alias = &get_proxy_alias();
 3747:         if ($alias eq $host_name) {
 3748:             my $lonhost = $perlvar{'lonHostID'};
 3749:             my $hostname = &hostname($lonhost);
 3750:             my $lcproto; 
 3751:             if (($keep_proto) || ($hostname eq '')) {
 3752:                 $lcproto = $protocol;
 3753:             } else {
 3754:                 $lcproto = $protocol{$lonhost};
 3755:                 $lcproto = 'http' if ($lcproto ne 'https');
 3756:                 $lcproto .= '://';
 3757:             }
 3758:             unless ($hostname eq '') {
 3759:                 return $lcproto.$hostname;
 3760:             }
 3761:         }
 3762:     }
 3763:     return $protocol.$host_name;
 3764: }
 3765: 
 3766: #
 3767: #   Server side include.
 3768: # Parameters:
 3769: #  fn     Possibly encrypted resource name/id.
 3770: #  form   Hash that describes how the rendering should be done
 3771: #         and other things.
 3772: # Returns:
 3773: #   Scalar context: The content of the response.
 3774: #   Array context:  2 element list of the content and the full response object.
 3775: #     
 3776: sub ssi {
 3777: 
 3778:     my ($fn,%form)=@_;
 3779:     my ($host,$request,$response);
 3780:     $host = &absolute_url('',1);
 3781: 
 3782:     $form{'no_update_last_known'}=1;
 3783:     &Apache::lonenc::check_encrypt(\$fn);
 3784:     if (%form) {
 3785:       $request=new HTTP::Request('POST',$host.$fn);
 3786:       $request->content(join('&',map { 
 3787:             my $name = escape($_);
 3788:             "$name=" . ( ref($form{$_}) eq 'ARRAY' 
 3789:             ? join("&$name=", map {escape($_) } @{$form{$_}}) 
 3790:             : &escape($form{$_}) );    
 3791:         } keys(%form)));
 3792:     } else {
 3793:       $request=new HTTP::Request('GET',$host.$fn);
 3794:     }
 3795: 
 3796:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
 3797:     my $lonhost = $perlvar{'lonHostID'};
 3798:     my $islocal;
 3799:     if (($env{'request.course.id'}) &&
 3800:         ($form{'grade_courseid'} eq $env{'request.course.id'}) &&
 3801:         ($form{'grade_username'} ne '') && ($form{'grade_domain'} ne '') &&
 3802:         ($form{'grade_symb'} ne '') &&
 3803:         (&allowed('mgr',$env{'request.course.id'}.
 3804:                         ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:'')))) {
 3805:         $islocal = 1;
 3806:     }
 3807:     $response= &LONCAPA::LWPReq::makerequest($lonhost,$request,'',\%perlvar,
 3808:                                              '','','',$islocal);
 3809: 
 3810:     if (wantarray) {
 3811: 	return ($response->content, $response);
 3812:     } else {
 3813: 	return $response->content;
 3814:     }
 3815: }
 3816: 
 3817: sub externalssi {
 3818:     my ($url)=@_;
 3819:     my $request=new HTTP::Request('GET',$url);
 3820:     my $response = &LONCAPA::LWPReq::makerequest('',$request,'',\%perlvar);
 3821:     if (wantarray) {
 3822:         return ($response->content, $response);
 3823:     } else {
 3824:         return $response->content;
 3825:     }
 3826: }
 3827: 
 3828: 
 3829: # If the local copy of a replicated resource is outdated, trigger a  
 3830: # connection from the homeserver to flush the delayed queue. If no update 
 3831: # happens, remove local copies of outdated resource (and corresponding
 3832: # metadata file).
 3833: 
 3834: sub remove_stale_resfile {
 3835:     my ($url) = @_;
 3836:     my $removed;
 3837:     if ($url=~m{^/res/($match_domain)/($match_username)/}) {
 3838:         my $audom = $1;
 3839:         my $auname = $2;
 3840:         unless (($url =~ /\.\d+\.\w+$/) || ($url =~ m{^/res/lib/templates/})) {
 3841:             my $homeserver = &homeserver($auname,$audom);
 3842:             unless (($homeserver eq 'no_host') ||
 3843:                     (grep { $_ eq $homeserver } &current_machine_ids())) {
 3844:                 my $fname = &filelocation('',$url);
 3845:                 if (-e $fname) {
 3846:                     my $hostname = &hostname($homeserver);
 3847:                     if ($hostname) {
 3848:                         my $protocol = $protocol{$homeserver};
 3849:                         $protocol = 'http' if ($protocol ne 'https');
 3850:                         my $uri = &declutter($url);
 3851:                         my $request=new HTTP::Request('HEAD',$protocol.'://'.$hostname.'/raw/'.$uri);
 3852:                         my $response = &LONCAPA::LWPReq::makerequest($homeserver,$request,'',\%perlvar,5,0,1);
 3853:                         if ($response->is_success()) {
 3854:                             my $remmodtime = &HTTP::Date::str2time( $response->header('Last-modified') );
 3855:                             my $locmodtime = (stat($fname))[9];
 3856:                             if ($locmodtime < $remmodtime) {
 3857:                                 my $stale;
 3858:                                 my $answer = &reply('pong',$homeserver);
 3859:                                 if ($answer eq $homeserver.':'.$perlvar{'lonHostID'}) {
 3860:                                     sleep(0.2);
 3861:                                     $locmodtime = (stat($fname))[9];
 3862:                                     if ($locmodtime < $remmodtime) {
 3863:                                         my $posstransfer = $fname.'.in.transfer';
 3864:                                         if ((-e $posstransfer) && ($remmodtime < (stat($posstransfer))[9])) {
 3865:                                             $removed = 1;
 3866:                                         } else {
 3867:                                             $stale = 1;
 3868:                                         }
 3869:                                     } else {
 3870:                                         $removed = 1;
 3871:                                     }
 3872:                                 } else {
 3873:                                     $stale = 1;
 3874:                                 }
 3875:                                 if ($stale) {
 3876:                                     if (unlink($fname)) {
 3877:                                         if ($uri!~/\.meta$/) {
 3878:                                             if (-e $fname.'.meta') {
 3879:                                                 unlink($fname.'.meta');
 3880:                                             }
 3881:                                         }
 3882:                                         my $unsubresult = &unsubscribe($fname);
 3883:                                         unless ($unsubresult eq 'ok') {
 3884:                                             &logthis("no unsub of $fname from $homeserver, reason: $unsubresult");
 3885:                                         }
 3886:                                         $removed = 1;
 3887:                                     }
 3888:                                 }
 3889:                             }
 3890:                         }
 3891:                     }
 3892:                 }
 3893:             }
 3894:         }
 3895:     }
 3896:     return $removed;
 3897: }
 3898: 
 3899: # -------------------------------- Allow a /uploaded/ URI to be vouched for
 3900: 
 3901: sub allowuploaded {
 3902:     my ($srcurl,$url)=@_;
 3903:     $url=&clutter(&declutter($url));
 3904:     my $dir=$url;
 3905:     $dir=~s/\/[^\/]+$//;
 3906:     my %httpref=();
 3907:     my $httpurl=&hreflocation('',$url);
 3908:     $httpref{'httpref.'.$httpurl}=$srcurl;
 3909:     &Apache::lonnet::appenv(\%httpref);
 3910: }
 3911: 
 3912: #
 3913: # Determine if the current user should be able to edit a particular resource,
 3914: # when viewing in course context.
 3915: # (a) When viewing resource used to determine if "Edit" item is included in 
 3916: #     Functions.
 3917: # (b) When displaying folder contents in course editor, used to determine if
 3918: #     "Edit" link will be displayed alongside resource.
 3919: #
 3920: #  input: six args -- filename (decluttered), course number, course domain,
 3921: #                   url, symb (if registered) and group (if this is a group
 3922: #                   item -- e.g., bulletin board, group page etc.).
 3923: #  output: array of five scalars -- 
 3924: #          $cfile -- url for file editing if editable on current server
 3925: #          $home -- homeserver of resource (i.e., for author if published,
 3926: #                                           or course if uploaded.).
 3927: #          $switchserver --  1 if server switch will be needed.
 3928: #          $forceedit -- 1 if icon/link should be to go to edit mode 
 3929: #          $forceview -- 1 if icon/link should be to go to view mode
 3930: #
 3931: 
 3932: sub can_edit_resource {
 3933:     my ($file,$cnum,$cdom,$resurl,$symb,$group) = @_;
 3934:     my ($cfile,$home,$switchserver,$forceedit,$forceview,$uploaded,$incourse);
 3935: #
 3936: # For aboutme pages user can only edit his/her own.
 3937: #
 3938:     if ($resurl =~ m{^/?adm/($match_domain)/($match_username)/aboutme$}) {
 3939:         my ($sdom,$sname) = ($1,$2);
 3940:         if (($sdom eq $env{'user.domain'}) && ($sname eq $env{'user.name'})) {
 3941:             $home = $env{'user.home'};
 3942:             $cfile = $resurl;
 3943:             if ($env{'form.forceedit'}) {
 3944:                 $forceview = 1;
 3945:             } else {
 3946:                 $forceedit = 1;
 3947:             }
 3948:             return ($cfile,$home,$switchserver,$forceedit,$forceview);
 3949:         } else {
 3950:             return;
 3951:         }
 3952:     }
 3953: 
 3954: #
 3955: # For /adm/viewcoauthors can only edit if author or co-author who is manager.
 3956: #
 3957: 
 3958:     if (($resurl eq '/adm/viewcoauthors') && ($cnum ne '') && ($cdom ne '')) {
 3959:         if (((&allowed('cca',"$cdom/$cnum")) ||
 3960:              (&allowed('caa',"$cdom/$cnum"))) ||
 3961:              ((&allowed('vca',"$cdom/$cnum") ||
 3962:                &allowed('vaa',"$cdom/$cnum")) &&
 3963:               ($env{"environment.internal.manager./$cdom/$cnum"}))) {
 3964:             $home = $env{'user.home'};
 3965:             $cfile = $resurl;
 3966:             if ($env{'form.forceedit'}) {
 3967:                 $forceview = 1;
 3968:             } else {
 3969:                 $forceedit = 1;
 3970:             }
 3971:             return ($cfile,$home,$switchserver,$forceedit,$forceview);
 3972:         } else {
 3973:             return;
 3974:         }
 3975:     }
 3976: 
 3977:     if ($env{'request.course.id'}) {
 3978:         my $crsedit = &allowed('mdc',$env{'request.course.id'});
 3979:         if ($group ne '') {
 3980: # if this is a group homepage or group bulletin board, check group privs
 3981:             my $allowed = 0;
 3982:             if ($resurl =~ m{^/?adm/$cdom/$cnum/$group/smppg$}) {
 3983:                 if ((&allowed('mdg',$env{'request.course.id'}.
 3984:                               ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
 3985:                         (&allowed('mgh',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
 3986:                     $allowed = 1;
 3987:                 }
 3988:             } elsif ($resurl =~ m{^/?adm/$cdom/$cnum/\d+/bulletinboard$}) {
 3989:                 if ((&allowed('mdg',$env{'request.course.id'}.($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
 3990:                         (&allowed('cgb',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
 3991:                     $allowed = 1;
 3992:                 }
 3993:             }
 3994:             if ($allowed) {
 3995:                 $home=&homeserver($cnum,$cdom);
 3996:                 if ($env{'form.forceedit'}) {
 3997:                     $forceview = 1;
 3998:                 } else {
 3999:                     $forceedit = 1;
 4000:                 }
 4001:                 $cfile = $resurl;
 4002:             } else {
 4003:                 return;
 4004:             }
 4005:         } else {
 4006:             if ($resurl =~ m{^/?adm/viewclasslist$}) {
 4007:                 unless (&allowed('opa',$env{'request.course.id'})) {
 4008:                     return;
 4009:                 }
 4010:             } elsif (!$crsedit) {
 4011:                 if ($env{'request.role'} =~ m{^st\./$cdom/$cnum}) {
 4012: #
 4013: # No edit allowed where CC has switched to student role.
 4014: #
 4015:                     return;
 4016:                 } elsif (($resurl !~ m{^/res/$match_domain/$match_username/}) ||
 4017:                          ($resurl =~ m{^/res/lib/templates/})) {
 4018:                     return;
 4019:                 }
 4020:             }
 4021:         }
 4022:     }
 4023: 
 4024:     if ($file ne '') {
 4025:         if (($cnum =~ /$match_courseid/) && ($cdom =~ /$match_domain/)) {
 4026:             if (&is_course_upload($file,$cnum,$cdom)) {
 4027:                 $uploaded = 1;
 4028:                 $incourse = 1;
 4029:                 if ($file =~/\.(htm|html|css|js|txt)$/) {
 4030:                     $cfile = &hreflocation('',$file);
 4031:                     if ($env{'form.forceedit'}) {
 4032:                         $forceview = 1;
 4033:                     } else {
 4034:                         $forceedit = 1;
 4035:                     }
 4036:                 }
 4037:             } elsif ($resurl =~ m{^/public/$cdom/$cnum/syllabus}) {
 4038:                 $incourse = 1;
 4039:                 if ($env{'form.forceedit'}) {
 4040:                     $forceview = 1;
 4041:                 } else {
 4042:                     $forceedit = 1;
 4043:                 }
 4044:                 $cfile = $resurl;
 4045:             } elsif (($resurl ne '') && (&is_on_map($resurl))) {
 4046:                 if ($resurl =~ m{^/adm/$match_domain/$match_username/\d+/smppg|bulletinboard$}) {
 4047:                     $incourse = 1;
 4048:                     if ($env{'form.forceedit'}) {
 4049:                         $forceview = 1;
 4050:                     } else {
 4051:                         $forceedit = 1;
 4052:                     }
 4053:                     $cfile = $resurl;
 4054:                 } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem') {
 4055:                     $incourse = 1;
 4056:                     $cfile = $resurl.'/smpedit';
 4057:                 } elsif ($resurl =~ m{^/adm/wrapper/ext/}) {
 4058:                     $incourse = 1;
 4059:                     if ($env{'form.forceedit'}) {
 4060:                         $forceview = 1;
 4061:                     } else {
 4062:                         $forceedit = 1;
 4063:                     }
 4064:                     $cfile = $resurl;
 4065:                 } elsif (($resurl =~ m{^/ext/}) && ($symb ne '')) {
 4066:                     my ($map,$id,$res) = &decode_symb($symb);
 4067:                     if ($map =~ /\.page$/) {
 4068:                         $incourse = 1;
 4069:                         if ($env{'form.forceedit'}) {
 4070:                             $forceview = 1;
 4071:                             $cfile = $map;
 4072:                         } else {
 4073:                             $forceedit = 1;
 4074:                             $cfile =  '/adm/wrapper'.$resurl;
 4075:                         }
 4076:                     }
 4077:                 } elsif ($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/ext\.tool$}) {
 4078:                     $incourse = 1;
 4079:                     if ($env{'form.forceedit'}) {
 4080:                         $forceview = 1;
 4081:                     } else {
 4082:                         $forceedit = 1;
 4083:                     }
 4084:                     $cfile = $resurl;
 4085:                 } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
 4086:                     $incourse = 1;
 4087:                     if ($env{'form.forceedit'}) {
 4088:                         $forceview = 1;
 4089:                     } else {
 4090:                         $forceedit = 1;
 4091:                     }
 4092:                     $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
 4093:                 }
 4094:             } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem/smpedit') {
 4095:                 my $template = '/res/lib/templates/simpleproblem.problem';
 4096:                 if (&is_on_map($template)) { 
 4097:                     $incourse = 1;
 4098:                     $forceview = 1;
 4099:                     $cfile = $template;
 4100:                 }
 4101:             } elsif (($resurl =~ m{^/adm/wrapper/ext/}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
 4102:                 $incourse = 1;
 4103:                 if ($env{'form.forceedit'}) {
 4104:                     $forceview = 1;
 4105:                 } else {
 4106:                     $forceedit = 1;
 4107:                 }
 4108:                 $cfile = $resurl;
 4109:             } elsif (($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/ext\.tool$}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
 4110:                 $incourse = 1;
 4111:                 if ($env{'form.forceedit'}) {
 4112:                     $forceview = 1;
 4113:                 } else {
 4114:                     $forceedit = 1;
 4115:                 }
 4116:                 $cfile = $resurl;
 4117:             } elsif (($resurl eq '/adm/extresedit') && ($symb || $env{'form.folderpath'})) {
 4118:                 $incourse = 1;
 4119:                 $forceview = 1;
 4120:                 if ($symb) {
 4121:                     my ($map,$id,$res)=&decode_symb($symb);
 4122:                     $env{'request.symb'} = $symb;
 4123:                     $cfile = &clutter($res);
 4124:                 } else {
 4125:                     $cfile = $env{'form.suppurl'};
 4126:                     my $escfile = &unescape($cfile);
 4127:                     if ($escfile =~ m{^/adm/$cdom/$cnum/\d+/ext\.tool$}) {
 4128:                         $cfile = '/adm/wrapper'.$escfile;
 4129:                     } else {
 4130:                         $escfile =~ s{^http://}{};
 4131:                         $cfile = &escape("/adm/wrapper/ext/$escfile");
 4132:                     }
 4133:                 }
 4134:             } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
 4135:                 if ($env{'form.forceedit'}) {
 4136:                     $forceview = 1;
 4137:                 } else {
 4138:                     $forceedit = 1;
 4139:                 }
 4140:                 $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
 4141:             }
 4142:         }
 4143:         if ($uploaded || $incourse) {
 4144:             $home=&homeserver($cnum,$cdom);
 4145:         } elsif ($file !~ m{/$}) {
 4146:             $file=~s{^(priv/$match_domain/$match_username)}{/$1};
 4147:             $file=~s{^($match_domain/$match_username)}{/priv/$1};
 4148:             # Check that the user has permission to edit this resource
 4149:             my $setpriv = 1;
 4150:             my ($cfuname,$cfudom)=&constructaccess($file,$setpriv);
 4151:             if (defined($cfudom)) {
 4152:                 $home=&homeserver($cfuname,$cfudom);
 4153:                 $cfile=$file;
 4154:             }
 4155:         }
 4156:         if (($cfile ne '') && (!$incourse || $uploaded) && 
 4157:             (($home ne '') && ($home ne 'no_host'))) {
 4158:             my @ids=&current_machine_ids();
 4159:             unless (grep(/^\Q$home\E$/,@ids)) {
 4160:                 $switchserver=1;
 4161:             }
 4162:         }
 4163:     }
 4164:     return ($cfile,$home,$switchserver,$forceedit,$forceview);
 4165: }
 4166: 
 4167: sub is_course_upload {
 4168:     my ($file,$cnum,$cdom) = @_;
 4169:     my $uploadpath = &LONCAPA::propath($cdom,$cnum);
 4170:     $uploadpath =~ s{^\/}{};
 4171:     if (($file =~ m{^\Q$uploadpath\E/userfiles/(docs|supplemental)/}) ||
 4172:         ($file =~ m{^userfiles/\Q$cdom\E/\Q$cnum\E/(docs|supplemental)/})) {
 4173:         return 1;
 4174:     }
 4175:     return;
 4176: }
 4177: 
 4178: sub in_course {
 4179:     my ($udom,$uname,$cdom,$cnum,$type,$hideprivileged) = @_;
 4180:     if ($hideprivileged) {
 4181:         my $skipuser;
 4182:         my %coursehash = &coursedescription($cdom.'_'.$cnum);
 4183:         my @possdoms = ($cdom);  
 4184:         if ($coursehash{'checkforpriv'}) { 
 4185:             push(@possdoms,split(/,/,$coursehash{'checkforpriv'})); 
 4186:         }
 4187:         if (&privileged($uname,$udom,\@possdoms)) {
 4188:             $skipuser = 1;
 4189:             if ($coursehash{'nothideprivileged'}) {
 4190:                 foreach my $item (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 4191:                     my $user;
 4192:                     if ($item =~ /:/) {
 4193:                         $user = $item;
 4194:                     } else {
 4195:                         $user = join(':',split(/[\@]/,$item));
 4196:                     }
 4197:                     if ($user eq $uname.':'.$udom) {
 4198:                         undef($skipuser);
 4199:                         last;
 4200:                     }
 4201:                 }
 4202:             }
 4203:             if ($skipuser) {
 4204:                 return 0;
 4205:             }
 4206:         }
 4207:     }
 4208:     $type ||= 'any';
 4209:     if (!defined($cdom) || !defined($cnum)) {
 4210:         my $cid  = $env{'request.course.id'};
 4211:         $cdom = $env{'course.'.$cid.'.domain'};
 4212:         $cnum = $env{'course.'.$cid.'.num'};
 4213:     }
 4214:     my $typesref;
 4215:     if (($type eq 'any') || ($type eq 'all')) {
 4216:         $typesref = ['active','previous','future'];
 4217:     } elsif ($type eq 'previous' || $type eq 'future') {
 4218:         $typesref = [$type];
 4219:     }
 4220:     my %roles = &get_my_roles($uname,$udom,'userroles',
 4221:                               $typesref,undef,[$cdom]);
 4222:     my ($tmp) = keys(%roles);
 4223:     return 0 if ($tmp =~ /^(con_lost|error|no_such_host)/i);
 4224:     my @course_roles = grep(/^\Q$cnum\E:\Q$cdom\E:/, keys(%roles));
 4225:     if (@course_roles > 0) {
 4226:         return 1;
 4227:     }
 4228:     return 0;
 4229: }
 4230: 
 4231: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
 4232: # input: action, courseID, current domain, intended
 4233: #        path to file, source of file, instruction to parse file for objects,
 4234: #        ref to hash for embedded objects,
 4235: #        ref to hash for codebase of java objects.
 4236: #        reference to scalar to accommodate mime type determined
 4237: #          from File::MMagic if $parser = parse.
 4238: #
 4239: # output: url to file (if action was uploaddoc), 
 4240: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
 4241: #
 4242: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
 4243: # course.
 4244: #
 4245: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 4246: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
 4247: #          course's home server.
 4248: #
 4249: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
 4250: #          be copied from $source (current location) to 
 4251: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 4252: #         and will then be copied to
 4253: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
 4254: #         course's home server.
 4255: #
 4256: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 4257: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
 4258: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 4259: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
 4260: #         in course's home server.
 4261: #
 4262: 
 4263: sub process_coursefile {
 4264:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
 4265:         $mimetype)=@_;
 4266:     my $fetchresult;
 4267:     my $home=&homeserver($docuname,$docudom);
 4268:     if ($action eq 'propagate') {
 4269:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 4270: 			     $home);
 4271:     } else {
 4272:         my $fpath = '';
 4273:         my $fname = $file;
 4274:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 4275:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 4276:         my $filepath = &build_filepath($fpath);
 4277:         if ($action eq 'copy') {
 4278:             if ($source eq '') {
 4279:                 $fetchresult = 'no source file';
 4280:                 return $fetchresult;
 4281:             } else {
 4282:                 my $destination = $filepath.'/'.$fname;
 4283:                 rename($source,$destination);
 4284:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 4285:                                  $home);
 4286:             }
 4287:         } elsif ($action eq 'uploaddoc') {
 4288:             open(my $fh,'>',$filepath.'/'.$fname);
 4289:             print $fh $env{'form.'.$source};
 4290:             close($fh);
 4291:             if ($parser eq 'parse') {
 4292:                 my $mm = new File::MMagic;
 4293:                 my $type = $mm->checktype_filename($filepath.'/'.$fname);
 4294:                 if ($type eq 'text/html') {
 4295:                     my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
 4296:                     unless ($parse_result eq 'ok') {
 4297:                         &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
 4298:                     }
 4299:                 }
 4300:                 if (ref($mimetype)) {
 4301:                     $$mimetype = $type;
 4302:                 } 
 4303:             }
 4304:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 4305:                                  $home);
 4306:             if ($fetchresult eq 'ok') {
 4307:                 return '/uploaded/'.$fpath.'/'.$fname;
 4308:             } else {
 4309:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 4310:                         ' to host '.$home.': '.$fetchresult);
 4311:                 return '/adm/notfound.html';
 4312:             }
 4313:         }
 4314:     }
 4315:     unless ( $fetchresult eq 'ok') {
 4316:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 4317:              ' to host '.$home.': '.$fetchresult);
 4318:     }
 4319:     return $fetchresult;
 4320: }
 4321: 
 4322: sub build_filepath {
 4323:     my ($fpath) = @_;
 4324:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
 4325:     unless ($fpath eq '') {
 4326:         my @parts=split('/',$fpath);
 4327:         foreach my $part (@parts) {
 4328:             $filepath.= '/'.$part;
 4329:             if ((-e $filepath)!=1) {
 4330:                 mkdir($filepath,0777);
 4331:             }
 4332:         }
 4333:     }
 4334:     return $filepath;
 4335: }
 4336: 
 4337: sub store_edited_file {
 4338:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
 4339:     my $file = $primary_url;
 4340:     $file =~ s#^/uploaded/$docudom/$docuname/##;
 4341:     my $fpath = '';
 4342:     my $fname = $file;
 4343:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 4344:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 4345:     my $filepath = &build_filepath($fpath);
 4346:     open(my $fh,'>',$filepath.'/'.$fname);
 4347:     print $fh $content;
 4348:     close($fh);
 4349:     my $home=&homeserver($docuname,$docudom);
 4350:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 4351: 			  $home);
 4352:     if ($$fetchresult eq 'ok') {
 4353:         return '/uploaded/'.$fpath.'/'.$fname;
 4354:     } else {
 4355:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 4356: 		 ' to host '.$home.': '.$$fetchresult);
 4357:         return '/adm/notfound.html';
 4358:     }
 4359: }
 4360: 
 4361: sub clean_filename {
 4362:     my ($fname,$args)=@_;
 4363: # Replace Windows backslashes by forward slashes
 4364:     $fname=~s/\\/\//g;
 4365:     if (!$args->{'keep_path'}) {
 4366:         # Get rid of everything but the actual filename
 4367: 	$fname=~s/^.*\/([^\/]+)$/$1/;
 4368:     }
 4369: # Replace spaces by underscores
 4370:     $fname=~s/\s+/\_/g;
 4371: # Transliterate non-ascii text to ascii
 4372:     my $lang = &Apache::lonlocal::current_language();
 4373:     $fname = &LONCAPA::transliterate::fname_to_ascii($fname,$lang);
 4374: # Replace all other weird characters by nothing
 4375:     $fname=~s{[^/\w\.\-]}{}g;
 4376: # Replace all .\d. sequences with _\d. so they no longer look like version
 4377: # numbers
 4378:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
 4379: # Replace three or more adjacent underscores with one for consistency 
 4380: # with loncfile::filename_check() so complete url can be extracted by
 4381: # lonnet::decode_symb()
 4382:     $fname=~s/_{3,}/_/g;
 4383:     return $fname;
 4384: }
 4385: 
 4386: # This Function checks if an Image's dimensions exceed either $resizewidth (width) 
 4387: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an 
 4388: # image with the same aspect ratio as the original, but with dimensions which do 
 4389: # not exceed $resizewidth and $resizeheight.
 4390:  
 4391: sub resizeImage {
 4392:     my ($img_path,$resizewidth,$resizeheight) = @_;
 4393:     my $ima = Image::Magick->new;
 4394:     my $resized;
 4395:     if (-e $img_path) {
 4396:         $ima->Read($img_path);
 4397:         if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
 4398:             my $width = $ima->Get('width');
 4399:             my $height = $ima->Get('height');
 4400:             if ($width > $resizewidth) {
 4401: 	        my $factor = $width/$resizewidth;
 4402:                 my $newheight = $height/$factor;
 4403:                 $ima->Scale(width=>$resizewidth,height=>$newheight);
 4404:                 $resized = 1;
 4405:             }
 4406:         }
 4407:         if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
 4408:             my $width = $ima->Get('width');
 4409:             my $height = $ima->Get('height');
 4410:             if ($height > $resizeheight) {
 4411:                 my $factor = $height/$resizeheight;
 4412:                 my $newwidth = $width/$factor;
 4413:                 $ima->Scale(width=>$newwidth,height=>$resizeheight);
 4414:                 $resized = 1;
 4415:             }
 4416:         }
 4417:         if ($resized) {
 4418:             $ima->Write($img_path);
 4419:         }
 4420:     }
 4421:     return;
 4422: }
 4423: 
 4424: # --------------- Take an uploaded file and put it into the userfiles directory
 4425: # input: $formname - the contents of the file are in $env{"form.$formname"}
 4426: #                    the desired filename is in $env{"form.$formname.filename"}
 4427: #        $context - possible values: coursedoc, existingfile, overwrite, 
 4428: #                                    canceloverwrite, scantron, toollogo  or ''.
 4429: #                   if 'coursedoc': upload to the current course
 4430: #                   if 'existingfile': write file to tmp/overwrites directory 
 4431: #                   if 'canceloverwrite': delete file written to tmp/overwrites directory
 4432: #                   $context is passed as argument to &finishuserfileupload
 4433: #        $subdir - directory in userfile to store the file into
 4434: #        $parser - instruction to parse file for objects ($parser = parse) or
 4435: #                  if context is 'scantron', $parser is hashref of csv column mapping
 4436: #                  (e.g.,{ PaperID => 0, LastName => 1, FirstName => 2, ID => 3, 
 4437: #                          Section => 4, CODE => 5, FirstQuestion => 9 }).
 4438: #        $allfiles - reference to hash for embedded objects
 4439: #        $codebase - reference to hash for codebase of java objects
 4440: #        $destuname - username for permanent storage of uploaded file
 4441: #        $destudom - domain for permanaent storage of uploaded file
 4442: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
 4443: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
 4444: #        $resizewidth - width (pixels) to which to resize uploaded image
 4445: #        $resizeheight - height (pixels) to which to resize uploaded image
 4446: #        $mimetype - reference to scalar to accommodate mime type determined
 4447: #                    from File::MMagic.
 4448: # 
 4449: # output: url of file in userspace, or error: <message> 
 4450: #             or /adm/notfound.html if failure to upload occurse
 4451: 
 4452: sub userfileupload {
 4453:     my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
 4454:         $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
 4455:     if (!defined($subdir)) { $subdir='unknown'; }
 4456:     my $fname=$env{'form.'.$formname.'.filename'};
 4457:     $fname=&clean_filename($fname);
 4458:     # See if there is anything left
 4459:     unless ($fname) { return 'error: no uploaded file'; }
 4460:     # If filename now begins with a . prepend unix timestamp _ milliseconds
 4461:     if ($fname =~ /^\./) {
 4462:         my ($s,$usec) = &gettimeofday();
 4463:         while (length($usec) < 6) {
 4464:             $usec = '0'.$usec;
 4465:         }
 4466:         $fname = $s.'_'.substr($usec,0,3).$fname;
 4467:     }
 4468:     # Files uploaded to help request form, or uploaded to "create course" page are handled differently
 4469:     if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
 4470:         (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
 4471:          ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
 4472:         my $now = time;
 4473:         my $filepath;
 4474:         if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
 4475:              $filepath = 'tmp/helprequests/'.$now;
 4476:         } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
 4477:              $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
 4478:                          '_'.$env{'user.domain'}.'/pending';
 4479:         } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
 4480:             my ($docuname,$docudom);
 4481:             if ($destudom =~ /^$match_domain$/) {
 4482:                 $docudom = $destudom;
 4483:             } else {
 4484:                 $docudom = $env{'user.domain'};
 4485:             }
 4486:             if ($destuname =~ /^$match_username$/) {
 4487:                 $docuname = $destuname;
 4488:             } else {
 4489:                 $docuname = $env{'user.name'};
 4490:             }
 4491:             if (exists($env{'form.group'})) {
 4492:                 $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 4493:                 $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 4494:             }
 4495:             $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
 4496:             if ($context eq 'canceloverwrite') {
 4497:                 my $tempfile =  $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
 4498:                 if (-e  $tempfile) {
 4499:                     my @info = stat($tempfile);
 4500:                     if ($info[9] eq $env{'form.timestamp'}) {
 4501:                         unlink($tempfile);
 4502:                     }
 4503:                 }
 4504:                 return;
 4505:             }
 4506:         }
 4507:         # Create the directory if not present
 4508:         my @parts=split(/\//,$filepath);
 4509:         my $fullpath = $perlvar{'lonDaemons'};
 4510:         for (my $i=0;$i<@parts;$i++) {
 4511:             $fullpath .= '/'.$parts[$i];
 4512:             if ((-e $fullpath)!=1) {
 4513:                 mkdir($fullpath,0777);
 4514:             }
 4515:         }
 4516:         open(my $fh,'>',$fullpath.'/'.$fname);
 4517:         print $fh $env{'form.'.$formname};
 4518:         close($fh);
 4519:         if ($context eq 'existingfile') {
 4520:             my @info = stat($fullpath.'/'.$fname);
 4521:             return ($fullpath.'/'.$fname,$info[9]);
 4522:         } else {
 4523:             return $fullpath.'/'.$fname;
 4524:         }
 4525:     }
 4526:     if ($subdir eq 'scantron') {
 4527:         $fname = 'scantron_orig_'.$fname;
 4528:     } else {
 4529:         $fname="$subdir/$fname";
 4530:     }
 4531:     if ($context eq 'coursedoc') {
 4532: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 4533: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 4534:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
 4535:             return &finishuserfileupload($docuname,$docudom,
 4536: 					 $formname,$fname,$parser,$allfiles,
 4537: 					 $codebase,$thumbwidth,$thumbheight,
 4538:                                          $resizewidth,$resizeheight,$context,$mimetype);
 4539:         } else {
 4540:             if ($env{'form.folder'}) {
 4541:                 $fname=$env{'form.folder'}.'/'.$fname;
 4542:             }
 4543:             return &process_coursefile('uploaddoc',$docuname,$docudom,
 4544: 				       $fname,$formname,$parser,
 4545: 				       $allfiles,$codebase,$mimetype);
 4546:         }
 4547:     } elsif (defined($destuname)) {
 4548:         my $docuname=$destuname;
 4549:         my $docudom=$destudom;
 4550: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
 4551: 				     $parser,$allfiles,$codebase,
 4552:                                      $thumbwidth,$thumbheight,
 4553:                                      $resizewidth,$resizeheight,$context,$mimetype);
 4554:     } else {
 4555:         my $docuname=$env{'user.name'};
 4556:         my $docudom=$env{'user.domain'};
 4557:         if ((exists($env{'form.group'})) || ($context eq 'syllabus')) {
 4558:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 4559:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 4560:         }
 4561: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
 4562: 				     $parser,$allfiles,$codebase,
 4563:                                      $thumbwidth,$thumbheight,
 4564:                                      $resizewidth,$resizeheight,$context,$mimetype);
 4565:     }
 4566: }
 4567: 
 4568: sub finishuserfileupload {
 4569:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
 4570:         $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
 4571:     my $path=$docudom.'/'.$docuname.'/';
 4572:     my $filepath=$perlvar{'lonDocRoot'};
 4573:   
 4574:     my ($fnamepath,$file,$fetchthumb);
 4575:     $file=$fname;
 4576:     if ($fname=~m|/|) {
 4577:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
 4578: 	$path.=$fnamepath.'/';
 4579:     }
 4580:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
 4581:     my $count;
 4582:     for ($count=4;$count<=$#parts;$count++) {
 4583:         $filepath.="/$parts[$count]";
 4584:         if ((-e $filepath)!=1) {
 4585: 	    mkdir($filepath,0777);
 4586:         }
 4587:     }
 4588: 
 4589: # Save the file
 4590:     {
 4591: 	if (!open(FH,'>',$filepath.'/'.$file)) {
 4592: 	    &logthis('Failed to create '.$filepath.'/'.$file);
 4593: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
 4594: 	    return '/adm/notfound.html';
 4595: 	}
 4596:         if ($context eq 'overwrite') {
 4597:             my $source =  LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
 4598:             my $target = $filepath.'/'.$file;
 4599:             if (-e $source) {
 4600:                 my @info = stat($source);
 4601:                 if ($info[9] eq $env{'form.timestamp'}) {   
 4602:                     unless (&File::Copy::move($source,$target)) {
 4603:                         &logthis('Failed to overwrite '.$filepath.'/'.$file);
 4604:                         return "Moving from $source failed";
 4605:                     }
 4606:                 } else {
 4607:                     return "Temporary file: $source had unexpected date/time for last modification";
 4608:                 }
 4609:             } else {
 4610:                 return "Temporary file: $source missing";
 4611:             }
 4612:         } elsif (!print FH ($env{'form.'.$formname})) {
 4613: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
 4614: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
 4615: 	    return '/adm/notfound.html';
 4616: 	}
 4617: 	close(FH);
 4618:         if ($resizewidth && $resizeheight) {
 4619:             my $mm = new File::MMagic;
 4620:             my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
 4621:             if ($mime_type =~ m{^image/}) {
 4622: 	        &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
 4623:             }  
 4624: 	}
 4625:     }
 4626:     if (($context eq 'coursedoc') || ($parser eq 'parse')) {
 4627:         if (ref($mimetype)) {
 4628:             if ($$mimetype eq '') {
 4629:                 my $mm = new File::MMagic;
 4630:                 my $type = $mm->checktype_filename($filepath.'/'.$file);
 4631:                 $$mimetype = $type;
 4632:             }
 4633:         }
 4634:     }
 4635:     if (($context ne 'scantron') && ($parser eq 'parse')) {
 4636:         if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
 4637:             my $parse_result = &extract_embedded_items($filepath.'/'.$file,
 4638:                                                        $allfiles,$codebase);
 4639:             unless ($parse_result eq 'ok') {
 4640:                 &logthis('Failed to parse '.$filepath.$file.
 4641: 	   	         ' for embedded media: '.$parse_result); 
 4642:             }
 4643:         }
 4644:     } elsif (($context eq 'scantron') && (ref($parser) eq 'HASH')) {
 4645:         my $format = $env{'form.scantron_format'};
 4646:         &bubblesheet_converter($docudom,$filepath.'/'.$file,$parser,$format);
 4647:     }
 4648:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
 4649:         my $input = $filepath.'/'.$file;
 4650:         my $output = $filepath.'/'.'tn-'.$file;
 4651:         my $makethumb; 
 4652:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
 4653:         if ($context eq 'toollogo') {
 4654:             my ($fullwidth,$fullheight) = &check_dimensions($input);
 4655:             if ($fullwidth ne '' && $fullheight ne '') {
 4656:                 if ($fullwidth > $thumbwidth && $fullheight > $thumbheight) {
 4657:                     $makethumb = 1;
 4658:                 }
 4659:             }
 4660:         } else {
 4661:             $makethumb = 1;
 4662:         }
 4663:         if ($makethumb) {
 4664:             my @args = ('convert','-sample',$thumbsize,$input,$output);
 4665:             system({$args[0]} @args);
 4666:             if (-e $filepath.'/'.'tn-'.$file) {
 4667:                 $fetchthumb  = 1; 
 4668:             }
 4669:         }
 4670:     }
 4671:  
 4672: # Notify homeserver to grep it
 4673: #
 4674:     my $docuhome=&homeserver($docuname,$docudom);	
 4675:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
 4676:     if ($fetchresult eq 'ok') {
 4677:         if ($fetchthumb) {
 4678:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
 4679:             if ($thumbresult ne 'ok') {
 4680:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
 4681:                          $docuhome.': '.$thumbresult);
 4682:             }
 4683:         }
 4684: #
 4685: # Return the URL to it
 4686:         return '/uploaded/'.$path.$file;
 4687:     } else {
 4688:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
 4689: 		 ': '.$fetchresult);
 4690:         return '/adm/notfound.html';
 4691:     }
 4692: }
 4693: 
 4694: sub extract_embedded_items {
 4695:     my ($fullpath,$allfiles,$codebase,$content) = @_;
 4696:     my @state = ();
 4697:     my (%lastids,%related,%shockwave,%flashvars);
 4698:     my %javafiles = (
 4699:                       codebase => '',
 4700:                       code => '',
 4701:                       archive => ''
 4702:                     );
 4703:     my %mediafiles = (
 4704:                       src => '',
 4705:                       movie => '',
 4706:                      );
 4707:     my $p;
 4708:     if ($content) {
 4709:         $p = HTML::LCParser->new($content);
 4710:     } else {
 4711:         $p = HTML::LCParser->new($fullpath);
 4712:     }
 4713:     while (my $t=$p->get_token()) {
 4714: 	if ($t->[0] eq 'S') {
 4715: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
 4716: 	    push(@state, $tagname);
 4717:             if (lc($tagname) eq 'allow') {
 4718:                 &add_filetype($allfiles,$attr->{'src'},'src');
 4719:             }
 4720: 	    if (lc($tagname) eq 'img') {
 4721: 		&add_filetype($allfiles,$attr->{'src'},'src');
 4722: 	    }
 4723: 	    if (lc($tagname) eq 'a') {
 4724:                 unless (($attr->{'href'} =~ /^#/) || ($attr->{'href'} eq '')) {
 4725:                     &add_filetype($allfiles,$attr->{'href'},'href');
 4726:                 }
 4727: 	    }
 4728:             if (lc($tagname) eq 'script') {
 4729:                 my $src;
 4730:                 if ($attr->{'archive'} =~ /\.jar$/i) {
 4731:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
 4732:                 } else {
 4733:                     if ($attr->{'src'} ne '') {
 4734:                         $src = $attr->{'src'};
 4735:                         &add_filetype($allfiles,$src,'src');
 4736:                     }
 4737:                 }
 4738:                 my $text = $p->get_trimmed_text();
 4739:                 if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
 4740:                     my @swfargs = split(/,/,$1);
 4741:                     foreach my $item (@swfargs) {
 4742:                         $item =~ s/["']//g;
 4743:                         $item =~ s/^\s+//;
 4744:                         $item =~ s/\s+$//;
 4745:                     }
 4746:                     if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
 4747:                         if (ref($related{$swfargs[0]}) eq 'ARRAY') {
 4748:                             push(@{$related{$swfargs[0]}},$swfargs[2]);
 4749:                         } else {
 4750:                             $related{$swfargs[0]} = [$swfargs[2]];
 4751:                         }
 4752:                     }
 4753:                 }
 4754:             }
 4755:             if (lc($tagname) eq 'link') {
 4756:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
 4757:                     &add_filetype($allfiles,$attr->{'href'},'href');
 4758:                 }
 4759:             }
 4760: 	    if (lc($tagname) eq 'object' ||
 4761: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
 4762: 		foreach my $item (keys(%javafiles)) {
 4763: 		    $javafiles{$item} = '';
 4764: 		}
 4765:                 if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
 4766:                     $lastids{lc($tagname)} = $attr->{'id'};
 4767:                 }
 4768: 	    }
 4769: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
 4770: 		my $name = lc($attr->{'name'});
 4771: 		foreach my $item (keys(%javafiles)) {
 4772: 		    if ($name eq $item) {
 4773: 			$javafiles{$item} = $attr->{'value'};
 4774: 			last;
 4775: 		    }
 4776: 		}
 4777:                 my $pathfrom;
 4778: 		foreach my $item (keys(%mediafiles)) {
 4779: 		    if ($name eq $item) {
 4780:                         $pathfrom = $attr->{'value'};
 4781:                         $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
 4782: 			&add_filetype($allfiles,$pathfrom,$name);
 4783: 			last;
 4784: 		    }
 4785: 		}
 4786:                 if ($name eq 'flashvars') {
 4787:                     $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
 4788:                 }
 4789:                 if ($pathfrom ne '') {
 4790:                     &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
 4791:                                          $pathfrom);
 4792:                 }
 4793: 	    }
 4794: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
 4795: 		foreach my $item (keys(%javafiles)) {
 4796: 		    if ($attr->{$item}) {
 4797: 			$javafiles{$item} = $attr->{$item};
 4798: 			last;
 4799: 		    }
 4800: 		}
 4801: 		foreach my $item (keys(%mediafiles)) {
 4802: 		    if ($attr->{$item}) {
 4803: 			&add_filetype($allfiles,$attr->{$item},$item);
 4804: 			last;
 4805: 		    }
 4806: 		}
 4807:                 if (lc($tagname) eq 'embed') {
 4808:                     if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
 4809:                         &embedded_dependency($allfiles,\%related,$attr->{'name'},
 4810:                                              $attr->{'src'});
 4811:                     }
 4812:                 }
 4813: 	    }
 4814:             if (lc($tagname) eq 'iframe') {
 4815:                 my $src = $attr->{'src'} ;
 4816:                 if (($src ne '') && ($src !~ m{^(/|https?://)})) {
 4817:                     &add_filetype($allfiles,$src,'src');
 4818:                 } elsif ($src =~ m{^/}) {
 4819:                     if ($env{'request.course.id'}) {
 4820:                         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 4821:                         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 4822:                         my $url = &hreflocation('',$fullpath);
 4823:                         if ($url =~ m{^/uploaded/$cdom/$cnum/docs/(\w+/\d+)/}) {
 4824:                             my $relpath = $1;
 4825:                             if ($src =~ m{^/uploaded/$cdom/$cnum/docs/\Q$relpath\E/(.+)$}) {
 4826:                                 &add_filetype($allfiles,$1,'src');
 4827:                             }
 4828:                         }
 4829:                     }
 4830:                 }
 4831:             }
 4832:             if ($t->[4] =~ m{/>$}) {
 4833:                 pop(@state);
 4834:             }
 4835: 	} elsif ($t->[0] eq 'E') {
 4836: 	    my ($tagname) = ($t->[1]);
 4837: 	    if ($javafiles{'codebase'} ne '') {
 4838: 		$javafiles{'codebase'} .= '/';
 4839: 	    }  
 4840: 	    if (lc($tagname) eq 'applet' ||
 4841: 		lc($tagname) eq 'object' ||
 4842: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
 4843: 		) {
 4844: 		foreach my $item (keys(%javafiles)) {
 4845: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
 4846: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
 4847: 			&add_filetype($allfiles,$file,$item);
 4848: 		    }
 4849: 		}
 4850: 	    } 
 4851: 	    pop @state;
 4852: 	}
 4853:     }
 4854:     foreach my $id (sort(keys(%flashvars))) {
 4855:         if ($shockwave{$id} ne '') {
 4856:             my @pairs = split(/\&/,$flashvars{$id});
 4857:             foreach my $pair (@pairs) {
 4858:                 my ($key,$value) = split(/\=/,$pair);
 4859:                 if ($key eq 'thumb') {
 4860:                     &add_filetype($allfiles,$value,$key);
 4861:                 } elsif ($key eq 'content') {
 4862:                     my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
 4863:                     my ($ext) = ($value =~ /\.([^.]+)$/);
 4864:                     if ($ext ne '') {
 4865:                         &add_filetype($allfiles,$path.$value,$ext);
 4866:                     }
 4867:                 }
 4868:             }
 4869:         }
 4870:     }
 4871:     return 'ok';
 4872: }
 4873: 
 4874: sub add_filetype {
 4875:     my ($allfiles,$file,$type)=@_;
 4876:     if (exists($allfiles->{$file})) {
 4877: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
 4878: 	    push(@{$allfiles->{$file}}, &escape($type));
 4879: 	}
 4880:     } else {
 4881: 	@{$allfiles->{$file}} = (&escape($type));
 4882:     }
 4883: }
 4884: 
 4885: sub embedded_dependency {
 4886:     my ($allfiles,$related,$identifier,$pathfrom) = @_;
 4887:     if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
 4888:         if (($identifier ne '') &&
 4889:             (ref($related->{$identifier}) eq 'ARRAY') &&
 4890:             ($pathfrom ne '')) {
 4891:             my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
 4892:             foreach my $dep (@{$related->{$identifier}}) {
 4893:                 &add_filetype($allfiles,$path.$dep,'object');
 4894:             }
 4895:         }
 4896:     }
 4897:     return;
 4898: }
 4899: 
 4900: sub check_dimensions {
 4901:     my ($inputfile) = @_;
 4902:     my ($fullwidth,$fullheight);
 4903:     if (($inputfile =~ m|^[/\w.\-]+$|) && (-e $inputfile)) {
 4904:         my $mm = new File::MMagic;
 4905:         my $mime_type = $mm->checktype_filename($inputfile);
 4906:         if ($mime_type =~ m{^image/}) {
 4907:             if (open(PIPE,"identify $inputfile 2>&1 |")) {
 4908:                 my $imageinfo = <PIPE>;
 4909:                 if (!close(PIPE)) {
 4910:                     &Apache::lonnet::logthis("Failed to close PIPE opened to retrieve image information for $inputfile");
 4911:                 }
 4912:                 chomp($imageinfo);
 4913:                 my ($fullsize) =
 4914:                     ($imageinfo =~ /^\Q$inputfile\E\s+\w+\s+(\d+x\d+)/);
 4915:                 if ($fullsize) {
 4916:                     ($fullwidth,$fullheight) = split(/x/,$fullsize);
 4917:                 }
 4918:             }
 4919:         }
 4920:     }
 4921:     return ($fullwidth,$fullheight);
 4922: }
 4923: 
 4924: sub bubblesheet_converter {
 4925:     my ($cdom,$fullpath,$config,$format) = @_;
 4926:     if ((&domain($cdom) ne '') &&
 4927:         ($fullpath =~ m{^\Q$perlvar{'lonDocRoot'}/userfiles/$cdom/\E$match_courseid/scantron_orig}) &&
 4928:         (-e $fullpath) && (ref($config) eq 'HASH') && ($format ne '')) {
 4929:         my (%csvcols,%csvoptions);
 4930:         if (ref($config->{'fields'}) eq 'HASH') {  
 4931:             %csvcols = %{$config->{'fields'}};
 4932:         }
 4933:         if (ref($config->{'options'}) eq 'HASH') {
 4934:             %csvoptions = %{$config->{'options'}};
 4935:         }
 4936:         my %csvbynum = reverse(%csvcols);
 4937:         my %scantronconf = &get_scantron_config($format,$cdom);
 4938:         if (keys(%scantronconf)) {
 4939:             my %bynum = (
 4940:                           $scantronconf{CODEstart} => 'CODEstart',
 4941:                           $scantronconf{IDstart}   => 'IDstart',
 4942:                           $scantronconf{PaperID}   => 'PaperID',
 4943:                           $scantronconf{FirstName} => 'FirstName',
 4944:                           $scantronconf{LastName}  => 'LastName',
 4945:                           $scantronconf{Qstart}    => 'Qstart',
 4946:                         );
 4947:             my @ordered;
 4948:             foreach my $item (sort { $a <=> $b } keys(%bynum)) {
 4949:                 push(@ordered,$bynum{$item});
 4950:             }
 4951:             my %mapstart = (
 4952:                               CODEstart => 'CODE',
 4953:                               IDstart   => 'ID',
 4954:                               PaperID   => 'PaperID',
 4955:                               FirstName => 'FirstName',
 4956:                               LastName  => 'LastName',
 4957:                               Qstart    => 'FirstQuestion',
 4958:                            );
 4959:             my %maplength = (
 4960:                               CODEstart => 'CODElength',
 4961:                               IDstart   => 'IDlength',
 4962:                               PaperID   => 'PaperIDlength',
 4963:                               FirstName => 'FirstNamelength',
 4964:                               LastName  => 'LastNamelength',
 4965:             );
 4966:             if (open(my $fh,'<',$fullpath)) {
 4967:                 my $output;
 4968:                 my %lettdig = &letter_to_digits();
 4969:                 my %diglett = reverse(%lettdig);
 4970:                 my $numletts = scalar(keys(%lettdig));
 4971:                 my $num = 0;
 4972:                 while (my $line=<$fh>) {
 4973:                     $num ++;
 4974:                     next if (($num == 1) && ($csvoptions{'hdr'} == 1));
 4975:                     $line =~ s{[\r\n]+$}{};
 4976:                     my %found;
 4977:                     my @values = split(/,/,$line,-1);
 4978:                     my ($qstart,$record);
 4979:                     for (my $i=0; $i<@values; $i++) {
 4980:                         if ((($qstart ne '') && ($i > $qstart)) ||
 4981:                             ($csvbynum{$i} eq 'FirstQuestion')) {
 4982:                             if ($values[$i] eq '') {
 4983:                                 $values[$i] = $scantronconf{'Qoff'};
 4984:                             } elsif ($scantronconf{'Qon'} eq 'number') {
 4985:                                 if ($values[$i] =~ /^[A-Ja-j]$/) {
 4986:                                     $values[$i] = $lettdig{uc($values[$i])};
 4987:                                 }
 4988:                             } elsif ($scantronconf{'Qon'} eq 'letter') {
 4989:                                 if ($values[$i] =~ /^[0-9]$/) {
 4990:                                     $values[$i] = $diglett{$values[$i]};
 4991:                                 }
 4992:                             } else {
 4993:                                 if ($values[$i] =~ /^[0-9A-Ja-j]$/) {
 4994:                                     my $digit;
 4995:                                     if ($values[$i] =~ /^[A-Ja-j]$/) {
 4996:                                         $digit = $lettdig{uc($values[$i])}-1;
 4997:                                         if ($values[$i] eq 'J') {
 4998:                                             $digit += $numletts;
 4999:                                         }
 5000:                                     } elsif ($values[$i] =~ /^[0-9]$/) {
 5001:                                         $digit = $values[$i]-1;
 5002:                                         if ($values[$i] eq '0') {
 5003:                                             $digit += $numletts;
 5004:                                         }
 5005:                                     }
 5006:                                     my $qval='';
 5007:                                     for (my $j=0; $j<$scantronconf{'Qlength'}; $j++) {
 5008:                                         if ($j == $digit) {
 5009:                                             $qval .= $scantronconf{'Qon'};
 5010:                                         } else {
 5011:                                             $qval .= $scantronconf{'Qoff'};
 5012:                                         }
 5013:                                     }
 5014:                                     $values[$i] = $qval;
 5015:                                 }
 5016:                             }
 5017:                             if (length($values[$i]) > $scantronconf{'Qlength'}) {
 5018:                                 $values[$i] = substr($values[$i],0,$scantronconf{'Qlength'});
 5019:                             }
 5020:                             my $numblank = $scantronconf{'Qlength'} - length($values[$i]);
 5021:                             if ($numblank > 0) {
 5022:                                  $values[$i] .= ($scantronconf{'Qoff'} x $numblank);
 5023:                             }
 5024:                             if ($csvbynum{$i} eq 'FirstQuestion') {
 5025:                                 $qstart = $i;
 5026:                                 $found{$csvbynum{$i}} = $values[$i];
 5027:                             } else {
 5028:                                 $found{'FirstQuestion'} .= $values[$i];
 5029:                             }
 5030:                         } elsif (exists($csvbynum{$i})) {
 5031:                             if ($csvoptions{'rem'}) {
 5032:                                 $values[$i] =~ s/^\s+//;
 5033:                             }
 5034:                             if (($csvbynum{$i} eq 'PaperID') && ($csvoptions{'pad'})) {
 5035:                                 while (length($values[$i]) < $scantronconf{$maplength{$csvbynum{$i}}}) {
 5036:                                     $values[$i] = '0'.$values[$i];
 5037:                                 }
 5038:                             }
 5039:                             $found{$csvbynum{$i}} = $values[$i];
 5040:                         }
 5041:                     }
 5042:                     foreach my $item (@ordered) {
 5043:                         my $currlength = 1+length($record);
 5044:                         my $numspaces = $scantronconf{$item} - $currlength;
 5045:                         if ($numspaces > 0) {
 5046:                             $record .= (' ' x $numspaces);
 5047:                         }
 5048:                         if (($mapstart{$item} ne '') && (exists($found{$mapstart{$item}}))) {
 5049:                             unless ($item eq 'Qstart') {
 5050:                                 if (length($found{$mapstart{$item}}) > $scantronconf{$maplength{$item}}) {
 5051:                                     $found{$mapstart{$item}} = substr($found{$mapstart{$item}},0,$scantronconf{$maplength{$item}});
 5052:                                 }
 5053:                             }
 5054:                             $record .= $found{$mapstart{$item}};
 5055:                         }
 5056:                     }
 5057:                     $output .= "$record\n";
 5058:                 }
 5059:                 close($fh);
 5060:                 if ($output) {
 5061:                     if (open(my $fh,'>',$fullpath)) {
 5062:                         print $fh $output;
 5063:                         close($fh);
 5064:                     }
 5065:                 }
 5066:             }
 5067:         }
 5068:         return;
 5069:     }
 5070: }
 5071: 
 5072: sub letter_to_digits {
 5073:     my %lettdig = (
 5074:                     A => 1,
 5075:                     B => 2,
 5076:                     C => 3,
 5077:                     D => 4,
 5078:                     E => 5,
 5079:                     F => 6,
 5080:                     G => 7,
 5081:                     H => 8,
 5082:                     I => 9,
 5083:                     J => 0,
 5084:                   );
 5085:     return %lettdig;
 5086: }
 5087: 
 5088: sub get_scantron_config {
 5089:     my ($which,$cdom) = @_;
 5090:     my @lines = &get_scantronformat_file($cdom);
 5091:     my %config;
 5092:     #FIXME probably should move to XML it has already gotten a bit much now
 5093:     foreach my $line (@lines) {
 5094:         my ($name,$descrip)=split(/:/,$line);
 5095:         if ($name ne $which ) { next; }
 5096:         chomp($line);
 5097:         my @config=split(/:/,$line);
 5098:         $config{'name'}=$config[0];
 5099:         $config{'description'}=$config[1];
 5100:         $config{'CODElocation'}=$config[2];
 5101:         $config{'CODEstart'}=$config[3];
 5102:         $config{'CODElength'}=$config[4];
 5103:         $config{'IDstart'}=$config[5];
 5104:         $config{'IDlength'}=$config[6];
 5105:         $config{'Qstart'}=$config[7];
 5106:         $config{'Qlength'}=$config[8];
 5107:         $config{'Qoff'}=$config[9];
 5108:         $config{'Qon'}=$config[10];
 5109:         $config{'PaperID'}=$config[11];
 5110:         $config{'PaperIDlength'}=$config[12];
 5111:         $config{'FirstName'}=$config[13];
 5112:         $config{'FirstNamelength'}=$config[14];
 5113:         $config{'LastName'}=$config[15];
 5114:         $config{'LastNamelength'}=$config[16];
 5115:         $config{'BubblesPerRow'}=$config[17];
 5116:         last;
 5117:     }
 5118:     return %config;
 5119: }
 5120: 
 5121: sub get_scantronformat_file {
 5122:     my ($cdom) = @_;
 5123:     if ($cdom eq '') {
 5124:         $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
 5125:     }
 5126:     my %domconfig = &get_dom('configuration',['scantron'],$cdom);
 5127:     my $gottab = 0;
 5128:     my @lines;
 5129:     if (ref($domconfig{'scantron'}) eq 'HASH') {
 5130:         if ($domconfig{'scantron'}{'scantronformat'} ne '') {
 5131:             my $formatfile = &getfile($perlvar{'lonDocRoot'}.$domconfig{'scantron'}{'scantronformat'});
 5132:             if ($formatfile ne '-1') {
 5133:                 @lines = split("\n",$formatfile,-1);
 5134:                 $gottab = 1;
 5135:             }
 5136:         }
 5137:     }
 5138:     if (!$gottab) {
 5139:         my $confname = $cdom.'-domainconfig';
 5140:         my $default = $perlvar{'lonDocRoot'}.'/res/'.$cdom.'/'.$confname.'/default.tab';
 5141:         my $formatfile = &getfile($default);
 5142:         if ($formatfile ne '-1') {
 5143:             @lines = split("\n",$formatfile,-1);
 5144:             $gottab = 1;
 5145:         }
 5146:     }
 5147:     if (!$gottab) {
 5148:         my @domains = &current_machine_domains();
 5149:         if (grep(/^\Q$cdom\E$/,@domains)) {
 5150:             if (open(my $fh,'<',$perlvar{'lonTabDir'}.'/scantronformat.tab')) {
 5151:                 @lines = <$fh>;
 5152:                 close($fh);
 5153:             }
 5154:         } else {
 5155:             if (open(my $fh,'<',$perlvar{'lonTabDir'}.'/default_scantronformat.tab')) {
 5156:                 @lines = <$fh>;
 5157:                 close($fh);
 5158:             }
 5159:         }
 5160:         chomp(@lines);
 5161:     }
 5162:     return @lines;
 5163: }
 5164: 
 5165: sub removeuploadedurl {
 5166:     my ($url)=@_;	
 5167:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);    
 5168:     return &removeuserfile($uname,$udom,$fname);
 5169: }
 5170: 
 5171: sub removeuserfile {
 5172:     my ($docuname,$docudom,$fname)=@_;
 5173:     my $home=&homeserver($docuname,$docudom);    
 5174:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
 5175:     if ($result eq 'ok') {	
 5176:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
 5177:             my $metafile = $fname.'.meta';
 5178:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
 5179: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
 5180:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];	   
 5181:             my $sqlresult = 
 5182:                 &update_portfolio_table($docuname,$docudom,$file,
 5183:                                         'portfolio_metadata',$group,
 5184:                                         'delete');
 5185:         }
 5186:     }
 5187:     return $result;
 5188: }
 5189: 
 5190: sub mkdiruserfile {
 5191:     my ($docuname,$docudom,$dir)=@_;
 5192:     my $home=&homeserver($docuname,$docudom);
 5193:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
 5194: }
 5195: 
 5196: sub renameuserfile {
 5197:     my ($docuname,$docudom,$old,$new)=@_;
 5198:     my $home=&homeserver($docuname,$docudom);
 5199:     my $result = &reply("renameuserfile:$docudom:$docuname:".
 5200:                         &escape("$old").':'.&escape("$new"),$home);
 5201:     if ($result eq 'ok') {
 5202:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
 5203:             my $oldmeta = $old.'.meta';
 5204:             my $newmeta = $new.'.meta';
 5205:             my $metaresult = 
 5206:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
 5207: 	    my $url = "/uploaded/$docudom/$docuname/$old";
 5208:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
 5209:             my $sqlresult = 
 5210:                 &update_portfolio_table($docuname,$docudom,$file,
 5211:                                         'portfolio_metadata',$group,
 5212:                                         'delete');
 5213:         }
 5214:     }
 5215:     return $result;
 5216: }
 5217: 
 5218: # ------------------------------------------------------------------------- Log
 5219: 
 5220: sub log {
 5221:     my ($dom,$nam,$hom,$what)=@_;
 5222:     return critical("log:$dom:$nam:$what",$hom);
 5223: }
 5224: 
 5225: # ------------------------------------------------------------------ Course Log
 5226: #
 5227: # This routine flushes several buffers of non-mission-critical nature
 5228: #
 5229: 
 5230: sub flushcourselogs {
 5231:     &logthis('Flushing log buffers');
 5232: #
 5233: # course logs
 5234: # This is a log of all transactions in a course, which can be used
 5235: # for data mining purposes
 5236: #
 5237: # It also collects the courseid database, which lists last transaction
 5238: # times and course titles for all courseids
 5239: #
 5240:     my %courseidbuffer=();
 5241:     foreach my $crsid (keys(%courselogs)) {
 5242:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
 5243: 		          &escape($courselogs{$crsid}),
 5244: 		          $coursehombuf{$crsid}) eq 'ok') {
 5245: 	    delete $courselogs{$crsid};
 5246:         } else {
 5247:             &logthis('Failed to flush log buffer for '.$crsid);
 5248:             if (length($courselogs{$crsid})>40000) {
 5249:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
 5250:                         " exceeded maximum size, deleting.</font>");
 5251:                delete $courselogs{$crsid};
 5252:             }
 5253:         }
 5254:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
 5255:             'description' => $coursedescrbuf{$crsid},
 5256:             'inst_code'    => $courseinstcodebuf{$crsid},
 5257:             'type'        => $coursetypebuf{$crsid},
 5258:             'owner'       => $courseownerbuf{$crsid},
 5259:         };
 5260:     }
 5261: #
 5262: # Write course id database (reverse lookup) to homeserver of courses 
 5263: # Is used in pickcourse
 5264: #
 5265:     foreach my $crs_home (keys(%courseidbuffer)) {
 5266:         my $response = &courseidput(&host_domain($crs_home),
 5267:                                     $courseidbuffer{$crs_home},
 5268:                                     $crs_home,'timeonly');
 5269:     }
 5270: #
 5271: # File accesses
 5272: # Writes to the dynamic metadata of resources to get hit counts, etc.
 5273: #
 5274:     foreach my $entry (keys(%accesshash)) {
 5275:         if ($entry =~ /___count$/) {
 5276:             my ($dom,$name);
 5277:             ($dom,$name,undef)=
 5278: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
 5279:             if (! defined($dom) || $dom eq '' || 
 5280:                 ! defined($name) || $name eq '') {
 5281:                 my $cid = $env{'request.course.id'};
 5282: #
 5283: # FIXME 11/29/2021
 5284: # Typo in rev. 1.458 (2003/12/09)??
 5285: # These should likely by $env{'course.'.$cid.'.domain'} and $env{'course.'.$cid.'.num'}
 5286: #
 5287: # While these remain as $env{'request.'.$cid.'.domain'} and $env{'request.'.$cid.'.num'}
 5288: # $dom and $name will always be null, so the &inc() call will default to storing this data
 5289: # in a nohist_accesscount.db file for the user rather than the course.
 5290: #
 5291: # That said there is a lot of noise in the data being stored.
 5292: # So counts for prtspool/  and adm/ etc. are recorded.
 5293: #
 5294: # A review of which items ending '___count' are written to %accesshash should likely be 
 5295: # made before deciding whether to set these to 'course.' instead of 'request.'
 5296: #
 5297: # Under the current scheme each user receives a nohist_accesscount.db file listing 
 5298: # accesses for things which are not published resources, regardless of course, and
 5299: # there is not a nohist_accesscount.db file in a course, which might log accesses from
 5300: # anyone in the course for things which are not published resources.
 5301: #
 5302: # For an author, nohist_accesscount.db ends up having records for other items
 5303: # mixed up with the legitimate access counts for the author's published resources.
 5304: #
 5305:                 $dom  = $env{'request.'.$cid.'.domain'};
 5306:                 $name = $env{'request.'.$cid.'.num'};
 5307:             }
 5308:             my $value = $accesshash{$entry};
 5309:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
 5310:             my %temphash=($url => $value);
 5311:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
 5312:             if ($result eq 'ok') {
 5313:                 delete $accesshash{$entry};
 5314:             }
 5315:         } else {
 5316:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
 5317:             if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
 5318:             my %temphash=($entry => $accesshash{$entry});
 5319:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
 5320:                 delete $accesshash{$entry};
 5321:             }
 5322:         }
 5323:     }
 5324: #
 5325: # Roles
 5326: # Reverse lookup of user roles for course faculty/staff and co-authorship
 5327: #
 5328:     foreach my $entry (keys(%userrolehash)) {
 5329:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
 5330: 	    split(/\:/,$entry);
 5331:         if (&put('nohist_userroles',
 5332:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
 5333:                 $rudom,$runame) eq 'ok') {
 5334: 	    delete $userrolehash{$entry};
 5335:         }
 5336:     }
 5337: #
 5338: # Reverse lookup of domain roles (dc, ad, li, sc, dh, da, au)
 5339: #
 5340:     my %domrolebuffer = ();
 5341:     foreach my $entry (keys(%domainrolehash)) {
 5342:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
 5343:         if ($domrolebuffer{$rudom}) {
 5344:             $domrolebuffer{$rudom}.='&'.&escape($entry).
 5345:                       '='.&escape($domainrolehash{$entry});
 5346:         } else {
 5347:             $domrolebuffer{$rudom}.=&escape($entry).
 5348:                       '='.&escape($domainrolehash{$entry});
 5349:         }
 5350:         delete $domainrolehash{$entry};
 5351:     }
 5352:     foreach my $dom (keys(%domrolebuffer)) {
 5353: 	my %servers;
 5354: 	if (defined(&domain($dom,'primary'))) {
 5355: 	    my $primary=&domain($dom,'primary');
 5356: 	    my $hostname=&hostname($primary);
 5357: 	    $servers{$primary} = $hostname;
 5358: 	} else { 
 5359: 	    %servers = &get_servers($dom,'library');
 5360: 	}
 5361: 	foreach my $tryserver (keys(%servers)) {
 5362: 	    if (&reply('domroleput:'.$dom.':'.
 5363: 		       $domrolebuffer{$dom},$tryserver) eq 'ok') {
 5364: 		last;
 5365: 	    } else {  
 5366: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
 5367: 	    }
 5368:         }
 5369:     }
 5370:     $dumpcount++;
 5371: }
 5372: 
 5373: sub courselog {
 5374:     my $what=shift;
 5375:     $what=time.':'.$what;
 5376:     unless ($env{'request.course.id'}) { return ''; }
 5377:     $coursedombuf{$env{'request.course.id'}}=
 5378:        $env{'course.'.$env{'request.course.id'}.'.domain'};
 5379:     $coursenumbuf{$env{'request.course.id'}}=
 5380:        $env{'course.'.$env{'request.course.id'}.'.num'};
 5381:     $coursehombuf{$env{'request.course.id'}}=
 5382:        $env{'course.'.$env{'request.course.id'}.'.home'};
 5383:     $coursedescrbuf{$env{'request.course.id'}}=
 5384:        $env{'course.'.$env{'request.course.id'}.'.description'};
 5385:     $courseinstcodebuf{$env{'request.course.id'}}=
 5386:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
 5387:     $courseownerbuf{$env{'request.course.id'}}=
 5388:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
 5389:     $coursetypebuf{$env{'request.course.id'}}=
 5390:        $env{'course.'.$env{'request.course.id'}.'.type'};
 5391:     if (defined $courselogs{$env{'request.course.id'}}) {
 5392: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
 5393:     } else {
 5394: 	$courselogs{$env{'request.course.id'}}.=$what;
 5395:     }
 5396:     if (length($courselogs{$env{'request.course.id'}})>4048) {
 5397: 	&flushcourselogs();
 5398:     }
 5399: }
 5400: 
 5401: sub courseacclog {
 5402:     my $fnsymb=shift;
 5403:     unless ($env{'request.course.id'}) { return ''; }
 5404:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
 5405:     if ($fnsymb=~/$LONCAPA::assess_re/) {
 5406:         $what.=':POST';
 5407:         # FIXME: Probably ought to escape things....
 5408: 	foreach my $key (keys(%env)) {
 5409:             if ($key=~/^form\.(.*)/) {
 5410:                 my $formitem = $1;
 5411:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
 5412:                     $what.=':'.$formitem.'='.$env{$key};
 5413:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
 5414:                     if ($formitem eq 'proctorpassword') {
 5415:                         $what.=':'.$formitem.'=' . '*' x length($env{$key});
 5416:                     } else {
 5417:                         $what.=':'.$formitem.'='.$env{$key};
 5418:                     }
 5419:                 }
 5420:             }
 5421:         }
 5422:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
 5423:         # FIXME: We should not be depending on a form parameter that someone
 5424:         # editing lonsearchcat.pm might change in the future.
 5425:         if ($env{'form.phase'} eq 'course_search') {
 5426:             $what.= ':POST';
 5427:             # FIXME: Probably ought to escape things....
 5428:             foreach my $element ('courseexp','crsfulltext','crsrelated',
 5429:                                  'crsdiscuss') {
 5430:                 $what.=':'.$element.'='.$env{'form.'.$element};
 5431:             }
 5432:         }
 5433:     }
 5434:     &courselog($what);
 5435: }
 5436: 
 5437: sub countacc {
 5438:     my $url=&declutter(shift);
 5439:     return if (! defined($url) || $url eq '');
 5440:     unless ($env{'request.course.id'}) { return ''; }
 5441: #
 5442: # Mark that this url was used in this course
 5443: #
 5444:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
 5445: #
 5446: # Increase the access count for this resource in this child process
 5447: #
 5448:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
 5449:     $accesshash{$key}++;
 5450: }
 5451: 
 5452: sub linklog {
 5453:     my ($from,$to)=@_;
 5454:     $from=&declutter($from);
 5455:     $to=&declutter($to);
 5456:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
 5457:     $accesshash{$to.'___'.$from.'___goto'}=1;
 5458: }
 5459: 
 5460: sub statslog {
 5461:     my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
 5462:     if ($users<2) { return; }
 5463:     my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
 5464:             'course'       => $env{'request.course.id'},
 5465:             'sections'     => '"all"',
 5466:             'num_students' => $users,
 5467:             'part'         => $part,
 5468:             'symb'         => $symb,
 5469:             'mean_tries'   => $av_attempts,
 5470:             'deg_of_diff'  => $degdiff});
 5471:     foreach my $key (keys(%dynstore)) {
 5472:         $accesshash{$key}=$dynstore{$key};
 5473:     }
 5474: }
 5475:   
 5476: sub userrolelog {
 5477:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
 5478:     if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
 5479:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 5480:        $userrolehash
 5481:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 5482:                     =$tend.':'.$tstart;
 5483:     }
 5484:     if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
 5485:        $userrolehash
 5486:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
 5487:                     =$tend.':'.$tstart;
 5488:     }
 5489:     if ($trole =~ /^(dc|ad|li|au|dg|sc|dh|da)/ ) {
 5490:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 5491:        $domainrolehash
 5492:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 5493:                     = $tend.':'.$tstart;
 5494:     }
 5495: }
 5496: 
 5497: sub courserolelog {
 5498:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,
 5499:         $context,$othdomby,$requester)=@_;
 5500:     if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
 5501:         my $cdom = $1;
 5502:         my $cnum = $2;
 5503:         my $sec = $3;
 5504:         my $namespace = 'rolelog';
 5505:         my %storehash = (
 5506:                            role    => $trole,
 5507:                            start   => $tstart,
 5508:                            end     => $tend,
 5509:                            selfenroll => $selfenroll,
 5510:                            context    => $context,
 5511:                         );
 5512:         if ($othdomby) {
 5513:             if ($othdomby eq 'othdombydc') {
 5514:                 $storehash{'approval'} = 'domain';
 5515:             } elsif ($othdomby eq 'othdombyuser') {
 5516:                 $storehash{'approval'} = 'user'; 
 5517:             }
 5518:             if ($requester ne '') {
 5519:                 $storehash{'requester'} = $requester;
 5520:             }
 5521:         }
 5522:         if ($trole eq 'gr') {
 5523:             $namespace = 'groupslog';
 5524:             $storehash{'group'} = $sec;
 5525:         } else {
 5526:             $storehash{'section'} = $sec;
 5527:             my ($curruserdomstr,$newuserdomstr);
 5528:             if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.userdomains'})) {
 5529:                 $curruserdomstr = $env{'course.'.$env{'request.course.id'}.'.internal.userdomains'};
 5530:             } else {
 5531:                 my %courseinfo = &coursedescription($cdom.'/'.$cnum);
 5532:                 $curruserdomstr = $courseinfo{'internal.userdomains'};
 5533:             }
 5534:             if ($curruserdomstr ne '') {
 5535:                 my @udoms = split(/,/,$curruserdomstr);
 5536:                 unless (grep(/^\Q$domain\E/,@udoms)) {
 5537:                     push(@udoms,$domain);
 5538:                     $newuserdomstr = join(',',sort(@udoms));
 5539:                 }
 5540:             } else {
 5541:                 $newuserdomstr = $domain;
 5542:             }
 5543:             if ($newuserdomstr ne '') {
 5544:                 my $putresult = &put('environment',{ 'internal.userdomains' => $newuserdomstr },
 5545:                                      $cdom,$cnum);
 5546:                 if ($putresult eq 'ok') {
 5547:                     unless (($selfenroll) || ($context eq 'selfenroll')) { 
 5548:                         if (($context eq 'createcourse') || ($context eq 'requestcourses') ||
 5549:                             ($context eq 'automated') || ($context eq 'domain')) {
 5550:                             $env{'course.'.$cdom.'_'.$cnum.'.internal.userdomains'} = $newuserdomstr;
 5551:                         } elsif ($env{'request.course.id'} eq $cdom.'_'.$cnum) {
 5552:                             &appenv({'course.'.$cdom.'_'.$cnum.'.internal.userdomains' => $newuserdomstr});
 5553:                         }
 5554:                     }
 5555:                 }
 5556:             }
 5557:         }
 5558:         &write_log('course',$namespace,\%storehash,$delflag,$username,
 5559:                    $domain,$cnum,$cdom);
 5560:         if (($trole ne 'st') || ($sec ne '')) {
 5561:             &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
 5562:         }
 5563:     }
 5564:     return;
 5565: }
 5566: 
 5567: sub domainrolelog {
 5568:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,
 5569:         $context,$othdomby,$requester)=@_;
 5570:     if ($area =~ m{^/($match_domain)/$}) {
 5571:         my $cdom = $1;
 5572:         my $domconfiguser = &get_domainconfiguser($cdom);
 5573:         my $namespace = 'rolelog';
 5574:         my %storehash = (
 5575:                            role    => $trole,
 5576:                            start   => $tstart,
 5577:                            end     => $tend,
 5578:                            context => $context,
 5579:                         );
 5580:         if ($othdomby) {
 5581:             if ($othdomby eq 'othdombydc') {
 5582:                 $storehash{'approval'} = 'domain';
 5583:             } elsif ($othdomby eq 'othdombyuser') {
 5584:                 $storehash{'approval'} = 'user';
 5585:             }
 5586:             if ($requester ne '') {
 5587:                 $storehash{'requester'} = $requester;
 5588:             }
 5589:         }
 5590:         &write_log('domain',$namespace,\%storehash,$delflag,$username,
 5591:                    $domain,$domconfiguser,$cdom);
 5592:     }
 5593:     return;
 5594: 
 5595: }
 5596: 
 5597: sub coauthorrolelog {
 5598:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,
 5599:         $context,$othdomby,$requester)=@_;
 5600:     if ($area =~ m{^/($match_domain)/($match_username)$}) {
 5601:         my $audom = $1;
 5602:         my $auname = $2;
 5603:         my $namespace = 'rolelog';
 5604:         my %storehash = (
 5605:                            role    => $trole,
 5606:                            start   => $tstart,
 5607:                            end     => $tend,
 5608:                            context => $context,
 5609:                         );
 5610:         if ($othdomby) {
 5611:             if ($othdomby eq 'othdombydc') {
 5612:                 $storehash{'approval'} = 'domain';
 5613:             } elsif ($othdomby eq 'othdombyuser') {
 5614:                 $storehash{'approval'} = 'user';
 5615:             }
 5616:             if ($requester ne '') {
 5617:                 $storehash{'requester'} = $requester;
 5618:             }
 5619:         }
 5620:         &write_log('author',$namespace,\%storehash,$delflag,$username,
 5621:                    $domain,$auname,$audom);
 5622:     }
 5623:     return;
 5624: }
 5625: 
 5626: sub get_course_adv_roles {
 5627:     my ($cid,$codes) = @_;
 5628:     $cid=$env{'request.course.id'} unless (defined($cid));
 5629:     my %coursehash=&coursedescription($cid);
 5630:     my $crstype = &Apache::loncommon::course_type($cid);
 5631:     my %nothide=();
 5632:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 5633:         if ($user !~ /:/) {
 5634: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
 5635:         } else {
 5636:             $nothide{$user}=1;
 5637:         }
 5638:     }
 5639:     my @possdoms = ($coursehash{'domain'});
 5640:     if ($coursehash{'checkforpriv'}) {
 5641:         push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
 5642:     }
 5643:     my %returnhash=();
 5644:     my %dumphash=
 5645:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
 5646:     my $now=time;
 5647:     my %privileged;
 5648:     foreach my $entry (keys(%dumphash)) {
 5649: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
 5650:         if (($tstart) && ($tstart<0)) { next; }
 5651:         if (($tend) && ($tend<$now)) { next; }
 5652:         if (($tstart) && ($now<$tstart)) { next; }
 5653:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
 5654: 	if ($username eq '' || $domain eq '') { next; }
 5655:         if ((&privileged($username,$domain,\@possdoms)) &&
 5656:             (!$nothide{$username.':'.$domain})) { next; }
 5657: 	if ($role eq 'cr') { next; }
 5658:         if ($codes) {
 5659:             if ($section) { $role .= ':'.$section; }
 5660:             if ($returnhash{$role}) {
 5661:                 $returnhash{$role}.=','.$username.':'.$domain;
 5662:             } else {
 5663:                 $returnhash{$role}=$username.':'.$domain;
 5664:             }
 5665:         } else {
 5666:             my $key=&plaintext($role,$crstype);
 5667:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
 5668:             if ($returnhash{$key}) {
 5669: 	        $returnhash{$key}.=','.$username.':'.$domain;
 5670:             } else {
 5671:                 $returnhash{$key}=$username.':'.$domain;
 5672:             }
 5673:         }
 5674:     }
 5675:     return %returnhash;
 5676: }
 5677: 
 5678: sub get_my_roles {
 5679:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
 5680:     unless (defined($uname)) { $uname=$env{'user.name'}; }
 5681:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
 5682:     my (%dumphash,%nothide);
 5683:     if ($context eq 'userroles') {
 5684:         %dumphash = &dump('roles',$udom,$uname);
 5685:     } else {
 5686:         %dumphash = &dump('nohist_userroles',$udom,$uname);
 5687:         if ($hidepriv) {
 5688:             my %coursehash=&coursedescription($udom.'_'.$uname);
 5689:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 5690:                 if ($user !~ /:/) {
 5691:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
 5692:                 } else {
 5693:                     $nothide{$user} = 1;
 5694:                 }
 5695:             }
 5696:         }
 5697:     }
 5698:     my %returnhash=();
 5699:     my $now=time;
 5700:     my %privileged;
 5701:     foreach my $entry (keys(%dumphash)) {
 5702:         my ($role,$tend,$tstart);
 5703:         if ($context eq 'userroles') {
 5704:             next if ($entry =~ /^rolesdef/);
 5705: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
 5706:         } else {
 5707:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
 5708:         }
 5709:         if (($tstart) && ($tstart<0)) { next; }
 5710:         my $status = 'active';
 5711:         if (($tend) && ($tend<=$now)) {
 5712:             $status = 'previous';
 5713:         } 
 5714:         if (($tstart) && ($now<$tstart)) {
 5715:             $status = 'future';
 5716:         }
 5717:         if (ref($types) eq 'ARRAY') {
 5718:             if (!grep(/^\Q$status\E$/,@{$types})) {
 5719:                 next;
 5720:             } 
 5721:         } else {
 5722:             if ($status ne 'active') {
 5723:                 next;
 5724:             }
 5725:         }
 5726:         my ($rolecode,$username,$domain,$section,$area);
 5727:         if ($context eq 'userroles') {
 5728:             ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
 5729:             (undef,$domain,$username,$section) = split(/\//,$area);
 5730:         } else {
 5731:             ($role,$username,$domain,$section) = split(/\:/,$entry);
 5732:         }
 5733:         if (ref($roledoms) eq 'ARRAY') {
 5734:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
 5735:                 next;
 5736:             }
 5737:         }
 5738:         if (ref($roles) eq 'ARRAY') {
 5739:             if (!grep(/^\Q$role\E$/,@{$roles})) {
 5740:                 if ($role =~ /^cr\//) {
 5741:                     if (!grep(/^cr$/,@{$roles})) {
 5742:                         next;
 5743:                     }
 5744:                 } elsif ($role =~ /^gr\//) {
 5745:                     if (!grep(/^gr$/,@{$roles})) {
 5746:                         next;
 5747:                     }
 5748:                 } else {
 5749:                     next;
 5750:                 }
 5751:             }
 5752:         }
 5753:         if ($hidepriv) {
 5754:             my @privroles = ('dc','su');
 5755:             if ($context eq 'userroles') {
 5756:                 next if (grep(/^\Q$role\E$/,@privroles));
 5757:             } else {
 5758:                 my $possdoms = [$domain];
 5759:                 if (ref($roledoms) eq 'ARRAY') {
 5760:                    push(@{$possdoms},@{$roledoms}); 
 5761:                 }
 5762:                 if (&privileged($username,$domain,$possdoms,\@privroles)) {
 5763:                     if (!$nothide{$username.':'.$domain}) {
 5764:                         next;
 5765:                     }
 5766:                 }
 5767:             }
 5768:         }
 5769:         if ($withsec) {
 5770:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
 5771:                 $tstart.':'.$tend;
 5772:         } else {
 5773:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
 5774:         }
 5775:     }
 5776:     return %returnhash;
 5777: }
 5778: 
 5779: sub get_all_adhocroles {
 5780:     my ($dom) = @_;
 5781:     my @roles_by_num = ();
 5782:     my %domdefaults = &get_domain_defaults($dom);
 5783:     my (%description,%access_in_dom,%access_info);
 5784:     if (ref($domdefaults{'adhocroles'}) eq 'HASH') {
 5785:         my $count = 0;
 5786:         my %domcurrent = %{$domdefaults{'adhocroles'}};
 5787:         my %ordered;
 5788:         foreach my $role (sort(keys(%domcurrent))) {
 5789:             my ($order,$desc,$access_in_dom);
 5790:             if (ref($domcurrent{$role}) eq 'HASH') {
 5791:                 $order = $domcurrent{$role}{'order'};
 5792:                 $desc = $domcurrent{$role}{'desc'};
 5793:                 $access_in_dom{$role} = $domcurrent{$role}{'access'};
 5794:                 $access_info{$role} = $domcurrent{$role}{$access_in_dom{$role}};
 5795:             }
 5796:             if ($order eq '') {
 5797:                 $order = $count;
 5798:             }
 5799:             $ordered{$order} = $role;
 5800:             if ($desc ne '') {
 5801:                 $description{$role} = $desc;
 5802:             } else {
 5803:                 $description{$role}= $role;
 5804:             }
 5805:             $count++;
 5806:         }
 5807:         foreach my $item (sort {$a <=> $b } (keys(%ordered))) {
 5808:             push(@roles_by_num,$ordered{$item});
 5809:         }
 5810:     }
 5811:     return (\@roles_by_num,\%description,\%access_in_dom,\%access_info);
 5812: }
 5813: 
 5814: sub get_my_adhocroles {
 5815:     my ($cid,$checkreg) = @_;
 5816:     my ($cdom,$cnum,%info,@possroles,$description,$roles_by_num);
 5817:     if ($env{'request.course.id'} eq $cid) {
 5818:         $cdom = $env{'course.'.$cid.'.domain'};
 5819:         $cnum = $env{'course.'.$cid.'.num'};
 5820:         $info{'internal.coursecode'} = $env{'course.'.$cid.'.internal.coursecode'};
 5821:     } elsif ($cid =~ /^($match_domain)_($match_courseid)$/) {
 5822:         $cdom = $1;
 5823:         $cnum = $2;
 5824:         %info = &get('environment',['internal.coursecode'],
 5825:                      $cdom,$cnum);
 5826:     }
 5827:     if (($info{'internal.coursecode'} ne '') && ($checkreg)) {
 5828:         my $user = $env{'user.name'}.':'.$env{'user.domain'};
 5829:         my %rosterhash = &get('classlist',[$user],$cdom,$cnum);
 5830:         if ($rosterhash{$user} ne '') {
 5831:             my $type = (split(/:/,$rosterhash{$user}))[5];
 5832:             return ([],{}) if ($type eq 'auto');
 5833:         }
 5834:     }
 5835:     if (($cdom ne '') && ($cnum ne ''))  {
 5836:         if (($env{"user.role.dh./$cdom/"}) || ($env{"user.role.da./$cdom/"})) {
 5837:             my $then=$env{'user.login.time'};
 5838:             my $update=$env{'user.update.time'};
 5839:             if (!$update) {
 5840:                 $update = $then;
 5841:             }
 5842:             my @liveroles;
 5843:             foreach my $role ('dh','da') {
 5844:                 if ($env{"user.role.$role./$cdom/"}) {
 5845:                     my ($tstart,$tend)=split(/\./,$env{"user.role.$role./$cdom/"});
 5846:                     my $limit = $update;
 5847:                     if ($env{'request.role'} eq "$role./$cdom/") {
 5848:                         $limit = $then;
 5849:                     }
 5850:                     my $activerole = 1;
 5851:                     if ($tstart && $tstart>$limit) { $activerole = 0; }
 5852:                     if ($tend   && $tend  <$limit) { $activerole = 0; }
 5853:                     if ($activerole) {
 5854:                         push(@liveroles,$role);
 5855:                     }
 5856:                 }
 5857:             }
 5858:             if (@liveroles) {
 5859:                 if (&homeserver($cnum,$cdom) ne 'no_host') {
 5860:                     my ($accessref,$accessinfo,%access_in_dom);
 5861:                     ($roles_by_num,$description,$accessref,$accessinfo) = &get_all_adhocroles($cdom);
 5862:                     if (ref($roles_by_num) eq 'ARRAY') {
 5863:                         if (@{$roles_by_num}) {
 5864:                             my %settings;
 5865:                             if ($env{'request.course.id'} eq $cid) {
 5866:                                 foreach my $envkey (keys(%env)) {
 5867:                                     if ($envkey =~ /^\Qcourse.$cid.\E(internal\.adhoc.+)$/) {
 5868:                                         $settings{$1} = $env{$envkey};
 5869:                                     }
 5870:                                 }
 5871:                             } else {
 5872:                                 %settings = &dump('environment',$cdom,$cnum,'internal\.adhoc');
 5873:                             }
 5874:                             my %setincrs;
 5875:                             if ($settings{'internal.adhocaccess'}) {
 5876:                                 map { $setincrs{$_} = 1; } split(/,/,$settings{'internal.adhocaccess'});
 5877:                             }
 5878:                             my @statuses;
 5879:                             if ($env{'environment.inststatus'}) {
 5880:                                 @statuses = split(/,/,$env{'environment.inststatus'});
 5881:                             }
 5882:                             my $user = $env{'user.name'}.':'.$env{'user.domain'};
 5883:                             if (ref($accessref) eq 'HASH') {
 5884:                                 %access_in_dom = %{$accessref};
 5885:                             }
 5886:                             foreach my $role (@{$roles_by_num}) {
 5887:                                 my ($curraccess,@okstatus,@personnel);
 5888:                                 if ($setincrs{$role}) {
 5889:                                     ($curraccess,my $rest) = split(/=/,$settings{'internal.adhoc.'.$role});
 5890:                                     if ($curraccess eq 'status') {
 5891:                                         @okstatus = split(/\&/,$rest);
 5892:                                     } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
 5893:                                         @personnel = split(/\&/,$rest);
 5894:                                     }
 5895:                                 } else {
 5896:                                     $curraccess = $access_in_dom{$role};
 5897:                                     if (ref($accessinfo) eq 'HASH') {
 5898:                                         if ($curraccess eq 'status') {
 5899:                                             if (ref($accessinfo->{$role}) eq 'ARRAY') {
 5900:                                                 @okstatus = @{$accessinfo->{$role}};
 5901:                                             }
 5902:                                         } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
 5903:                                             if (ref($accessinfo->{$role}) eq 'ARRAY') {
 5904:                                                 @personnel = @{$accessinfo->{$role}};
 5905:                                             }
 5906:                                         }
 5907:                                     }
 5908:                                 }
 5909:                                 if ($curraccess eq 'none') {
 5910:                                     next;
 5911:                                 } elsif ($curraccess eq 'all') {
 5912:                                     push(@possroles,$role);
 5913:                                 } elsif ($curraccess eq 'dh') {
 5914:                                     if (grep(/^dh$/,@liveroles)) {
 5915:                                         push(@possroles,$role);
 5916:                                     } else {
 5917:                                         next;
 5918:                                     }
 5919:                                 } elsif ($curraccess eq 'da') {
 5920:                                     if (grep(/^da$/,@liveroles)) {
 5921:                                         push(@possroles,$role);
 5922:                                     } else {
 5923:                                         next;
 5924:                                     }
 5925:                                 } elsif ($curraccess eq 'status') {
 5926:                                     if (@okstatus) {
 5927:                                         if (!@statuses) {
 5928:                                             if (grep(/^default$/,@okstatus)) {
 5929:                                                 push(@possroles,$role);
 5930:                                             }
 5931:                                         } else {
 5932:                                             foreach my $status (@okstatus) {
 5933:                                                 if (grep(/^\Q$status\E$/,@statuses)) {
 5934:                                                     push(@possroles,$role);
 5935:                                                     last;
 5936:                                                 }
 5937:                                             }
 5938:                                         }
 5939:                                     }
 5940:                                 } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
 5941:                                     if (grep(/^\Q$user\E$/,@personnel)) {
 5942:                                         if ($curraccess eq 'exc') {
 5943:                                             push(@possroles,$role);
 5944:                                         }
 5945:                                     } elsif ($curraccess eq 'inc') {
 5946:                                         push(@possroles,$role);
 5947:                                     }
 5948:                                 }
 5949:                             }
 5950:                         }
 5951:                     }
 5952:                 }
 5953:             }
 5954:         }
 5955:     }
 5956:     unless (ref($description) eq 'HASH') {
 5957:         if (ref($roles_by_num) eq 'ARRAY') {
 5958:             my %desc;
 5959:             map { $desc{$_} = $_; } (@{$roles_by_num});
 5960:             $description = \%desc;
 5961:         } else {
 5962:             $description = {};
 5963:         }
 5964:     }
 5965:     return (\@possroles,$description);
 5966: }
 5967: 
 5968: # ----------------------------------------------------- Frontpage Announcements
 5969: #
 5970: #
 5971: 
 5972: sub postannounce {
 5973:     my ($server,$text)=@_;
 5974:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
 5975:     unless ($text=~/\w/) { $text=''; }
 5976:     return &reply('setannounce:'.&escape($text),$server);
 5977: }
 5978: 
 5979: sub getannounce {
 5980: 
 5981:     if (open(my $fh,"<",$perlvar{'lonDocRoot'}.'/announcement.txt')) {
 5982: 	my $announcement='';
 5983: 	while (my $line = <$fh>) { $announcement .= $line; }
 5984: 	close($fh);
 5985: 	if ($announcement=~/\w/) { 
 5986: 	    return 
 5987:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
 5988:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
 5989: 	} else {
 5990: 	    return '';
 5991: 	}
 5992:     } else {
 5993: 	return '';
 5994:     }
 5995: }
 5996: 
 5997: # ---------------------------------------------------------- Course ID routines
 5998: # Deal with domain's nohist_courseid.db files
 5999: #
 6000: 
 6001: sub courseidput {
 6002:     my ($domain,$storehash,$coursehome,$caller) = @_;
 6003:     return unless (ref($storehash) eq 'HASH');
 6004:     my $outcome;
 6005:     if ($caller eq 'timeonly') {
 6006:         my $cids = '';
 6007:         foreach my $item (keys(%$storehash)) {
 6008:             $cids.=&escape($item).'&';
 6009:         }
 6010:         $cids=~s/\&$//;
 6011:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
 6012:                           $coursehome);       
 6013:     } else {
 6014:         my $items = '';
 6015:         foreach my $item (keys(%$storehash)) {
 6016:             $items.= &escape($item).'='.
 6017:                      &freeze_escape($$storehash{$item}).'&';
 6018:         }
 6019:         $items=~s/\&$//;
 6020:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
 6021:                           $coursehome);
 6022:     }
 6023:     if ($outcome eq 'unknown_cmd') {
 6024:         my $what;
 6025:         foreach my $cid (keys(%$storehash)) {
 6026:             $what .= &escape($cid).'=';
 6027:             foreach my $item ('description','inst_code','owner','type') {
 6028:                 $what .= &escape($storehash->{$cid}{$item}).':';
 6029:             }
 6030:             $what =~ s/\:$/&/;
 6031:         }
 6032:         $what =~ s/\&$//;  
 6033:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
 6034:     } else {
 6035:         return $outcome;
 6036:     }
 6037: }
 6038: 
 6039: sub courseiddump {
 6040:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
 6041:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
 6042:         $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
 6043:         $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner,
 6044:         $hasuniquecode,$reqcrsdom,$reqinstcode)=@_;
 6045:     my $as_hash = 1;
 6046:     my %returnhash;
 6047:     if (!$domfilter) { $domfilter=''; }
 6048:     my %libserv = &all_library();
 6049:     foreach my $tryserver (keys(%libserv)) {
 6050:         if ( (  $hostidflag == 1 
 6051: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
 6052: 	     || (!defined($hostidflag)) ) {
 6053: 
 6054: 	    if (($domfilter eq '') ||
 6055: 		(&host_domain($tryserver) eq $domfilter)) {
 6056:                 my $rep;
 6057:                 if (grep { $_ eq $tryserver } current_machine_ids()) {
 6058:                     $rep = LONCAPA::Lond::dump_course_id_handler(
 6059:                         join(":", (&host_domain($tryserver), $sincefilter, 
 6060:                                 &escape($descfilter), &escape($instcodefilter), 
 6061:                                 &escape($ownerfilter), &escape($coursefilter),
 6062:                                 &escape($typefilter), &escape($regexp_ok), 
 6063:                                 $as_hash, &escape($selfenrollonly), 
 6064:                                 &escape($catfilter), $showhidden, $caller, 
 6065:                                 &escape($cloner), &escape($cc_clone), $cloneonly, 
 6066:                                 &escape($createdbefore), &escape($createdafter), 
 6067:                                 &escape($creationcontext),$domcloner,$hasuniquecode,
 6068:                                 $reqcrsdom,&escape($reqinstcode))));
 6069:                 } else {
 6070:                     $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
 6071:                              $sincefilter.':'.&escape($descfilter).':'.
 6072:                              &escape($instcodefilter).':'.&escape($ownerfilter).
 6073:                              ':'.&escape($coursefilter).':'.&escape($typefilter).
 6074:                              ':'.&escape($regexp_ok).':'.$as_hash.':'.
 6075:                              &escape($selfenrollonly).':'.&escape($catfilter).':'.
 6076:                              $showhidden.':'.$caller.':'.&escape($cloner).':'.
 6077:                              &escape($cc_clone).':'.$cloneonly.':'.
 6078:                              &escape($createdbefore).':'.&escape($createdafter).':'.
 6079:                              &escape($creationcontext).':'.$domcloner.':'.$hasuniquecode.
 6080:                              ':'.$reqcrsdom.':'.&escape($reqinstcode),$tryserver);
 6081:                 }
 6082:                      
 6083:                 my @pairs=split(/\&/,$rep);
 6084:                 foreach my $item (@pairs) {
 6085:                     my ($key,$value)=split(/\=/,$item,2);
 6086:                     $key = &unescape($key);
 6087:                     next if ($key =~ /^error: 2 /);
 6088:                     my $result = &thaw_unescape($value);
 6089:                     if (ref($result) eq 'HASH') {
 6090:                         $returnhash{$key}=$result;
 6091:                     } else {
 6092:                         my @responses = split(/:/,$value);
 6093:                         my @items = ('description','inst_code','owner','type');
 6094:                         for (my $i=0; $i<@responses; $i++) {
 6095:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
 6096:                         }
 6097:                     }
 6098:                 }
 6099:             }
 6100:         }
 6101:     }
 6102:     return %returnhash;
 6103: }
 6104: 
 6105: sub courselastaccess {
 6106:     my ($cdom,$cnum,$hostidref) = @_;
 6107:     my %returnhash;
 6108:     if ($cdom && $cnum) {
 6109:         my $chome = &homeserver($cnum,$cdom);
 6110:         if ($chome ne 'no_host') {
 6111:             my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
 6112:             &extract_lastaccess(\%returnhash,$rep);
 6113:         }
 6114:     } else {
 6115:         if (!$cdom) { $cdom=''; }
 6116:         my %libserv = &all_library();
 6117:         foreach my $tryserver (keys(%libserv)) {
 6118:             if (ref($hostidref) eq 'ARRAY') {
 6119:                 next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
 6120:             } 
 6121:             if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
 6122:                 my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
 6123:                 &extract_lastaccess(\%returnhash,$rep);
 6124:             }
 6125:         }
 6126:     }
 6127:     return %returnhash;
 6128: }
 6129: 
 6130: sub extract_lastaccess {
 6131:     my ($returnhash,$rep) = @_;
 6132:     if (ref($returnhash) eq 'HASH') {
 6133:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' || 
 6134:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
 6135:                  $rep eq '') {
 6136:             my @pairs=split(/\&/,$rep);
 6137:             foreach my $item (@pairs) {
 6138:                 my ($key,$value)=split(/\=/,$item,2);
 6139:                 $key = &unescape($key);
 6140:                 next if ($key =~ /^error: 2 /);
 6141:                 $returnhash->{$key} = &thaw_unescape($value);
 6142:             }
 6143:         }
 6144:     }
 6145:     return;
 6146: }
 6147: 
 6148: # ---------------------------------------------------------- DC e-mail
 6149: 
 6150: sub dcmailput {
 6151:     my ($domain,$msgid,$message,$server)=@_;
 6152:     my $status = &critical(
 6153:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
 6154:        &escape($message),$server);
 6155:     return $status;
 6156: }
 6157: 
 6158: sub dcmaildump {
 6159:     my ($dom,$startdate,$enddate,$senders) = @_;
 6160:     my %returnhash=();
 6161: 
 6162:     if (defined(&domain($dom,'primary'))) {
 6163:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
 6164:                                                          &escape($enddate).':';
 6165: 	my @esc_senders=map { &escape($_)} @$senders;
 6166: 	$cmd.=&escape(join('&',@esc_senders));
 6167: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
 6168:             my ($key,$value) = split(/\=/,$line,2);
 6169:             if (($key) && ($value)) {
 6170:                 $returnhash{&unescape($key)} = &unescape($value);
 6171:             }
 6172:         }
 6173:     }
 6174:     return %returnhash;
 6175: }
 6176: # ---------------------------------------------------------- Domain roles
 6177: 
 6178: sub get_domain_roles {
 6179:     my ($dom,$roles,$startdate,$enddate)=@_;
 6180:     if ((!defined($startdate)) || ($startdate eq '')) {
 6181:         $startdate = '.';
 6182:     }
 6183:     if ((!defined($enddate)) || ($enddate eq '')) {
 6184:         $enddate = '.';
 6185:     }
 6186:     my $rolelist;
 6187:     if (ref($roles) eq 'ARRAY') {
 6188:         $rolelist = join('&',@{$roles});
 6189:     }
 6190:     my %personnel = ();
 6191: 
 6192:     my %servers = &get_servers($dom,'library');
 6193:     foreach my $tryserver (keys(%servers)) {
 6194: 	%{$personnel{$tryserver}}=();
 6195: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
 6196: 					    &escape($startdate).':'.
 6197: 					    &escape($enddate).':'.
 6198: 					    &escape($rolelist), $tryserver))) {
 6199: 	    my ($key,$value) = split(/\=/,$line,2);
 6200: 	    if (($key) && ($value)) {
 6201: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
 6202: 	    }
 6203: 	}
 6204:     }
 6205:     return %personnel;
 6206: }
 6207: 
 6208: sub get_active_domroles {
 6209:     my ($dom,$roles) = @_;
 6210:     return () unless (ref($roles) eq 'ARRAY');
 6211:     my $now = time;
 6212:     my %dompersonnel = &get_domain_roles($dom,$roles,$now,$now);
 6213:     my %domroles;
 6214:     foreach my $server (keys(%dompersonnel)) {
 6215:         foreach my $user (sort(keys(%{$dompersonnel{$server}}))) {
 6216:             my ($trole,$uname,$udom,$runame,$rudom,$rsec) = split(/:/,$user);
 6217:             $domroles{$uname.':'.$udom} = $dompersonnel{$server}{$user};
 6218:         }
 6219:     }
 6220:     return %domroles;
 6221: }
 6222: 
 6223: # ----------------------------------------------------------- Interval timing 
 6224: 
 6225: {
 6226: # Caches needed for speedup of navmaps
 6227: # We don't want to cache this for very long at all (5 seconds at most)
 6228: # 
 6229: # The user for whom we cache
 6230: my $cachedkey='';
 6231: # The cached times for this user
 6232: my %cachedtimes=();
 6233: # When this was last done
 6234: my $cachedtime='';
 6235: 
 6236: sub load_all_first_access {
 6237:     my ($uname,$udom,$ignorecache)=@_;
 6238:     if (($cachedkey eq $uname.':'.$udom) &&
 6239:         (abs($cachedtime-time)<5) && (!$env{'form.markaccess'}) &&
 6240:         (!$ignorecache)) {
 6241:         return;
 6242:     }
 6243:     $cachedtime=time;
 6244:     $cachedkey=$uname.':'.$udom;
 6245:     %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
 6246: }
 6247: 
 6248: sub get_first_access {
 6249:     my ($type,$argsymb,$argmap,$ignorecache)=@_;
 6250:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 6251:     if ($argsymb) { $symb=$argsymb; }
 6252:     my ($map,$id,$res)=&decode_symb($symb);
 6253:     if ($argmap) { $map = $argmap; }
 6254:     if ($type eq 'course') {
 6255: 	$res='course';
 6256:     } elsif ($type eq 'map') {
 6257: 	$res=&symbread($map);
 6258:     } else {
 6259: 	$res=$symb;
 6260:     }
 6261:     &load_all_first_access($uname,$udom,$ignorecache);
 6262:     return $cachedtimes{"$courseid\0$res"};
 6263: }
 6264: 
 6265: sub set_first_access {
 6266:     my ($type,$interval)=@_;
 6267:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 6268:     my ($map,$id,$res)=&decode_symb($symb);
 6269:     if ($type eq 'course') {
 6270: 	$res='course';
 6271:     } elsif ($type eq 'map') {
 6272: 	$res=&symbread($map);
 6273:     } else {
 6274: 	$res=$symb;
 6275:     }
 6276:     $cachedkey='';
 6277:     my $firstaccess=&get_first_access($type,$symb,$map);
 6278:     if ($firstaccess) {
 6279:         &logthis("First access time already set ($firstaccess) when attempting ".
 6280:                  "to set new value (type: $type, extent: $res) for $uname:$udom ".
 6281:                  "in $courseid");
 6282:         return 'already_set';
 6283:     } else {
 6284:         my $start = time;
 6285: 	my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
 6286:                           $udom,$uname);
 6287:         if ($putres eq 'ok') {
 6288:             &put('timerinterval',{"$courseid\0$res"=>$interval},
 6289:                  $udom,$uname); 
 6290:             &appenv(
 6291:                      {
 6292:                         'course.'.$courseid.'.firstaccess.'.$res   => $start,
 6293:                         'course.'.$courseid.'.timerinterval.'.$res => $interval,
 6294:                      }
 6295:                   );
 6296:             if (($cachedtime) && (abs($start-$cachedtime) < 5)) {
 6297:                 $cachedtimes{"$courseid\0$res"} = $start;
 6298:             }
 6299:         } elsif ($putres ne 'refused') {
 6300:             &logthis("Result: $putres when attempting to set first access time ".
 6301:                      "(type: $type, extent: $res) for $uname:$udom in $courseid");
 6302:         }
 6303:         return $putres;
 6304:     }
 6305:     return 'already_set';
 6306: }
 6307: }
 6308: 
 6309: # --------------------------------------------- Set Expire Date for Spreadsheet
 6310: 
 6311: sub expirespread {
 6312:     my ($uname,$udom,$stype,$usymb)=@_;
 6313:     my $cid=$env{'request.course.id'}; 
 6314:     if ($cid) {
 6315:        my $now=time;
 6316:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
 6317:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
 6318:                             $env{'course.'.$cid.'.num'}.
 6319: 	        	    ':nohist_expirationdates:'.
 6320:                             &escape($key).'='.$now,
 6321:                             $env{'course.'.$cid.'.home'})
 6322:     }
 6323:     return 'ok';
 6324: }
 6325: 
 6326: # ----------------------------------------------------- Devalidate Spreadsheets
 6327: 
 6328: sub devalidate {
 6329:     my ($symb,$uname,$udom)=@_;
 6330:     my $cid=$env{'request.course.id'}; 
 6331:     if ($cid) {
 6332:         # delete the stored spreadsheets for
 6333:         # - the student level sheet of this user in course's homespace
 6334:         # - the assessment level sheet for this resource 
 6335:         #   for this user in user's homespace
 6336: 	# - current conditional state info
 6337: 	my $key=$uname.':'.$udom.':';
 6338:         my $status=
 6339: 	    &del('nohist_calculatedsheets',
 6340: 		 [$key.'studentcalc:'],
 6341: 		 $env{'course.'.$cid.'.domain'},
 6342: 		 $env{'course.'.$cid.'.num'})
 6343: 		.' '.
 6344: 	    &del('nohist_calculatedsheets_'.$cid,
 6345: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
 6346:         unless ($status eq 'ok ok') {
 6347:            &logthis('Could not devalidate spreadsheet '.
 6348:                     $uname.' at '.$udom.' for '.
 6349: 		    $symb.': '.$status);
 6350:         }
 6351: 	&delenv('user.state.'.$cid);
 6352:     }
 6353: }
 6354: 
 6355: sub get_scalar {
 6356:     my ($string,$end) = @_;
 6357:     my $value;
 6358:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
 6359: 	$value = $1;
 6360:     } elsif ($$string =~ s/^([^&]*?)&//) {
 6361: 	$value = $1;
 6362:     }
 6363:     return &unescape($value);
 6364: }
 6365: 
 6366: sub array2str {
 6367:   my (@array) = @_;
 6368:   my $result=&arrayref2str(\@array);
 6369:   $result=~s/^__ARRAY_REF__//;
 6370:   $result=~s/__END_ARRAY_REF__$//;
 6371:   return $result;
 6372: }
 6373: 
 6374: sub arrayref2str {
 6375:   my ($arrayref) = @_;
 6376:   my $result='__ARRAY_REF__';
 6377:   foreach my $elem (@$arrayref) {
 6378:     if(ref($elem) eq 'ARRAY') {
 6379:       $result.=&arrayref2str($elem).'&';
 6380:     } elsif(ref($elem) eq 'HASH') {
 6381:       $result.=&hashref2str($elem).'&';
 6382:     } elsif(ref($elem)) {
 6383:       #print("Got a ref of ".(ref($elem))." skipping.");
 6384:     } else {
 6385:       $result.=&escape($elem).'&';
 6386:     }
 6387:   }
 6388:   $result=~s/\&$//;
 6389:   $result .= '__END_ARRAY_REF__';
 6390:   return $result;
 6391: }
 6392: 
 6393: sub hash2str {
 6394:   my (%hash) = @_;
 6395:   my $result=&hashref2str(\%hash);
 6396:   $result=~s/^__HASH_REF__//;
 6397:   $result=~s/__END_HASH_REF__$//;
 6398:   return $result;
 6399: }
 6400: 
 6401: sub hashref2str {
 6402:   my ($hashref)=@_;
 6403:   my $result='__HASH_REF__';
 6404:   foreach my $key (sort(keys(%$hashref))) {
 6405:     if (ref($key) eq 'ARRAY') {
 6406:       $result.=&arrayref2str($key).'=';
 6407:     } elsif (ref($key) eq 'HASH') {
 6408:       $result.=&hashref2str($key).'=';
 6409:     } elsif (ref($key)) {
 6410:       $result.='=';
 6411:       #print("Got a ref of ".(ref($key))." skipping.");
 6412:     } else {
 6413: 	if (defined($key)) {$result.=&escape($key).'=';} else { last; }
 6414:     }
 6415: 
 6416:     if(ref($hashref->{$key}) eq 'ARRAY') {
 6417:       $result.=&arrayref2str($hashref->{$key}).'&';
 6418:     } elsif(ref($hashref->{$key}) eq 'HASH') {
 6419:       $result.=&hashref2str($hashref->{$key}).'&';
 6420:     } elsif(ref($hashref->{$key})) {
 6421:        $result.='&';
 6422:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
 6423:     } else {
 6424:       $result.=&escape($hashref->{$key}).'&';
 6425:     }
 6426:   }
 6427:   $result=~s/\&$//;
 6428:   $result .= '__END_HASH_REF__';
 6429:   return $result;
 6430: }
 6431: 
 6432: sub str2hash {
 6433:     my ($string)=@_;
 6434:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
 6435:     return %$hash;
 6436: }
 6437: 
 6438: sub str2hashref {
 6439:   my ($string) = @_;
 6440: 
 6441:   my %hash;
 6442: 
 6443:   if($string !~ /^__HASH_REF__/) {
 6444:       if (! ($string eq '' || !defined($string))) {
 6445: 	  $hash{'error'}='Not hash reference';
 6446:       }
 6447:       return (\%hash, $string);
 6448:   }
 6449: 
 6450:   $string =~ s/^__HASH_REF__//;
 6451: 
 6452:   while($string !~ /^__END_HASH_REF__/) {
 6453:       #key
 6454:       my $key='';
 6455:       if($string =~ /^__HASH_REF__/) {
 6456:           ($key, $string)=&str2hashref($string);
 6457:           if(defined($key->{'error'})) {
 6458:               $hash{'error'}='Bad data';
 6459:               return (\%hash, $string);
 6460:           }
 6461:       } elsif($string =~ /^__ARRAY_REF__/) {
 6462:           ($key, $string)=&str2arrayref($string);
 6463:           if($key->[0] eq 'Array reference error') {
 6464:               $hash{'error'}='Bad data';
 6465:               return (\%hash, $string);
 6466:           }
 6467:       } else {
 6468:           $string =~ s/^(.*?)=//;
 6469: 	  $key=&unescape($1);
 6470:       }
 6471:       $string =~ s/^=//;
 6472: 
 6473:       #value
 6474:       my $value='';
 6475:       if($string =~ /^__HASH_REF__/) {
 6476:           ($value, $string)=&str2hashref($string);
 6477:           if(defined($value->{'error'})) {
 6478:               $hash{'error'}='Bad data';
 6479:               return (\%hash, $string);
 6480:           }
 6481:       } elsif($string =~ /^__ARRAY_REF__/) {
 6482:           ($value, $string)=&str2arrayref($string);
 6483:           if($value->[0] eq 'Array reference error') {
 6484:               $hash{'error'}='Bad data';
 6485:               return (\%hash, $string);
 6486:           }
 6487:       } else {
 6488: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
 6489:       }
 6490:       $string =~ s/^&//;
 6491: 
 6492:       $hash{$key}=$value;
 6493:   }
 6494: 
 6495:   $string =~ s/^__END_HASH_REF__//;
 6496: 
 6497:   return (\%hash, $string);
 6498: }
 6499: 
 6500: sub str2array {
 6501:     my ($string)=@_;
 6502:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
 6503:     return @$array;
 6504: }
 6505: 
 6506: sub str2arrayref {
 6507:   my ($string) = @_;
 6508:   my @array;
 6509: 
 6510:   if($string !~ /^__ARRAY_REF__/) {
 6511:       if (! ($string eq '' || !defined($string))) {
 6512: 	  $array[0]='Array reference error';
 6513:       }
 6514:       return (\@array, $string);
 6515:   }
 6516: 
 6517:   $string =~ s/^__ARRAY_REF__//;
 6518: 
 6519:   while($string !~ /^__END_ARRAY_REF__/) {
 6520:       my $value='';
 6521:       if($string =~ /^__HASH_REF__/) {
 6522:           ($value, $string)=&str2hashref($string);
 6523:           if(defined($value->{'error'})) {
 6524:               $array[0] ='Array reference error';
 6525:               return (\@array, $string);
 6526:           }
 6527:       } elsif($string =~ /^__ARRAY_REF__/) {
 6528:           ($value, $string)=&str2arrayref($string);
 6529:           if($value->[0] eq 'Array reference error') {
 6530:               $array[0] ='Array reference error';
 6531:               return (\@array, $string);
 6532:           }
 6533:       } else {
 6534: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
 6535:       }
 6536:       $string =~ s/^&//;
 6537: 
 6538:       push(@array, $value);
 6539:   }
 6540: 
 6541:   $string =~ s/^__END_ARRAY_REF__//;
 6542: 
 6543:   return (\@array, $string);
 6544: }
 6545: 
 6546: # -------------------------------------------------------------------Temp Store
 6547: 
 6548: sub tmpreset {
 6549:   my ($symb,$namespace,$domain,$stuname) = @_;
 6550:   if (!$symb) {
 6551:     $symb=&symbread();
 6552:     if (!$symb) { $symb= $env{'request.url'}; }
 6553:   }
 6554:   $symb=escape($symb);
 6555: 
 6556:   if (!$namespace) { $namespace=$env{'request.state'}; }
 6557:   $namespace=~s/\//\_/g;
 6558:   $namespace=~s/\W//g;
 6559: 
 6560:   if (!$domain) { $domain=$env{'user.domain'}; }
 6561:   if (!$stuname) { $stuname=$env{'user.name'}; }
 6562:   if ($domain eq 'public' && $stuname eq 'public') {
 6563:       $stuname=&get_requestor_ip();
 6564:   }
 6565:   my $path=LONCAPA::tempdir();
 6566:   my %hash;
 6567:   if (tie(%hash,'GDBM_File',
 6568: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 6569: 	  &GDBM_WRCREAT(),0640)) {
 6570:     foreach my $key (keys(%hash)) {
 6571:       if ($key=~ /:$symb/) {
 6572: 	delete($hash{$key});
 6573:       }
 6574:     }
 6575:   }
 6576: }
 6577: 
 6578: sub tmpstore {
 6579:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 6580: 
 6581:   if (!$symb) {
 6582:     $symb=&symbread();
 6583:     if (!$symb) { $symb= $env{'request.url'}; }
 6584:   }
 6585:   $symb=escape($symb);
 6586: 
 6587:   if (!$namespace) {
 6588:     # I don't think we would ever want to store this for a course.
 6589:     # it seems this will only be used if we don't have a course.
 6590:     #$namespace=$env{'request.course.id'};
 6591:     #if (!$namespace) {
 6592:       $namespace=$env{'request.state'};
 6593:     #}
 6594:   }
 6595:   $namespace=~s/\//\_/g;
 6596:   $namespace=~s/\W//g;
 6597:   if (!$domain) { $domain=$env{'user.domain'}; }
 6598:   if (!$stuname) { $stuname=$env{'user.name'}; }
 6599:   if ($domain eq 'public' && $stuname eq 'public') {
 6600:       $stuname=&get_requestor_ip();
 6601:   }
 6602:   my $now=time;
 6603:   my %hash;
 6604:   my $path=LONCAPA::tempdir();
 6605:   if (tie(%hash,'GDBM_File',
 6606: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 6607: 	  &GDBM_WRCREAT(),0640)) {
 6608:     $hash{"version:$symb"}++;
 6609:     my $version=$hash{"version:$symb"};
 6610:     my $allkeys=''; 
 6611:     foreach my $key (keys(%$storehash)) {
 6612:       $allkeys.=$key.':';
 6613:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
 6614:     }
 6615:     $hash{"$version:$symb:timestamp"}=$now;
 6616:     $allkeys.='timestamp';
 6617:     $hash{"$version:keys:$symb"}=$allkeys;
 6618:     if (untie(%hash)) {
 6619:       return 'ok';
 6620:     } else {
 6621:       return "error:$!";
 6622:     }
 6623:   } else {
 6624:     return "error:$!";
 6625:   }
 6626: }
 6627: 
 6628: # -----------------------------------------------------------------Temp Restore
 6629: 
 6630: sub tmprestore {
 6631:   my ($symb,$namespace,$domain,$stuname) = @_;
 6632: 
 6633:   if (!$symb) {
 6634:     $symb=&symbread();
 6635:     if (!$symb) { $symb= $env{'request.url'}; }
 6636:   }
 6637:   $symb=escape($symb);
 6638: 
 6639:   if (!$namespace) { $namespace=$env{'request.state'}; }
 6640: 
 6641:   if (!$domain) { $domain=$env{'user.domain'}; }
 6642:   if (!$stuname) { $stuname=$env{'user.name'}; }
 6643:   if ($domain eq 'public' && $stuname eq 'public') {
 6644:       $stuname=&get_requestor_ip();
 6645:   }
 6646:   my %returnhash;
 6647:   $namespace=~s/\//\_/g;
 6648:   $namespace=~s/\W//g;
 6649:   my %hash;
 6650:   my $path=LONCAPA::tempdir();
 6651:   if (tie(%hash,'GDBM_File',
 6652: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 6653: 	  &GDBM_READER(),0640)) {
 6654:     my $version=$hash{"version:$symb"};
 6655:     $returnhash{'version'}=$version;
 6656:     my $scope;
 6657:     for ($scope=1;$scope<=$version;$scope++) {
 6658:       my $vkeys=$hash{"$scope:keys:$symb"};
 6659:       my @keys=split(/:/,$vkeys);
 6660:       my $key;
 6661:       $returnhash{"$scope:keys"}=$vkeys;
 6662:       foreach $key (@keys) {
 6663: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 6664: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 6665:       }
 6666:     }
 6667:     if (!(untie(%hash))) {
 6668:       return "error:$!";
 6669:     }
 6670:   } else {
 6671:     return "error:$!";
 6672:   }
 6673:   return %returnhash;
 6674: }
 6675: 
 6676: # ----------------------------------------------------------------------- Store
 6677: 
 6678: sub store {
 6679:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
 6680:     my $home='';
 6681: 
 6682:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 6683: 
 6684:     $symb=&symbclean($symb);
 6685:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 6686: 
 6687:     if (!$domain) { $domain=$env{'user.domain'}; }
 6688:     if (!$stuname) { $stuname=$env{'user.name'}; }
 6689: 
 6690:     &devalidate($symb,$stuname,$domain);
 6691: 
 6692:     $symb=escape($symb);
 6693:     if (!$namespace) { 
 6694:        unless ($namespace=$env{'request.course.id'}) { 
 6695:           return ''; 
 6696:        } 
 6697:     }
 6698:     if (!$home) { $home=$env{'user.home'}; }
 6699: 
 6700:     $$storehash{'ip'}=&get_requestor_ip();
 6701:     $$storehash{'host'}=$perlvar{'lonHostID'};
 6702: 
 6703:     my $namevalue='';
 6704:     foreach my $key (keys(%$storehash)) {
 6705:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 6706:     }
 6707:     $namevalue=~s/\&$//;
 6708:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
 6709:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
 6710: }
 6711: 
 6712: # -------------------------------------------------------------- Critical Store
 6713: 
 6714: sub cstore {
 6715:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
 6716:     my $home='';
 6717: 
 6718:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 6719: 
 6720:     $symb=&symbclean($symb);
 6721:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 6722: 
 6723:     if (!$domain) { $domain=$env{'user.domain'}; }
 6724:     if (!$stuname) { $stuname=$env{'user.name'}; }
 6725: 
 6726:     &devalidate($symb,$stuname,$domain);
 6727: 
 6728:     $symb=escape($symb);
 6729:     if (!$namespace) { 
 6730:        unless ($namespace=$env{'request.course.id'}) { 
 6731:           return ''; 
 6732:        } 
 6733:     }
 6734:     if (!$home) { $home=$env{'user.home'}; }
 6735: 
 6736:     $$storehash{'ip'}=&get_requestor_ip();
 6737:     $$storehash{'host'}=$perlvar{'lonHostID'};
 6738: 
 6739:     my $namevalue='';
 6740:     foreach my $key (keys(%$storehash)) {
 6741:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 6742:     }
 6743:     $namevalue=~s/\&$//;
 6744:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
 6745:     return critical
 6746:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
 6747: }
 6748: 
 6749: # --------------------------------------------------------------------- Restore
 6750: 
 6751: sub restore {
 6752:     my ($symb,$namespace,$domain,$stuname) = @_;
 6753:     my $home='';
 6754: 
 6755:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 6756: 
 6757:     if (!$symb) {
 6758:         return if ($namespace eq 'courserequests');
 6759:         unless ($symb=escape(&symbread())) { return ''; }
 6760:     } else {
 6761:         unless ($namespace eq 'courserequests') {
 6762:             $symb=&escape(&symbclean($symb));
 6763:         }
 6764:     }
 6765:     if (!$namespace) { 
 6766:        unless ($namespace=$env{'request.course.id'}) { 
 6767:           return ''; 
 6768:        } 
 6769:     }
 6770:     if (!$domain) { $domain=$env{'user.domain'}; }
 6771:     if (!$stuname) { $stuname=$env{'user.name'}; }
 6772:     if (!$home) { $home=$env{'user.home'}; }
 6773:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
 6774: 
 6775:     my %returnhash=();
 6776:     foreach my $line (split(/\&/,$answer)) {
 6777: 	my ($name,$value)=split(/\=/,$line);
 6778:         $returnhash{&unescape($name)}=&thaw_unescape($value);
 6779:     }
 6780:     my $version;
 6781:     for ($version=1;$version<=$returnhash{'version'};$version++) {
 6782:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
 6783:           $returnhash{$item}=$returnhash{$version.':'.$item};
 6784:        }
 6785:     }
 6786:     return %returnhash;
 6787: }
 6788: 
 6789: # ---------------------------------------------------------- Course Description
 6790: #
 6791: #  
 6792: 
 6793: sub coursedescription {
 6794:     my ($courseid,$args)=@_;
 6795:     $courseid=~s/^\///;
 6796:     $courseid=~s/\_/\//g;
 6797:     my ($cdomain,$cnum)=split(/\//,$courseid);
 6798:     my $chome=&homeserver($cnum,$cdomain);
 6799:     my $normalid=$cdomain.'_'.$cnum;
 6800:     # need to always cache even if we get errors otherwise we keep 
 6801:     # trying and trying and trying to get the course description.
 6802:     my %envhash=();
 6803:     my %returnhash=();
 6804:     
 6805:     my $expiretime=600;
 6806:     if ($env{'request.course.id'} eq $normalid) {
 6807: 	$expiretime=120;
 6808:     }
 6809: 
 6810:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
 6811:     if (!$args->{'freshen_cache'}
 6812: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
 6813: 	foreach my $key (keys(%env)) {
 6814: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
 6815: 	    my ($setting) = $1;
 6816: 	    $returnhash{$setting} = $env{$key};
 6817: 	}
 6818: 	return %returnhash;
 6819:     }
 6820: 
 6821:     # get the data again
 6822: 
 6823:     if (!$args->{'one_time'}) {
 6824: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
 6825:     }
 6826: 
 6827:     if ($chome ne 'no_host') {
 6828:        %returnhash=&dump('environment',$cdomain,$cnum);
 6829:        if (!exists($returnhash{'con_lost'})) {
 6830: 	   my $username = $env{'user.name'}; # Defult username
 6831: 	   if(defined $args->{'user'}) {
 6832: 	       $username = $args->{'user'};
 6833: 	   }
 6834:            $returnhash{'home'}= $chome;
 6835: 	   $returnhash{'domain'} = $cdomain;
 6836: 	   $returnhash{'num'} = $cnum;
 6837:            if (!defined($returnhash{'type'})) {
 6838:                $returnhash{'type'} = 'Course';
 6839:            }
 6840:            while (my ($name,$value) = each %returnhash) {
 6841:                $envhash{'course.'.$normalid.'.'.$name}=$value;
 6842:            }
 6843:            $returnhash{'url'}=&clutter($returnhash{'url'});
 6844:            $returnhash{'fn'}=LONCAPA::tempdir() .
 6845: 	       $username.'_'.$cdomain.'_'.$cnum;
 6846:            $envhash{'course.'.$normalid.'.home'}=$chome;
 6847:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
 6848:            $envhash{'course.'.$normalid.'.num'}=$cnum;
 6849:        }
 6850:     }
 6851:     if (!$args->{'one_time'}) {
 6852: 	&appenv(\%envhash);
 6853:     }
 6854:     return %returnhash;
 6855: }
 6856: 
 6857: sub update_released_required {
 6858:     my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
 6859:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
 6860:         $cid = $env{'request.course.id'};
 6861:         $cdom = $env{'course.'.$cid.'.domain'};
 6862:         $cnum = $env{'course.'.$cid.'.num'};
 6863:         $chome = $env{'course.'.$cid.'.home'};
 6864:     }
 6865:     if ($needsrelease) {
 6866:         my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
 6867:         my $needsupdate;
 6868:         if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
 6869:             $needsupdate = 1;
 6870:         } else {
 6871:             my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
 6872:             my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
 6873:             if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
 6874:                 $needsupdate = 1;
 6875:             }
 6876:         }
 6877:         if ($needsupdate) {
 6878:             my %needshash = (
 6879:                              'internal.releaserequired' => $needsrelease,
 6880:                             );
 6881:             my $putresult = &put('environment',\%needshash,$cdom,$cnum);
 6882:             if ($putresult eq 'ok') {
 6883:                 &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
 6884:                 my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
 6885:                 if (ref($crsinfo{$cid}) eq 'HASH') {
 6886:                     $crsinfo{$cid}{'releaserequired'} = $needsrelease;
 6887:                     &courseidput($cdom,\%crsinfo,$chome,'notime');
 6888:                 }
 6889:             }
 6890:         }
 6891:     }
 6892:     return;
 6893: }
 6894: 
 6895: # -------------------------------------------------See if a user is privileged
 6896: 
 6897: sub privileged {
 6898:     my ($username,$domain,$possdomains,$possroles)=@_;
 6899:     my $now = time;
 6900:     my $roles;
 6901:     if (ref($possroles) eq 'ARRAY') {
 6902:         $roles = $possroles; 
 6903:     } else {
 6904:         $roles = ['dc','su'];
 6905:     }
 6906:     if (ref($possdomains) eq 'ARRAY') {
 6907:         my %privileged = &privileged_by_domain($possdomains,$roles);
 6908:         foreach my $dom (@{$possdomains}) {
 6909:             if (($username =~ /^$match_username$/) && ($domain =~ /^$match_domain$/) &&
 6910:                 (ref($privileged{$dom}) eq 'HASH')) {
 6911:                 foreach my $role (@{$roles}) {
 6912:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
 6913:                         if (exists($privileged{$dom}{$role}{$username.':'.$domain})) {
 6914:                             my ($end,$start) = split(/:/,$privileged{$dom}{$role}{$username.':'.$domain});
 6915:                             return 1 unless (($end && $end < $now) ||
 6916:                                              ($start && $start > $now));
 6917:                         }
 6918:                     }
 6919:                 }
 6920:             }
 6921:         }
 6922:     } else {
 6923:         my %rolesdump = &dump("roles", $domain, $username) or return 0;
 6924:         my $now = time;
 6925: 
 6926:         for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys(%rolesdump)}) {
 6927:             my ($trole, $tend, $tstart) = split(/_/, $role);
 6928:             if (grep(/^\Q$trole\E$/,@{$roles})) {
 6929:                 return 1 unless ($tend && $tend < $now) 
 6930:                         or ($tstart && $tstart > $now);
 6931:             }
 6932:         }
 6933:     }
 6934:     return 0;
 6935: }
 6936: 
 6937: sub privileged_by_domain {
 6938:     my ($domains,$roles) = @_;
 6939:     my %privileged = ();
 6940:     my $cachetime = 60*60*24;
 6941:     my $now = time;
 6942:     unless ((ref($domains) eq 'ARRAY') && (ref($roles) eq 'ARRAY')) {
 6943:         return %privileged;
 6944:     }
 6945:     foreach my $dom (@{$domains}) {
 6946:         next if (ref($privileged{$dom}) eq 'HASH');
 6947:         my $needroles;
 6948:         foreach my $role (@{$roles}) {
 6949:             my ($result,$cached)=&is_cached_new('priv_'.$role,$dom);
 6950:             if (defined($cached)) {
 6951:                 if (ref($result) eq 'HASH') {
 6952:                     $privileged{$dom}{$role} = $result;
 6953:                 }
 6954:             } else {
 6955:                 $needroles = 1;
 6956:             }
 6957:         }
 6958:         if ($needroles) {
 6959:             my %dompersonnel = &get_domain_roles($dom,$roles);
 6960:             $privileged{$dom} = {};
 6961:             foreach my $server (keys(%dompersonnel)) {
 6962:                 if (ref($dompersonnel{$server}) eq 'HASH') {
 6963:                     foreach my $item (keys(%{$dompersonnel{$server}})) {
 6964:                         my ($trole,$uname,$udom,$rest) = split(/:/,$item,4);
 6965:                         my ($end,$start) = split(/:/,$dompersonnel{$server}{$item});
 6966:                         next if ($end && $end < $now);
 6967:                         $privileged{$dom}{$trole}{$uname.':'.$udom} = 
 6968:                             $dompersonnel{$server}{$item};
 6969:                     }
 6970:                 }
 6971:             }
 6972:             if (ref($privileged{$dom}) eq 'HASH') {
 6973:                 foreach my $role (@{$roles}) {
 6974:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
 6975:                         &do_cache_new('priv_'.$role,$dom,$privileged{$dom}{$role},$cachetime);
 6976:                     } else {
 6977:                         my %hash = ();
 6978:                         &do_cache_new('priv_'.$role,$dom,\%hash,$cachetime);
 6979:                     }
 6980:                 }
 6981:             }
 6982:         }
 6983:     }
 6984:     return %privileged;
 6985: }
 6986: 
 6987: # -------------------------------------------------------- Get user privileges
 6988: 
 6989: sub rolesinit {
 6990:     my ($domain, $username) = @_;
 6991:     my %userroles = ('user.login.time' => time);
 6992:     my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
 6993: 
 6994:     # firstaccess and timerinterval are related to timed maps/resources. 
 6995:     # also, blocking can be triggered by an activating timer
 6996:     # it's saved in the user's %env.
 6997:     my %firstaccess = &dump('firstaccesstimes', $domain, $username);
 6998:     my %timerinterval = &dump('timerinterval', $domain, $username);
 6999:     my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
 7000:         %timerintchk, %timerintenv, %coauthorenv);
 7001: 
 7002:     foreach my $key (keys(%firstaccess)) {
 7003:         my ($cid, $rest) = split(/\0/, $key);
 7004:         $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
 7005:     }
 7006: 
 7007:     foreach my $key (keys(%timerinterval)) {
 7008:         my ($cid,$rest) = split(/\0/,$key);
 7009:         $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
 7010:     }
 7011: 
 7012:     my %allroles=();
 7013:     my %allgroups=();
 7014:     my %gotcoauconfig=();
 7015:     my %domdefaults=();
 7016: 
 7017:     for my $area (grep { ! /^rolesdef_/ } keys(%rolesdump)) {
 7018:         my $role = $rolesdump{$area};
 7019:         $area =~ s/\_\w\w$//;
 7020: 
 7021:         my ($trole, $tend, $tstart, $group_privs);
 7022: 
 7023:         if ($role =~ /^cr/) {
 7024:         # Custom role, defined by a user 
 7025:         # e.g., user.role.cr/msu/smith/mynewrole
 7026:             if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
 7027:                 $trole = $1;
 7028:                 ($tend, $tstart) = split('_', $2);
 7029:             } else {
 7030:                 $trole = $role;
 7031:             }
 7032:         } elsif ($role =~ m|^gr/|) {
 7033:         # Role of member in a group, defined within a course/community
 7034:         # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
 7035:             ($trole, $tend, $tstart) = split(/_/, $role);
 7036:             next if $tstart eq '-1';
 7037:             ($trole, $group_privs) = split(/\//, $trole);
 7038:             $group_privs = &unescape($group_privs);
 7039:         } else {
 7040:         # Just a normal role, defined in roles.tab
 7041:             ($trole, $tend, $tstart) = split(/_/,$role);
 7042:         }
 7043: 
 7044:         my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
 7045:                  $username);
 7046:         @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
 7047: 
 7048:         # role expired or not available yet?
 7049:         $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or 
 7050:             ($tstart != 0 && $tstart > $userroles{'user.login.time'});
 7051: 
 7052:         next if $area eq '' or $trole eq '';
 7053: 
 7054:         my $spec = "$trole.$area";
 7055:         my ($tdummy, $tdomain, $trest) = split(/\//, $area);
 7056: 
 7057:         if ($trole =~ /^cr\//) {
 7058:         # Custom role, defined by a user
 7059:             &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
 7060:         } elsif ($trole eq 'gr') {
 7061:         # Role of a member in a group, defined within a course/community
 7062:             &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
 7063:             next;
 7064:         } else {
 7065:         # Normal role, defined in roles.tab
 7066:             &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
 7067:             if (($trole eq 'ca') || ($trole eq 'aa')) {
 7068:                 (undef,my ($audom,$auname)) = split(/\//,$area);
 7069:                 unless ($gotcoauconfig{$area}) {
 7070:                     my @ca_settings = ('authoreditors','coauthorlist','coauthoroptin');
 7071:                     my %info = &userenvironment($audom,$auname,@ca_settings);
 7072:                     $gotcoauconfig{$area} = 1;
 7073:                     foreach my $item (@ca_settings) {
 7074:                         if (exists($info{$item})) {
 7075:                             my $name = $item;
 7076:                             if ($item eq 'authoreditors') {
 7077:                                 $name = 'editors';
 7078:                                 unless ($info{'authoreditors'}) {
 7079:                                     my %domdefs;
 7080:                                     if (ref($domdefaults{$audom}) eq 'HASH') {
 7081:                                         %domdefs = %{$domdefaults{$audom}};
 7082:                                     } else {
 7083:                                         %domdefs = &get_domain_defaults($audom);
 7084:                                         $domdefaults{$audom} = \%domdefs;
 7085:                                     }
 7086:                                     if ($domdefs{$name} ne '') {
 7087:                                         $info{'authoreditors'} = $domdefs{$name};
 7088:                                     } else {
 7089:                                         $info{'authoreditors'} = 'edit,xml';
 7090:                                     }
 7091:                                 }
 7092:                             }
 7093:                             $coauthorenv{"environment.internal.$name.$area"} = $info{$item};
 7094:                         }
 7095:                     }
 7096:                 }
 7097:             }
 7098:         }
 7099: 
 7100:         my $cid = $tdomain.'_'.$trest;
 7101:         unless ($firstaccchk{$cid}) {
 7102:             if (ref($coursetimerstarts{$cid}) eq 'HASH') {
 7103:                 foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
 7104:                     $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} = 
 7105:                         $coursetimerstarts{$cid}{$item}; 
 7106:                 }
 7107:             }
 7108:             $firstaccchk{$cid} = 1;
 7109:         }
 7110:         unless ($timerintchk{$cid}) {
 7111:             if (ref($coursetimerintervals{$cid}) eq 'HASH') {
 7112:                 foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
 7113:                     $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
 7114:                        $coursetimerintervals{$cid}{$item};
 7115:                 }
 7116:             }
 7117:             $timerintchk{$cid} = 1;
 7118:         }
 7119:     }
 7120: 
 7121:     @userroles{'user.author','user.adv','user.rar'} = &set_userprivs(\%userroles,
 7122:                                                           \%allroles, \%allgroups);
 7123:     $env{'user.adv'} = $userroles{'user.adv'};
 7124:     $env{'user.rar'} = $userroles{'user.rar'};
 7125: 
 7126:     return (\%userroles,\%firstaccenv,\%timerintenv,\%coauthorenv);
 7127: }
 7128: 
 7129: sub set_arearole {
 7130:     my ($trole,$area,$tstart,$tend,$domain,$username,$nolog) = @_;
 7131:     unless ($nolog) {
 7132: # log the associated role with the area
 7133:         &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
 7134:     }
 7135:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
 7136: }
 7137: 
 7138: sub custom_roleprivs {
 7139:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
 7140:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
 7141:     my $homsvr = &homeserver($rauthor,$rdomain);
 7142:     if (&hostname($homsvr) ne '') {
 7143:         my ($rdummy,$roledef)=
 7144:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
 7145:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
 7146:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
 7147:             if (defined($syspriv)) {
 7148:                 if ($trest =~ /^$match_community$/) {
 7149:                     $syspriv =~ s/bre\&S//; 
 7150:                 }
 7151:                 $$allroles{'cm./'}.=':'.$syspriv;
 7152:                 $$allroles{$spec.'./'}.=':'.$syspriv;
 7153:             }
 7154:             if ($tdomain ne '') {
 7155:                 if (defined($dompriv)) {
 7156:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
 7157:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
 7158:                 }
 7159:                 if (($trest ne '') && (defined($coursepriv))) {
 7160:                     if ($trole =~ m{^cr/$tdomain/$tdomain\Q-domainconfig\E/([^/]+)$}) {
 7161:                         my $rolename = $1;
 7162:                         $coursepriv = &course_adhocrole_privs($rolename,$tdomain,$trest,$coursepriv);
 7163:                     }
 7164:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
 7165:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
 7166:                 }
 7167:             }
 7168:         }
 7169:     }
 7170: }
 7171: 
 7172: sub course_adhocrole_privs {
 7173:     my ($rolename,$cdom,$cnum,$coursepriv) = @_;
 7174:     my %overrides = &get('environment',["internal.adhocpriv.$rolename"],$cdom,$cnum);
 7175:     if ($overrides{"internal.adhocpriv.$rolename"}) {
 7176:         my (%currprivs,%storeprivs);
 7177:         foreach my $item (split(/:/,$coursepriv)) {
 7178:             my ($priv,$restrict) = split(/\&/,$item);
 7179:             $currprivs{$priv} = $restrict;
 7180:         }
 7181:         my (%possadd,%possremove,%full);
 7182:         foreach my $item (split(/\:/,$Apache::lonnet::pr{'cr:c'})) {
 7183:             my ($priv,$restrict)=split(/\&/,$item);
 7184:             $full{$priv} = $restrict;
 7185:         }
 7186:         foreach my $item (split(/,/,$overrides{"internal.adhocpriv.$rolename"})) {
 7187:             next if ($item eq '');
 7188:             my ($rule,$rest) = split(/=/,$item);
 7189:             next unless (($rule eq 'off') || ($rule eq 'on'));
 7190:             foreach my $priv (split(/:/,$rest)) {
 7191:                 if ($priv ne '') {
 7192:                     if ($rule eq 'off') {
 7193:                         $possremove{$priv} = 1;
 7194:                     } else {
 7195:                         $possadd{$priv} = 1;
 7196:                     }
 7197:                 }
 7198:             }
 7199:         }
 7200:         foreach my $priv (sort(keys(%full))) {
 7201:             if (exists($currprivs{$priv})) {
 7202:                 unless (exists($possremove{$priv})) {
 7203:                     $storeprivs{$priv} = $currprivs{$priv};
 7204:                 }
 7205:             } elsif (exists($possadd{$priv})) {
 7206:                 $storeprivs{$priv} = $full{$priv};
 7207:             }
 7208:         }
 7209:         $coursepriv = ':'.join(':',map { $_.'&'.$storeprivs{$_}; } sort(keys(%storeprivs)));
 7210:     }
 7211:     return $coursepriv;
 7212: }
 7213: 
 7214: sub group_roleprivs {
 7215:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
 7216:     my $access = 1;
 7217:     my $now = time;
 7218:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
 7219:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
 7220:     if ($access) {
 7221:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
 7222:         $$allgroups{$course}{$group} .=':'.$group_privs;
 7223:     }
 7224: }
 7225: 
 7226: sub standard_roleprivs {
 7227:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
 7228:     if (defined($pr{$trole.':s'})) {
 7229:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
 7230:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
 7231:     }
 7232:     if ($tdomain ne '') {
 7233:         if (defined($pr{$trole.':d'})) {
 7234:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 7235:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 7236:         }
 7237:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
 7238:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
 7239:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
 7240:         }
 7241:     }
 7242: }
 7243: 
 7244: sub set_userprivs {
 7245:     my ($userroles,$allroles,$allgroups,$groups_roles) = @_; 
 7246:     my $author=0;
 7247:     my $adv=0;
 7248:     my $rar=0;
 7249:     my %grouproles = ();
 7250:     if (keys(%{$allgroups}) > 0) {
 7251:         my @groupkeys; 
 7252:         foreach my $role (keys(%{$allroles})) {
 7253:             push(@groupkeys,$role);
 7254:         }
 7255:         if (ref($groups_roles) eq 'HASH') {
 7256:             foreach my $key (keys(%{$groups_roles})) {
 7257:                 unless (grep(/^\Q$key\E$/,@groupkeys)) {
 7258:                     push(@groupkeys,$key);
 7259:                 }
 7260:             }
 7261:         }
 7262:         if (@groupkeys > 0) {
 7263:             foreach my $role (@groupkeys) {
 7264:                 my ($trole,$area,$sec,$extendedarea);
 7265:                 if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
 7266:                     $trole = $1;
 7267:                     $area = $2;
 7268:                     $sec = $3;
 7269:                     $extendedarea = $area.$sec;
 7270:                     if (exists($$allgroups{$area})) {
 7271:                         foreach my $group (keys(%{$$allgroups{$area}})) {
 7272:                             my $spec = $trole.'.'.$extendedarea;
 7273:                             $grouproles{$spec.'.'.$area.'/'.$group} = 
 7274:                                                 $$allgroups{$area}{$group};
 7275:                         }
 7276:                     }
 7277:                 }
 7278:             }
 7279:         }
 7280:     }
 7281:     foreach my $group (keys(%grouproles)) {
 7282:         $$allroles{$group} = $grouproles{$group};
 7283:     }
 7284:     foreach my $role (keys(%{$allroles})) {
 7285:         my %thesepriv;
 7286:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
 7287:         foreach my $item (split(/:/,$$allroles{$role})) {
 7288:             if ($item ne '') {
 7289:                 my ($privilege,$restrictions)=split(/&/,$item);
 7290:                 if ($restrictions eq '') {
 7291:                     $thesepriv{$privilege}='F';
 7292:                 } elsif ($thesepriv{$privilege} ne 'F') {
 7293:                     $thesepriv{$privilege}.=$restrictions;
 7294:                 }
 7295:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
 7296:                 if ($thesepriv{'rar'} eq 'F') { $rar=1; }
 7297:             }
 7298:         }
 7299:         my $thesestr='';
 7300:         foreach my $priv (sort(keys(%thesepriv))) {
 7301: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
 7302: 	}
 7303:         $userroles->{'user.priv.'.$role} = $thesestr;
 7304:     }
 7305:     return ($author,$adv,$rar);
 7306: }
 7307: 
 7308: sub role_status {
 7309:     my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
 7310:     if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
 7311:         my ($one,$two) = split(m{\./},$rolekey,2);
 7312:         (undef,undef,$$role) = split(/\./,$one,3);
 7313:         unless (!defined($$role) || $$role eq '') {
 7314:             $$where = '/'.$two;
 7315:             $$trolecode=$$role.'.'.$$where;
 7316:             ($$tstart,$$tend)=split(/\./,$env{$rolekey});
 7317:             $$tstatus='is';
 7318:             if ($$tstart && $$tstart>$update) {
 7319:                 $$tstatus='future';
 7320:                 if ($$tstart<$now) {
 7321:                     if ($$tstart && $$tstart>$refresh) {
 7322:                         if (($$where ne '') && ($$role ne '')) {
 7323:                             my (%allroles,%allgroups,$group_privs,
 7324:                                 %groups_roles,@rolecodes);
 7325:                             my %userroles = (
 7326:                                 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
 7327:                             );
 7328:                             @rolecodes = ('cm'); 
 7329:                             my $spec=$$role.'.'.$$where;
 7330:                             my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
 7331:                             if ($$role =~ /^cr\//) {
 7332:                                 &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
 7333:                                 push(@rolecodes,'cr');
 7334:                             } elsif ($$role eq 'gr') {
 7335:                                 push(@rolecodes,$$role);
 7336:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
 7337:                                                     $env{'user.name'});
 7338:                                 my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
 7339:                                 (undef,my $group_privs) = split(/\//,$trole);
 7340:                                 $group_privs = &unescape($group_privs);
 7341:                                 &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
 7342:                                 my %course_roles = &get_my_roles($env{'user.name'},$env{'user.domain'},'userroles',['active'],['cc','co','in','ta','ep','ad','st','cr'],[$tdomain],1);
 7343:                                 &get_groups_roles($tdomain,$trest,
 7344:                                                   \%course_roles,\@rolecodes,
 7345:                                                   \%groups_roles);
 7346:                             } else {
 7347:                                 push(@rolecodes,$$role);
 7348:                                 &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
 7349:                             }
 7350:                             my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%allroles,\%allgroups,
 7351:                                                                    \%groups_roles);
 7352:                             &appenv(\%userroles,\@rolecodes);
 7353:                             &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
 7354:                         }
 7355:                     }
 7356:                     $$tstatus = 'is';
 7357:                 }
 7358:             }
 7359:             if ($$tend) {
 7360:                 if ($$tend<$update) {
 7361:                     $$tstatus='expired';
 7362:                 } elsif ($$tend<$now) {
 7363:                     $$tstatus='will_not';
 7364:                 }
 7365:             }
 7366:         }
 7367:     }
 7368: }
 7369: 
 7370: sub get_groups_roles {
 7371:     my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
 7372:     return unless((ref($cdom_courseroles) eq 'HASH') && 
 7373:                   (ref($rolecodes) eq 'ARRAY') && 
 7374:                   (ref($groups_roles) eq 'HASH')); 
 7375:     if (keys(%{$cdom_courseroles}) > 0) {
 7376:         my ($cnum) = ($rest =~ /^($match_courseid)/);
 7377:         if ($cdom ne '' && $cnum ne '') {
 7378:             foreach my $key (keys(%{$cdom_courseroles})) {
 7379:                 if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
 7380:                     my $crsrole = $1;
 7381:                     my $crssec = $2;
 7382:                     if ($crsrole =~ /^cr/) {
 7383:                         unless (grep(/^cr$/,@{$rolecodes})) {
 7384:                             push(@{$rolecodes},'cr');
 7385:                         }
 7386:                     } else {
 7387:                         unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
 7388:                             push(@{$rolecodes},$crsrole);
 7389:                         }
 7390:                     }
 7391:                     my $rolekey = "$crsrole./$cdom/$cnum";
 7392:                     if ($crssec ne '') {
 7393:                         $rolekey .= "/$crssec";
 7394:                     }
 7395:                     $rolekey .= './';
 7396:                     $groups_roles->{$rolekey} = $rolecodes;
 7397:                 }
 7398:             }
 7399:         }
 7400:     }
 7401:     return;
 7402: }
 7403: 
 7404: sub delete_env_groupprivs {
 7405:     my ($where,$courseroles,$possroles) = @_;
 7406:     return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
 7407:     my ($dummy,$udom,$uname,$group) = split(/\//,$where);
 7408:     unless (ref($courseroles->{$udom}) eq 'HASH') {
 7409:         %{$courseroles->{$udom}} =
 7410:             &get_my_roles('','','userroles',['active'],
 7411:                           $possroles,[$udom],1);
 7412:     }
 7413:     if (ref($courseroles->{$udom}) eq 'HASH') {
 7414:         foreach my $item (keys(%{$courseroles->{$udom}})) {
 7415:             my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
 7416:             my $area = '/'.$cdom.'/'.$cnum;
 7417:             my $privkey = "user.priv.$crsrole.$area";
 7418:             if ($crssec ne '') {
 7419:                 $privkey .= '/'.$crssec;
 7420:             }
 7421:             $privkey .= ".$area/$group";
 7422:             &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
 7423:         }
 7424:     }
 7425:     return;
 7426: }
 7427: 
 7428: sub check_adhoc_privs {
 7429:     my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller,$sec) = @_;
 7430:     my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
 7431:     if ($sec) {
 7432:         $cckey .= '/'.$sec;
 7433:     } 
 7434:     my $setprivs;
 7435:     if ($env{$cckey}) {
 7436:         my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
 7437:         &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
 7438:         unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
 7439:             &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
 7440:             $setprivs = 1;
 7441:         }
 7442:     } else {
 7443:         &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
 7444:         $setprivs = 1;
 7445:     }
 7446:     return $setprivs;
 7447: }
 7448: 
 7449: sub set_adhoc_privileges {
 7450: # role can be cc, ca, or cr/<dom>/<dom>-domainconfig/role
 7451:     my ($dcdom,$pickedcourse,$role,$caller,$sec) = @_;
 7452:     my $area = '/'.$dcdom.'/'.$pickedcourse;
 7453:     if ($sec ne '') {
 7454:         $area .= '/'.$sec;
 7455:     }
 7456:     my $spec = $role.'.'.$area;
 7457:     my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
 7458:                                   $env{'user.name'},1);
 7459:     my %rolehash = ();
 7460:     if ($role =~ m{^\Qcr/$dcdom/$dcdom\E\-domainconfig/(\w+)$}) {
 7461:         my $rolename = $1;
 7462:         &custom_roleprivs(\%rolehash,$role,$dcdom,$pickedcourse,$spec,$area);
 7463:         my %domdef = &get_domain_defaults($dcdom);
 7464:         if (ref($domdef{'adhocroles'}) eq 'HASH') {
 7465:             if (ref($domdef{'adhocroles'}{$rolename}) eq 'HASH') {
 7466:                 &appenv({'request.role.desc' => $domdef{'adhocroles'}{$rolename}{'desc'},});
 7467:             }
 7468:         }
 7469:     } else {
 7470:         &standard_roleprivs(\%rolehash,$role,$dcdom,$spec,$pickedcourse,$area);
 7471:     }
 7472:     my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%rolehash);
 7473:     &appenv(\%userroles,[$role,'cm']);
 7474:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
 7475:     unless (($caller eq 'constructaccess' && $env{'request.course.id'}) ||
 7476:             ($caller eq 'tiny')) {
 7477:         &appenv( {'request.role'        => $spec,
 7478:                   'request.role.domain' => $dcdom,
 7479:                   'request.course.sec'  => $sec,
 7480:                  }
 7481:                );
 7482:         my $tadv=0;
 7483:         if (&allowed('adv') eq 'F') { $tadv=1; }
 7484:         &appenv({'request.role.adv'    => $tadv});
 7485:     }
 7486: }
 7487: 
 7488: # --------------------------------------------------------------- get interface
 7489: 
 7490: sub get {
 7491:    my ($namespace,$storearr,$udomain,$uname)=@_;
 7492:    my $items='';
 7493:    foreach my $item (@$storearr) {
 7494:        $items.=&escape($item).'&';
 7495:    }
 7496:    $items=~s/\&$//;
 7497:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 7498:    if (!$uname) { $uname=$env{'user.name'}; }
 7499:    my $uhome=&homeserver($uname,$udomain);
 7500: 
 7501:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
 7502:    my @pairs=split(/\&/,$rep);
 7503:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
 7504:      return @pairs;
 7505:    }
 7506:    my %returnhash=();
 7507:    my $i=0;
 7508:    foreach my $item (@$storearr) {
 7509:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 7510:       $i++;
 7511:    }
 7512:    return %returnhash;
 7513: }
 7514: 
 7515: # --------------------------------------------------------------- del interface
 7516: 
 7517: sub del {
 7518:    my ($namespace,$storearr,$udomain,$uname)=@_;
 7519:    my $items='';
 7520:    foreach my $item (@$storearr) {
 7521:        $items.=&escape($item).'&';
 7522:    }
 7523: 
 7524:    $items=~s/\&$//;
 7525:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 7526:    if (!$uname) { $uname=$env{'user.name'}; }
 7527:    my $uhome=&homeserver($uname,$udomain);
 7528:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
 7529: }
 7530: 
 7531: # -------------------------------------------------------------- dump interface
 7532: 
 7533: sub unserialize {
 7534:     my ($rep, $escapedkeys) = @_;
 7535: 
 7536:     return {} if $rep =~ /^error/;
 7537: 
 7538:     my %returnhash=();
 7539: 	foreach my $item (split(/\&/,$rep)) {
 7540: 	    my ($key, $value) = split(/=/, $item, 2);
 7541: 	    $key = unescape($key) unless $escapedkeys;
 7542: 	    next if $key =~ /^error: 2 /;
 7543: 	    $returnhash{$key} = &thaw_unescape($value);
 7544: 	}
 7545:     #return %returnhash;
 7546:     return \%returnhash;
 7547: }        
 7548: 
 7549: # see Lond::dump_with_regexp
 7550: # if $escapedkeys hash keys won't get unescaped.
 7551: sub dump {
 7552:     my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys,$encrypt)=@_;
 7553:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 7554:     if (!$uname) { $uname=$env{'user.name'}; }
 7555:     my $uhome=&homeserver($uname,$udomain);
 7556: 
 7557:     if ($regexp) {
 7558:         $regexp=&escape($regexp);
 7559:     } else {
 7560:         $regexp='.';
 7561:     }
 7562:     if (grep { $_ eq $uhome } current_machine_ids()) {
 7563:         # user is hosted on this machine
 7564:         my $reply = LONCAPA::Lond::dump_with_regexp(join(":", ($udomain,
 7565:                     $uname, $namespace, $regexp, $range)), $perlvar{'lonVersion'});
 7566:         return %{unserialize($reply, $escapedkeys)};
 7567:     }
 7568:     my $rep;
 7569:     if ($encrypt) {
 7570:         $rep=&reply("encrypt:edump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
 7571:     } else {
 7572:         $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
 7573:     }
 7574:     my @pairs=split(/\&/,$rep);
 7575:     my %returnhash=();
 7576:     if (!($rep =~ /^error/ )) {
 7577: 	foreach my $item (@pairs) {
 7578: 	    my ($key,$value)=split(/=/,$item,2);
 7579:         $key = unescape($key) unless $escapedkeys;
 7580:         #$key = &unescape($key);
 7581: 	    next if ($key =~ /^error: 2 /);
 7582: 	    $returnhash{$key}=&thaw_unescape($value);
 7583: 	}
 7584:     }
 7585:     return %returnhash;
 7586: }
 7587: 
 7588: 
 7589: # --------------------------------------------------------- dumpstore interface
 7590: 
 7591: sub dumpstore {
 7592:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
 7593:    # same as dump but keys must be escaped. They may contain colon separated
 7594:    # lists of values that may themself contain colons (e.g. symbs).
 7595:    return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
 7596: }
 7597: 
 7598: # -------------------------------------------------------------- keys interface
 7599: 
 7600: sub getkeys {
 7601:    my ($namespace,$udomain,$uname)=@_;
 7602:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 7603:    if (!$uname) { $uname=$env{'user.name'}; }
 7604:    my $uhome=&homeserver($uname,$udomain);
 7605:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
 7606:    my @keyarray=();
 7607:    foreach my $key (split(/\&/,$rep)) {
 7608:       next if ($key =~ /^error: 2 /);
 7609:       push(@keyarray,&unescape($key));
 7610:    }
 7611:    return @keyarray;
 7612: }
 7613: 
 7614: # --------------------------------------------------------------- currentdump
 7615: sub currentdump {
 7616:    my ($courseid,$sdom,$sname)=@_;
 7617:    $courseid = $env{'request.course.id'} if (! defined($courseid));
 7618:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
 7619:    $sname    = $env{'user.name'}         if (! defined($sname));
 7620:    my $uhome = &homeserver($sname,$sdom);
 7621:    my $rep;
 7622: 
 7623:    if (grep { $_ eq $uhome } current_machine_ids()) {
 7624:        $rep = LONCAPA::Lond::dump_profile_database(join(":", ($sdom, $sname, 
 7625:                    $courseid)));
 7626:    } else {
 7627:        $rep = reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
 7628:    }
 7629: 
 7630:    return if ($rep =~ /^(error:|no_such_host)/);
 7631:    #
 7632:    my %returnhash=();
 7633:    #
 7634:    if ($rep eq 'unknown_cmd') {
 7635:        # an old lond will not know currentdump
 7636:        # Do a dump and make it look like a currentdump
 7637:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
 7638:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
 7639:        my %hash = @tmp;
 7640:        @tmp=();
 7641:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
 7642:    } else {
 7643:        my @pairs=split(/\&/,$rep);
 7644:        foreach my $pair (@pairs) {
 7645:            my ($key,$value)=split(/=/,$pair,2);
 7646:            my ($symb,$param) = split(/:/,$key);
 7647:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
 7648:                                                         &thaw_unescape($value);
 7649:        }
 7650:    }
 7651:    return %returnhash;
 7652: }
 7653: 
 7654: sub convert_dump_to_currentdump{
 7655:     my %hash = %{shift()};
 7656:     my %returnhash;
 7657:     # Code ripped from lond, essentially.  The only difference
 7658:     # here is the unescaping done by lonnet::dump().  Conceivably
 7659:     # we might run in to problems with parameter names =~ /^v\./
 7660:     while (my ($key,$value) = each(%hash)) {
 7661:         my ($v,$symb,$param) = split(/:/,$key);
 7662: 	$symb  = &unescape($symb);
 7663: 	$param = &unescape($param);
 7664:         next if ($v eq 'version' || $symb eq 'keys');
 7665:         next if (exists($returnhash{$symb}) &&
 7666:                  exists($returnhash{$symb}->{$param}) &&
 7667:                  $returnhash{$symb}->{'v.'.$param} > $v);
 7668:         $returnhash{$symb}->{$param}=$value;
 7669:         $returnhash{$symb}->{'v.'.$param}=$v;
 7670:     }
 7671:     #
 7672:     # Remove all of the keys in the hashes which keep track of
 7673:     # the version of the parameter.
 7674:     while (my ($symb,$param_hash) = each(%returnhash)) {
 7675:         # use a foreach because we are going to delete from the hash.
 7676:         foreach my $key (keys(%$param_hash)) {
 7677:             delete($param_hash->{$key}) if ($key =~ /^v\./);
 7678:         }
 7679:     }
 7680:     return \%returnhash;
 7681: }
 7682: 
 7683: # ------------------------------------------------------ critical inc interface
 7684: 
 7685: sub cinc {
 7686:     return &inc(@_,'critical');
 7687: }
 7688: 
 7689: # --------------------------------------------------------------- inc interface
 7690: 
 7691: sub inc {
 7692:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
 7693:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 7694:     if (!$uname) { $uname=$env{'user.name'}; }
 7695:     my $uhome=&homeserver($uname,$udomain);
 7696:     my $items='';
 7697:     if (! ref($store)) {
 7698:         # got a single value, so use that instead
 7699:         $items = &escape($store).'=&';
 7700:     } elsif (ref($store) eq 'SCALAR') {
 7701:         $items = &escape($$store).'=&';        
 7702:     } elsif (ref($store) eq 'ARRAY') {
 7703:         $items = join('=&',map {&escape($_);} @{$store});
 7704:     } elsif (ref($store) eq 'HASH') {
 7705:         while (my($key,$value) = each(%{$store})) {
 7706:             $items.= &escape($key).'='.&escape($value).'&';
 7707:         }
 7708:     }
 7709:     $items=~s/\&$//;
 7710:     if ($critical) {
 7711: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
 7712:     } else {
 7713: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
 7714:     }
 7715: }
 7716: 
 7717: # --------------------------------------------------------------- put interface
 7718: 
 7719: sub put {
 7720:    my ($namespace,$storehash,$udomain,$uname,$encrypt)=@_;
 7721:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 7722:    if (!$uname) { $uname=$env{'user.name'}; }
 7723:    my $uhome=&homeserver($uname,$udomain);
 7724:    my $items='';
 7725:    foreach my $item (keys(%$storehash)) {
 7726:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 7727:    }
 7728:    $items=~s/\&$//;
 7729:    if ($encrypt) {
 7730:        return &reply("encrypt:put:$udomain:$uname:$namespace:$items",$uhome);
 7731:    } else {
 7732:        return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 7733:    }
 7734: }
 7735: 
 7736: # ------------------------------------------------------------ newput interface
 7737: 
 7738: sub newput {
 7739:    my ($namespace,$storehash,$udomain,$uname)=@_;
 7740:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 7741:    if (!$uname) { $uname=$env{'user.name'}; }
 7742:    my $uhome=&homeserver($uname,$udomain);
 7743:    my $items='';
 7744:    foreach my $key (keys(%$storehash)) {
 7745:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 7746:    }
 7747:    $items=~s/\&$//;
 7748:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
 7749: }
 7750: 
 7751: # ---------------------------------------------------------  putstore interface
 7752: 
 7753: sub putstore {
 7754:    my ($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog)=@_;
 7755:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 7756:    if (!$uname) { $uname=$env{'user.name'}; }
 7757:    my $uhome=&homeserver($uname,$udomain);
 7758:    my $items='';
 7759:    foreach my $key (keys(%$storehash)) {
 7760:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
 7761:    }
 7762:    $items=~s/\&$//;
 7763:    my $esc_symb=&escape($symb);
 7764:    my $esc_v=&escape($version);
 7765:    my $reply =
 7766:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
 7767: 	      $uhome);
 7768:    if (($tolog) && ($reply eq 'ok')) {
 7769:        my $namevalue='';
 7770:        foreach my $key (keys(%{$storehash})) {
 7771:            $namevalue.=&escape($key).'='.&freeze_escape($storehash->{$key}).'&';
 7772:        }
 7773:        my $ip = &get_requestor_ip();
 7774:        $namevalue .= 'ip='.&escape($ip).
 7775:                      '&host='.&escape($perlvar{'lonHostID'}).
 7776:                      '&version='.$esc_v.
 7777:                      '&by='.&escape($env{'user.name'}.':'.$env{'user.domain'});
 7778:        &courselog($symb.':'.$uname.':'.$udomain.':PUTSTORE:'.$namevalue);
 7779:    }
 7780:    if ($reply eq 'unknown_cmd') {
 7781:        # gfall back to way things use to be done
 7782:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
 7783: 			    $uname);
 7784:    }
 7785:    return $reply;
 7786: }
 7787: 
 7788: sub old_putstore {
 7789:     my ($namespace,$symb,$version,$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 %newstorehash;
 7794:     foreach my $item (keys(%$storehash)) {
 7795: 	my $key = $version.':'.&escape($symb).':'.$item;
 7796: 	$newstorehash{$key} = $storehash->{$item};
 7797:     }
 7798:     my $items='';
 7799:     my %allitems = ();
 7800:     foreach my $item (keys(%newstorehash)) {
 7801: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
 7802: 	    my $key = $1.':keys:'.$2;
 7803: 	    $allitems{$key} .= $3.':';
 7804: 	}
 7805: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
 7806:     }
 7807:     foreach my $item (keys(%allitems)) {
 7808: 	$allitems{$item} =~ s/\:$//;
 7809: 	$items.= $item.'='.$allitems{$item}.'&';
 7810:     }
 7811:     $items=~s/\&$//;
 7812:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 7813: }
 7814: 
 7815: # ------------------------------------------------------ critical put interface
 7816: 
 7817: sub cput {
 7818:    my ($namespace,$storehash,$udomain,$uname)=@_;
 7819:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 7820:    if (!$uname) { $uname=$env{'user.name'}; }
 7821:    my $uhome=&homeserver($uname,$udomain);
 7822:    my $items='';
 7823:    foreach my $item (keys(%$storehash)) {
 7824:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 7825:    }
 7826:    $items=~s/\&$//;
 7827:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
 7828: }
 7829: 
 7830: # -------------------------------------------------------------- eget interface
 7831: 
 7832: sub eget {
 7833:    my ($namespace,$storearr,$udomain,$uname)=@_;
 7834:    my $items='';
 7835:    foreach my $item (@$storearr) {
 7836:        $items.=&escape($item).'&';
 7837:    }
 7838:    $items=~s/\&$//;
 7839:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 7840:    if (!$uname) { $uname=$env{'user.name'}; }
 7841:    my $uhome=&homeserver($uname,$udomain);
 7842:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
 7843:    my @pairs=split(/\&/,$rep);
 7844:    my %returnhash=();
 7845:    my $i=0;
 7846:    foreach my $item (@$storearr) {
 7847:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 7848:       $i++;
 7849:    }
 7850:    return %returnhash;
 7851: }
 7852: 
 7853: # ------------------------------------------------------------ tmpput interface
 7854: sub tmpput {
 7855:     my ($storehash,$server,$context)=@_;
 7856:     my $items='';
 7857:     foreach my $item (keys(%$storehash)) {
 7858: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 7859:     }
 7860:     $items=~s/\&$//;
 7861:     if (defined($context)) {
 7862:         $items .= ':'.&escape($context);
 7863:     }
 7864:     return &reply("tmpput:$items",$server);
 7865: }
 7866: 
 7867: # ------------------------------------------------------------ tmpget interface
 7868: sub tmpget {
 7869:     my ($token,$server)=@_;
 7870:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 7871:     my $rep=&reply("tmpget:$token",$server);
 7872:     my %returnhash;
 7873:     if ($rep =~ /^(con_lost|error|no_such_host)/i) {
 7874:         return %returnhash;
 7875:     }
 7876:     foreach my $item (split(/\&/,$rep)) {
 7877: 	my ($key,$value)=split(/=/,$item);
 7878: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
 7879:     }
 7880:     return %returnhash;
 7881: }
 7882: 
 7883: # ------------------------------------------------------------ tmpdel interface
 7884: sub tmpdel {
 7885:     my ($token,$server)=@_;
 7886:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 7887:     return &reply("tmpdel:$token",$server);
 7888: }
 7889: 
 7890: # ------------------------------------------------------------ get_timebased_id 
 7891: 
 7892: sub get_timebased_id {
 7893:     my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
 7894:         $maxtries) = @_;
 7895:     my ($newid,$error,$dellock);
 7896:     unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {  
 7897:         return ('','ok','invalid call to get suffix');
 7898:     }
 7899: 
 7900: # set defaults for any optional args for which values were not supplied
 7901:     if ($who eq '') {
 7902:         $who = $env{'user.name'}.':'.$env{'user.domain'};
 7903:     }
 7904:     if (!$locktries) {
 7905:         $locktries = 3;
 7906:     }
 7907:     if (!$maxtries) {
 7908:         $maxtries = 10;
 7909:     }
 7910:     
 7911:     if (($cdom eq '') || ($cnum eq '')) {
 7912:         if ($env{'request.course.id'}) {
 7913:             $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 7914:             $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 7915:         }
 7916:         if (($cdom eq '') || ($cnum eq '')) {
 7917:             return ('','ok','call to get suffix not in course context');
 7918:         }
 7919:     }
 7920: 
 7921: # construct locking item
 7922:     my $lockhash = {
 7923:                       $prefix."\0".'locked_'.$keyid => $who,
 7924:                    };
 7925:     my $tries = 0;
 7926: 
 7927: # attempt to get lock on nohist_$namespace file
 7928:     my $gotlock = &newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
 7929:     while (($gotlock ne 'ok') && $tries <$locktries) {
 7930:         $tries ++;
 7931:         sleep 1;
 7932:         $gotlock = &newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
 7933:     }
 7934: 
 7935: # attempt to get unique identifier, based on current timestamp
 7936:     if ($gotlock eq 'ok') {
 7937:         my %inuse = &dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
 7938:         my $id = time;
 7939:         $newid = $id;
 7940:         if ($idtype eq 'addcode') {
 7941:             $newid .= &sixnum_code();
 7942:         }
 7943:         my $idtries = 0;
 7944:         while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
 7945:             if ($idtype eq 'concat') {
 7946:                 $newid = $id.$idtries;
 7947:             } elsif ($idtype eq 'addcode') {
 7948:                 $newid = $newid.&sixnum_code();
 7949:             } else {
 7950:                 $newid ++;
 7951:             }
 7952:             $idtries ++;
 7953:         }
 7954:         if (!exists($inuse{$prefix."\0".$newid})) {
 7955:             my %new_item =  (
 7956:                               $prefix."\0".$newid => $who,
 7957:                             );
 7958:             my $putresult = &put('nohist_'.$namespace,\%new_item,
 7959:                                                  $cdom,$cnum);
 7960:             if ($putresult ne 'ok') {
 7961:                 undef($newid);
 7962:                 $error = 'error saving new item: '.$putresult;
 7963:             }
 7964:         } else {
 7965:              undef($newid);
 7966:              $error = ('error: no unique suffix available for the new item ');
 7967:         }
 7968: #  remove lock
 7969:         my @del_lock = ($prefix."\0".'locked_'.$keyid);
 7970:         $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
 7971:     } else {
 7972:         $error = "error: could not obtain lockfile\n";
 7973:         $dellock = 'ok';
 7974:         if (($prefix eq 'paste') && ($namespace eq 'courseeditor') && ($keyid eq 'num')) {
 7975:             $dellock = 'nolock';
 7976:         }
 7977:     }
 7978:     return ($newid,$dellock,$error);
 7979: }
 7980: 
 7981: sub sixnum_code {
 7982:     my $code;
 7983:     for (0..6) {
 7984:         $code .= int( rand(9) );
 7985:     }
 7986:     return $code;
 7987: }
 7988: 
 7989: # -------------------------------------------------- portfolio access checking
 7990: 
 7991: sub portfolio_access {
 7992:     my ($requrl,$clientip) = @_;
 7993:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
 7994:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group,$clientip);
 7995:     if ($result) {
 7996:         my %setters;
 7997:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 7998:             my ($startblock,$endblock,$triggerblock,$by_ip,$blockdom) =
 7999:                 &Apache::loncommon::blockcheck(\%setters,'port',$clientip,$unum,$udom);
 8000:             if (($startblock && $endblock) || ($by_ip)) {
 8001:                 return 'B';
 8002:             }
 8003:         } else {
 8004:             my ($startblock,$endblock,$triggerblock,$by_ip,$blockdom) =
 8005:                 &Apache::loncommon::blockcheck(\%setters,'port',$clientip);
 8006:             if (($startblock && $endblock) || ($by_ip)) {
 8007:                 return 'B';
 8008:             }
 8009:         }
 8010:     }
 8011:     if ($result eq 'ok') {
 8012:        return 'F';
 8013:     } elsif ($result =~ /^[^:]+:guest_/) {
 8014:        return 'A';
 8015:     }
 8016:     return '';
 8017: }
 8018: 
 8019: sub get_portfolio_access {
 8020:     my ($udom,$unum,$file_name,$group,$clientip,$access_hash,$portaccessref) = @_;
 8021: 
 8022:     if (!ref($access_hash)) {
 8023: 	my $current_perms = &get_portfile_permissions($udom,$unum);
 8024: 	my %access_controls = &get_access_controls($current_perms,$group,
 8025: 						   $file_name);
 8026: 	$access_hash = $access_controls{$file_name};
 8027:     }
 8028: 
 8029:     my $portaccess;
 8030:     if (ref($portaccess) eq 'SCALAR') {
 8031:         $portaccess = $$portaccessref;
 8032:     } else {
 8033:         $portaccess = &usertools_access($unum,$udom,'portaccess',undef,'tools');
 8034:     }
 8035: 
 8036:     my ($public,$guest,@domains,@users,@courses,@groups,@ips,@userips);
 8037:     my $now = time;
 8038:     if (ref($access_hash) eq 'HASH') {
 8039:         foreach my $key (keys(%{$access_hash})) {
 8040:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
 8041:             next if (($scope ne 'ip') && ($portaccess == 0));
 8042:             if ($start > $now) {
 8043:                 next;
 8044:             }
 8045:             if ($end && $end<$now) {
 8046:                 next;
 8047:             }
 8048:             if ($scope eq 'public') {
 8049:                 $public = $key;
 8050:                 last;
 8051:             } elsif ($scope eq 'guest') {
 8052:                 $guest = $key;
 8053:             } elsif ($scope eq 'domains') {
 8054:                 push(@domains,$key);
 8055:             } elsif ($scope eq 'users') {
 8056:                 push(@users,$key);
 8057:             } elsif ($scope eq 'course') {
 8058:                 push(@courses,$key);
 8059:             } elsif ($scope eq 'group') {
 8060:                 push(@groups,$key);
 8061:             } elsif ($scope eq 'ip') {
 8062:                 push(@ips,$key);
 8063:             } elsif ($scope eq 'userip') {
 8064:                 push(@userips,$key);
 8065:             }
 8066:         }
 8067:         if ($public) {
 8068:             return 'ok';
 8069:         } elsif (@ips > 0) {
 8070:             my $allowed;
 8071:             foreach my $ipkey (@ips) {
 8072:                 if (ref($access_hash->{$ipkey}{'ip'}) eq 'ARRAY') {
 8073:                     if (&Apache::loncommon::check_ip_acc(join(',',@{$access_hash->{$ipkey}{'ip'}}),$clientip)) {
 8074:                         $allowed = 1;
 8075:                         last; 
 8076:                     }
 8077:                 }
 8078:             }
 8079:             if ($allowed) {
 8080:                 return 'ok';
 8081:             }
 8082:         } elsif (@userips > 0) {
 8083:             my $allowed;
 8084:             foreach my $useripkey (@userips) {
 8085:                 if (ref($access_hash->{$useripkey}{'ip'}) eq 'ARRAY') {
 8086:                     if (&Apache::loncommon::check_ip_acc(join(',',@{$access_hash->{$useripkey}{'ip'}}),$clientip)) {
 8087:                         $allowed = 1;
 8088:                         last;
 8089:                     }
 8090:                 }
 8091:             }
 8092:             if ($allowed) {
 8093:                 return 'ok';
 8094:             }
 8095:         }
 8096:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 8097:             if ($guest) {
 8098:                 return $guest;
 8099:             }
 8100:         } else {
 8101:             if (@domains > 0) {
 8102:                 foreach my $domkey (@domains) {
 8103:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
 8104:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
 8105:                             return 'ok';
 8106:                         }
 8107:                     }
 8108:                 }
 8109:             }
 8110:             if (@users > 0) {
 8111:                 foreach my $userkey (@users) {
 8112:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
 8113:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
 8114:                             if (ref($item) eq 'HASH') {
 8115:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
 8116:                                     ($item->{'udom'} eq $env{'user.domain'})) {
 8117:                                     return 'ok';
 8118:                                 }
 8119:                             }
 8120:                         }
 8121:                     } 
 8122:                 }
 8123:             }
 8124:             my %roleshash;
 8125:             my @courses_and_groups = @courses;
 8126:             push(@courses_and_groups,@groups); 
 8127:             if (@courses_and_groups > 0) {
 8128:                 my (%allgroups,%allroles); 
 8129:                 my ($start,$end,$role,$sec,$group);
 8130:                 foreach my $envkey (%env) {
 8131:                     if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
 8132:                         my $cid = $2.'_'.$3; 
 8133:                         if ($1 eq 'gr') {
 8134:                             $group = $4;
 8135:                             $allgroups{$cid}{$group} = $env{$envkey};
 8136:                         } else {
 8137:                             if ($4 eq '') {
 8138:                                 $sec = 'none';
 8139:                             } else {
 8140:                                 $sec = $4;
 8141:                             }
 8142:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
 8143:                         }
 8144:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
 8145:                         my $cid = $2.'_'.$3;
 8146:                         if ($4 eq '') {
 8147:                             $sec = 'none';
 8148:                         } else {
 8149:                             $sec = $4;
 8150:                         }
 8151:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
 8152:                     }
 8153:                 }
 8154:                 if (keys(%allroles) == 0) {
 8155:                     return;
 8156:                 }
 8157:                 foreach my $key (@courses_and_groups) {
 8158:                     my %content = %{$$access_hash{$key}};
 8159:                     my $cnum = $content{'number'};
 8160:                     my $cdom = $content{'domain'};
 8161:                     my $cid = $cdom.'_'.$cnum;
 8162:                     if (!exists($allroles{$cid})) {
 8163:                         next;
 8164:                     }    
 8165:                     foreach my $role_id (keys(%{$content{'roles'}})) {
 8166:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
 8167:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
 8168:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
 8169:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
 8170:                         foreach my $role (keys(%{$allroles{$cid}})) {
 8171:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
 8172:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
 8173:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
 8174:                                         if (grep/^all$/,@sections) {
 8175:                                             return 'ok';
 8176:                                         } else {
 8177:                                             if (grep/^$sec$/,@sections) {
 8178:                                                 return 'ok';
 8179:                                             }
 8180:                                         }
 8181:                                     }
 8182:                                 }
 8183:                                 if (keys(%{$allgroups{$cid}}) == 0) {
 8184:                                     if (grep/^none$/,@groups) {
 8185:                                         return 'ok';
 8186:                                     }
 8187:                                 } else {
 8188:                                     if (grep/^all$/,@groups) {
 8189:                                         return 'ok';
 8190:                                     } 
 8191:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
 8192:                                         if (grep/^$group$/,@groups) {
 8193:                                             return 'ok';
 8194:                                         }
 8195:                                     }
 8196:                                 } 
 8197:                             }
 8198:                         }
 8199:                     }
 8200:                 }
 8201:             }
 8202:             if ($guest) {
 8203:                 return $guest;
 8204:             }
 8205:         }
 8206:     }
 8207:     return;
 8208: }
 8209: 
 8210: sub course_group_datechecker {
 8211:     my ($dates,$now,$status) = @_;
 8212:     my ($start,$end) = split(/\./,$dates);
 8213:     if (!$start && !$end) {
 8214:         return 'ok';
 8215:     }
 8216:     if (grep/^active$/,@{$status}) {
 8217:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
 8218:             return 'ok';
 8219:         }
 8220:     }
 8221:     if (grep/^previous$/,@{$status}) {
 8222:         if ($end > $now ) {
 8223:             return 'ok';
 8224:         }
 8225:     }
 8226:     if (grep/^future$/,@{$status}) {
 8227:         if ($start > $now) {
 8228:             return 'ok';
 8229:         }
 8230:     }
 8231:     return; 
 8232: }
 8233: 
 8234: sub parse_portfolio_url {
 8235:     my ($url) = @_;
 8236: 
 8237:     my ($type,$udom,$unum,$group,$file_name);
 8238:     
 8239:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
 8240: 	$type = 1;
 8241:         $udom = $1;
 8242:         $unum = $2;
 8243:         $file_name = $3;
 8244:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
 8245: 	$type = 2;
 8246:         $udom = $1;
 8247:         $unum = $2;
 8248:         $group = $3;
 8249:         $file_name = $3.'/'.$4;
 8250:     }
 8251:     if (wantarray) {
 8252: 	return ($type,$udom,$unum,$file_name,$group);
 8253:     }
 8254:     return $type;
 8255: }
 8256: 
 8257: sub is_portfolio_url {
 8258:     my ($url) = @_;
 8259:     return scalar(&parse_portfolio_url($url));
 8260: }
 8261: 
 8262: sub is_portfolio_file {
 8263:     my ($file) = @_;
 8264:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
 8265:         return 1;
 8266:     }
 8267:     return;
 8268: }
 8269: 
 8270: sub is_coursetool_logo {
 8271:     my ($uri) = @_;
 8272:     if ($env{'request.course.id'}) {
 8273:         my $courseurl = &courseid_to_courseurl($env{'request.course.id'});
 8274:         if ($uri =~ m{^/*uploaded\Q$courseurl\E/toollogo/\d+/[^/]+$}) {
 8275:             return 1;
 8276:         }
 8277:     }
 8278:     return;
 8279: }
 8280: 
 8281: sub usertools_access {
 8282:     my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
 8283:     my ($access,%tools);
 8284:     if ($context eq '') {
 8285:         $context = 'tools';
 8286:     }
 8287:     if ($context eq 'requestcourses') {
 8288:         %tools = (
 8289:                       official   => 1,
 8290:                       unofficial => 1,
 8291:                       community  => 1,
 8292:                       textbook   => 1,
 8293:                       placement  => 1,
 8294:                       lti        => 1,
 8295:                  );
 8296:     } elsif ($context eq 'requestauthor') {
 8297:         %tools = (
 8298:                       requestauthor => 1,
 8299:                  );
 8300:     } elsif ($context eq 'authordefaults') {
 8301:         %tools = (
 8302:                       webdav    => 1,
 8303:                  );
 8304:     } else {
 8305:         %tools = (
 8306:                       aboutme   => 1,
 8307:                       blog      => 1,
 8308:                       portfolio => 1,
 8309:                       portaccess => 1,
 8310:                       timezone  => 1,
 8311:                  );
 8312:     }
 8313:     return if (!defined($tools{$tool}));
 8314: 
 8315:     if (($udom eq '') || ($uname eq '')) {
 8316:         $udom = $env{'user.domain'};
 8317:         $uname = $env{'user.name'};
 8318:     }
 8319: 
 8320:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 8321:         if ($action ne 'reload') {
 8322:             if ($context eq 'requestcourses') {
 8323:                 return $env{'environment.canrequest.'.$tool};
 8324:             } elsif ($context eq 'requestauthor') {
 8325:                 return $env{'environment.canrequest.author'};
 8326:             } elsif ($context eq 'authordefaults') {
 8327:                 if ($tool eq 'webdav') {
 8328:                     return $env{'environment.availabletools.'.$tool};
 8329:                 }
 8330:             } else {
 8331:                 return $env{'environment.availabletools.'.$tool};
 8332:             }
 8333:         }
 8334:     }
 8335: 
 8336:     my ($toolstatus,$inststatus,$envkey);
 8337:     if ($context eq 'requestauthor') {
 8338:         $envkey = $context;
 8339:     } elsif ($context eq 'authordefaults') {
 8340:         if ($tool eq 'webdav') {
 8341:             $envkey = 'tools.'.$tool;
 8342:         }
 8343:     } else {
 8344:         $envkey = $context.'.'.$tool;
 8345:     }
 8346: 
 8347:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
 8348:          ($action ne 'reload')) {
 8349:         $toolstatus = $env{'environment.'.$envkey};
 8350:         $inststatus = $env{'environment.inststatus'};
 8351:     } else {
 8352:         if (ref($userenvref) eq 'HASH') {
 8353:             $toolstatus = $userenvref->{$envkey};
 8354:             $inststatus = $userenvref->{'inststatus'};
 8355:         } else {
 8356:             my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
 8357:             $toolstatus = $userenv{$envkey};
 8358:             $inststatus = $userenv{'inststatus'};
 8359:         }
 8360:     }
 8361: 
 8362:     if ($toolstatus ne '') {
 8363:         if ($toolstatus) {
 8364:             $access = 1;
 8365:         } else {
 8366:             $access = 0;
 8367:         }
 8368:         return $access;
 8369:     }
 8370: 
 8371:     my ($is_adv,%domdef);
 8372:     if (ref($is_advref) eq 'HASH') {
 8373:         $is_adv = $is_advref->{'is_adv'};
 8374:     } else {
 8375:         $is_adv = &is_advanced_user($udom,$uname);
 8376:     }
 8377:     if (ref($domdefref) eq 'HASH') {
 8378:         %domdef = %{$domdefref};
 8379:     } else {
 8380:         %domdef = &get_domain_defaults($udom);
 8381:     }
 8382:     if (ref($domdef{$tool}) eq 'HASH') {
 8383:         if ($is_adv) {
 8384:             if ($domdef{$tool}{'_LC_adv'} ne '') {
 8385:                 if ($domdef{$tool}{'_LC_adv'}) { 
 8386:                     $access = 1;
 8387:                 } else {
 8388:                     $access = 0;
 8389:                 }
 8390:                 return $access;
 8391:             }
 8392:         }
 8393:         if ($inststatus ne '') {
 8394:             my ($hasaccess,$hasnoaccess);
 8395:             foreach my $affiliation (split(/:/,$inststatus)) {
 8396:                 if ($domdef{$tool}{$affiliation} ne '') { 
 8397:                     if ($domdef{$tool}{$affiliation}) {
 8398:                         $hasaccess = 1;
 8399:                     } else {
 8400:                         $hasnoaccess = 1;
 8401:                     }
 8402:                 }
 8403:             }
 8404:             if ($hasaccess || $hasnoaccess) {
 8405:                 if ($hasaccess) {
 8406:                     $access = 1;
 8407:                 } elsif ($hasnoaccess) {
 8408:                     $access = 0; 
 8409:                 }
 8410:                 return $access;
 8411:             }
 8412:         } else {
 8413:             if ($domdef{$tool}{'default'} ne '') {
 8414:                 if ($domdef{$tool}{'default'}) {
 8415:                     $access = 1;
 8416:                 } elsif ($domdef{$tool}{'default'} == 0) {
 8417:                     $access = 0;
 8418:                 }
 8419:                 return $access;
 8420:             }
 8421:         }
 8422:     } else {
 8423:         if (($context eq 'tools') && ($tool ne 'webdav')) {
 8424:             $access = 1;
 8425:         } else {
 8426:             $access = 0;
 8427:         }
 8428:         return $access;
 8429:     }
 8430: }
 8431: 
 8432: sub is_course_owner {
 8433:     my ($cdom,$cnum,$udom,$uname) = @_;
 8434:     if (($udom eq '') || ($uname eq '')) {
 8435:         $udom = $env{'user.domain'};
 8436:         $uname = $env{'user.name'};
 8437:     }
 8438:     unless (($udom eq '') || ($uname eq '')) {
 8439:         if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
 8440:             if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
 8441:                 return 1;
 8442:             } else {
 8443:                 my %courseinfo = &coursedescription($cdom.'/'.$cnum);
 8444:                 if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
 8445:                     return 1;
 8446:                 }
 8447:             }
 8448:         }
 8449:     }
 8450:     return;
 8451: }
 8452: 
 8453: sub is_advanced_user {
 8454:     my ($udom,$uname,$nocache) = @_;
 8455:     my ($is_adv,$is_author,$use_cache,$hashid);
 8456:     if ($udom ne '' && $uname ne '') {
 8457:         if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 8458:             if (wantarray) {
 8459:                 return ($env{'user.adv'},$env{'user.author'});
 8460:             } else {
 8461:                 return $env{'user.adv'};
 8462:             }
 8463:         } elsif (!$nocache) {
 8464:             $use_cache = 1;
 8465:             $hashid = "$udom:$uname";  
 8466:             my ($info,$cached)=&is_cached_new('isadvau',$hashid);
 8467:             if ($cached) {
 8468:                 ($is_adv,$is_author) = split(/:/,$info);
 8469:                 if (wantarray) {
 8470:                     return ($is_adv,$is_author);
 8471:                 }
 8472:                 return $is_adv; 
 8473:             }
 8474:         }
 8475:     }
 8476:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
 8477:     my %allroles;
 8478:     foreach my $role (keys(%roleshash)) {
 8479:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
 8480:         my $area = '/'.$tdomain.'/'.$trest;
 8481:         if ($sec ne '') {
 8482:             $area .= '/'.$sec;
 8483:         }
 8484:         if (($area ne '') && ($trole ne '')) {
 8485:             my $spec=$trole.'.'.$area;
 8486:             if ($trole =~ /^cr\//) {
 8487:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
 8488:             } elsif ($trole ne 'gr') {
 8489:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
 8490:             }
 8491:             if ($trole eq 'au') {
 8492:                 $is_author = 1;
 8493:             }
 8494:         }
 8495:     }
 8496:     foreach my $role (keys(%allroles)) {
 8497:         last if ($is_adv);
 8498:         foreach my $item (split(/:/,$allroles{$role})) {
 8499:             if ($item ne '') {
 8500:                 my ($privilege,$restrictions)=split(/&/,$item);
 8501:                 if ($privilege eq 'adv') {
 8502:                     $is_adv = 1;
 8503:                     last;
 8504:                 }
 8505:             }
 8506:         }
 8507:     }
 8508:     if ($use_cache) {
 8509:         my $cachetime = 600;
 8510:         &do_cache_new('isadvau',$hashid,$is_adv.':'.$is_author,$cachetime);
 8511:     }
 8512:     if (wantarray) {
 8513:         return ($is_adv,$is_author);
 8514:     }
 8515:     return $is_adv;
 8516: }
 8517: 
 8518: sub check_can_request {
 8519:     my ($dom,$can_request,$request_domains,$uname,$udom) = @_;
 8520:     my $canreq = 0;
 8521:     if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
 8522:         $uname = $env{'user.name'};
 8523:         $udom = $env{'user.domain'};
 8524:     }
 8525:     my ($types,$typename) = &Apache::loncommon::course_types();
 8526:     my @options = ('approval','validate','autolimit');
 8527:     my $optregex = join('|',@options);
 8528:     if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
 8529:         my %willtrust;
 8530:         foreach my $type (@{$types}) {
 8531:             if (&usertools_access($uname,$udom,$type,undef,
 8532:                                   'requestcourses')) {
 8533:                 $canreq ++;
 8534:                 if (ref($request_domains) eq 'HASH') {
 8535:                     push(@{$request_domains->{$type}},$udom);
 8536:                 }
 8537:                 if ($dom eq $udom) {
 8538:                     $can_request->{$type} = 1;
 8539:                 }
 8540:             }
 8541:             if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '') &&
 8542:                 ($env{'environment.reqcrsotherdom.'.$type} ne '')) {
 8543:                 my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
 8544:                 if (@curr > 0) {
 8545:                     foreach my $item (@curr) {
 8546:                         if (ref($request_domains) eq 'HASH') {
 8547:                             my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
 8548:                             if ($otherdom ne '') {
 8549:                                 unless (exists($willtrust{$otherdom})) {
 8550:                                     $willtrust{$otherdom} = &will_trust('reqcrs',$env{'user.domain'},$otherdom);
 8551:                                 }
 8552:                                 if ($willtrust{$otherdom}) {
 8553:                                     if (ref($request_domains->{$type}) eq 'ARRAY') {
 8554:                                         unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
 8555:                                             push(@{$request_domains->{$type}},$otherdom);
 8556:                                         }
 8557:                                     } else {
 8558:                                         push(@{$request_domains->{$type}},$otherdom);
 8559:                                     }
 8560:                                 }
 8561:                             }
 8562:                         }
 8563:                     }
 8564:                     unless ($dom eq $env{'user.domain'}) {
 8565:                         $canreq ++;
 8566:                         if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
 8567:                             $can_request->{$type} = 1;
 8568:                         }
 8569:                     }
 8570:                 }
 8571:             }
 8572:         }
 8573:     }
 8574:     return $canreq;
 8575: }
 8576: 
 8577: # ---------------------------------------------- Custom access rule evaluation
 8578: 
 8579: sub customaccess {
 8580:     my ($priv,$uri)=@_;
 8581:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
 8582:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
 8583:     $udom = &LONCAPA::clean_domain($udom);
 8584:     $ucrs = &LONCAPA::clean_username($ucrs);
 8585:     my $access=0;
 8586:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
 8587: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
 8588: 	if ($type eq 'user') {
 8589: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
 8590: 		my ($tdom,$tuname)=split(m{/},$scope);
 8591: 		if ($tdom) {
 8592: 		    if ($tdom ne $env{'user.domain'}) { next; }
 8593: 		}
 8594: 		if ($tuname) {
 8595: 		    if ($tuname ne $env{'user.name'}) { next; }
 8596: 		}
 8597: 		$access=($effect eq 'allow');
 8598: 		last;
 8599: 	    }
 8600: 	} else {
 8601: 	    if ($role) {
 8602: 		if ($role ne $urole) { next; }
 8603: 	    }
 8604: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
 8605: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
 8606: 		if ($tdom) {
 8607: 		    if ($tdom ne $udom) { next; }
 8608: 		}
 8609: 		if ($tcrs) {
 8610: 		    if ($tcrs ne $ucrs) { next; }
 8611: 		}
 8612: 		if ($tsec) {
 8613: 		    if ($tsec ne $usec) { next; }
 8614: 		}
 8615: 		$access=($effect eq 'allow');
 8616: 		last;
 8617: 	    }
 8618: 	    if ($realm eq '' && $role eq '') {
 8619: 		$access=($effect eq 'allow');
 8620: 	    }
 8621: 	}
 8622:     }
 8623:     return $access;
 8624: }
 8625: 
 8626: # ------------------------------------------------- Check for a user privilege
 8627: 
 8628: sub allowed {
 8629:     my ($priv,$uri,$symb,$role,$clientip,$noblockcheck,$ignorecache,$nodeeplinkcheck,$nodeeplinkout)=@_;
 8630:     my $ver_orguri=$uri;
 8631:     $uri=&deversion($uri);
 8632:     my $orguri=$uri;
 8633:     $uri=&declutter($uri);
 8634: 
 8635:     if ($priv eq 'evb') {
 8636: # Evade communication block restrictions for specified role in a course or domain
 8637:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
 8638:             return $1;
 8639:         } else {
 8640:             return;
 8641:         }
 8642:     }
 8643: 
 8644:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
 8645: # Free bre access to adm and meta resources
 8646:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard|viewclasslist|aboutme|ext\.tool)$})) 
 8647: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
 8648: 	&& ($priv eq 'bre')) {
 8649: 	return 'F';
 8650:     }
 8651: 
 8652: # Free bre access to user's own portfolio contents
 8653:     my ($space,$domain,$name,@dir)=split('/',$uri);
 8654:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
 8655: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
 8656:         my %setters;
 8657:         my ($startblock,$endblock,$triggerblock,$by_ip,$blockdom) = 
 8658:             &Apache::loncommon::blockcheck(\%setters,'port',$clientip);
 8659:         if (($startblock && $endblock) || ($by_ip)) {
 8660:             return 'B';
 8661:         } else {
 8662:             return 'F';
 8663:         }
 8664:     }
 8665: 
 8666: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
 8667:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
 8668:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
 8669:         if (exists($env{'request.course.id'})) {
 8670:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 8671:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 8672:             if (($domain eq $cdom) && ($name eq $cnum)) {
 8673:                 my $courseprivid=$env{'request.course.id'};
 8674:                 $courseprivid=~s/\_/\//;
 8675:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
 8676:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
 8677:                     return $1; 
 8678:                 } else {
 8679:                     if ($env{'request.course.sec'}) {
 8680:                         $courseprivid.='/'.$env{'request.course.sec'};
 8681:                     }
 8682:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
 8683:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
 8684:                         return $2;
 8685:                     }
 8686:                 }
 8687:             }
 8688:         }
 8689:     }
 8690: 
 8691: # Free bre to public access
 8692: 
 8693:     if ($priv eq 'bre') {
 8694:         my $copyright;
 8695:         unless ($uri =~ /ext\.tool/) {
 8696:             $copyright=&metadata($uri,'copyright');
 8697:         }
 8698: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
 8699:            return 'F'; 
 8700:         }
 8701:         if ($copyright eq 'priv') {
 8702:             $uri=~/([^\/]+)\/([^\/]+)\//;
 8703: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
 8704: 		return '';
 8705:             }
 8706:         }
 8707:         if ($copyright eq 'domain') {
 8708:             $uri=~/([^\/]+)\/([^\/]+)\//;
 8709: 	    unless (($env{'user.domain'} eq $1) ||
 8710:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
 8711: 		return '';
 8712:             }
 8713:         }
 8714:         if ($env{'request.role'}=~ /li\.\//) {
 8715:             # Library role, so allow browsing of resources in this domain.
 8716:             return 'F';
 8717:         }
 8718:         if ($copyright eq 'custom') {
 8719: 	    unless (&customaccess($priv,$uri)) { return ''; }
 8720:         }
 8721:     }
 8722:     # Domain coordinator is trying to create a course
 8723:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
 8724:         # uri is the requested domain in this case.
 8725:         # comparison to 'request.role.domain' shows if the user has selected
 8726:         # a role of dc for the domain in question.
 8727:         return 'F' if ($uri eq $env{'request.role.domain'});
 8728:     }
 8729: 
 8730:     my $thisallowed='';
 8731:     my $statecond=0;
 8732:     my $courseprivid='';
 8733: 
 8734:     my $ownaccess;
 8735:     # Community Coordinator or Assistant Co-author browsing resource space.
 8736:     if (($priv eq 'bro') && ($env{'user.author'})) {
 8737:         if ($uri eq '') {
 8738:             $ownaccess = 1;
 8739:         } else {
 8740:             if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
 8741:                 my $udom = $env{'user.domain'};
 8742:                 my $uname = $env{'user.name'};
 8743:                 if ($uri =~ m{^\Q$udom\E/?$}) {
 8744:                     $ownaccess = 1;
 8745:                 } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
 8746:                     unless ($uri =~ m{\.\./}) {
 8747:                         $ownaccess = 1;
 8748:                     }
 8749:                 } elsif (($udom ne 'public') && ($uname ne 'public')) {
 8750:                     my $now = time;
 8751:                     if ($uri =~ m{^([^/]+)/?$}) {
 8752:                         my $adom = $1;
 8753:                         foreach my $key (keys(%env)) {
 8754:                             if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
 8755:                                 my ($start,$end) = split(/\./,$env{$key});
 8756:                                 if (($now >= $start) && (!$end || $end > $now)) {
 8757:                                     $ownaccess = 1;
 8758:                                     last;
 8759:                                 }
 8760:                             }
 8761:                         }
 8762:                     } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
 8763:                         my $adom = $1;
 8764:                         my $aname = $2;
 8765:                         foreach my $role ('ca','aa') { 
 8766:                             if ($env{"user.role.$role./$adom/$aname"}) {
 8767:                                 my ($start,$end) =
 8768:                                     split(/\./,$env{"user.role.$role./$adom/$aname"});
 8769:                                 if (($now >= $start) && (!$end || $end > $now)) {
 8770:                                     $ownaccess = 1;
 8771:                                     last;
 8772:                                 }
 8773:                             }
 8774:                         }
 8775:                     }
 8776:                 }
 8777:             }
 8778:         }
 8779:     }
 8780: 
 8781: # Course
 8782: 
 8783:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
 8784:         unless (($priv eq 'bro') && (!$ownaccess)) {
 8785:             $thisallowed.=$1;
 8786:         }
 8787:     }
 8788: 
 8789: # Domain
 8790: 
 8791:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
 8792:        =~/\Q$priv\E\&([^\:]*)/) {
 8793:         unless (($priv eq 'bro') && (!$ownaccess)) {
 8794:             $thisallowed.=$1;
 8795:         }
 8796:     }
 8797: 
 8798: # User who is not author or co-author might still be able to edit
 8799: # resource of an author in the domain (e.g., if Domain Coordinator).
 8800:     if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
 8801:         (&allowed('mdc',$env{'request.course.id'}))) {
 8802:         if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
 8803:             $thisallowed.=$1;
 8804:         }
 8805:     }
 8806: 
 8807: # Course: uri itself is a course
 8808:     my $courseuri=$uri;
 8809:     $courseuri=~s/\_(\d)/\/$1/;
 8810:     $courseuri=~s/^([^\/])/\/$1/;
 8811: 
 8812:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
 8813:        =~/\Q$priv\E\&([^\:]*)/) {
 8814:         if ($priv eq 'mip') {
 8815:             my $rem = $1;
 8816:             if (($uri ne '') && ($env{'request.course.id'} eq $uri) &&
 8817:                 ($env{'course.'.$env{'request.course.id'}.'.internal.courseowner'} eq $env{'user.name'}.':'.$env{'user.domain'})) {
 8818:                 my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 8819:                 if ($cdom ne '') {
 8820:                     my %passwdconf = &get_passwdconf($cdom);
 8821:                     if (ref($passwdconf{'crsownerchg'}) eq 'HASH') {
 8822:                         if (ref($passwdconf{'crsownerchg'}{'by'}) eq 'ARRAY') {
 8823:                             if (@{$passwdconf{'crsownerchg'}{'by'}}) {
 8824:                                 my @inststatuses = split(':',$env{'environment.inststatus'});
 8825:                                 unless (@inststatuses) {
 8826:                                     @inststatuses = ('default');
 8827:                                 }
 8828:                                 foreach my $status (@inststatuses) {
 8829:                                     if (grep(/^\Q$status\E$/,@{$passwdconf{'crsownerchg'}{'by'}})) {
 8830:                                         $thisallowed.=$rem;
 8831:                                     }
 8832:                                 }
 8833:                             }
 8834:                         }
 8835:                     }
 8836:                 }
 8837:             }
 8838:         } else {
 8839:             unless (($priv eq 'bro') && (!$ownaccess)) {
 8840:                 $thisallowed.=$1;
 8841:             }
 8842:         }
 8843:     }
 8844: 
 8845: # URI is an uploaded document for this course, default permissions don't matter
 8846: # not allowing 'edit' access (editupload) to uploaded course docs
 8847:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
 8848: 	$thisallowed='';
 8849:         my ($match)=&is_on_map($uri);
 8850:         if ($match) {
 8851:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
 8852:                   =~/\Q$priv\E\&([^\:]*)/) {
 8853:                 my $value = $1;
 8854:                 my $deeplinkblock;
 8855:                 unless ($nodeeplinkcheck) {
 8856:                     $deeplinkblock = &deeplink_check($priv,$symb,$uri);
 8857:                 }
 8858:                 if ($deeplinkblock) {
 8859:                     $thisallowed='D';
 8860:                 } elsif ($noblockcheck) {
 8861:                     $thisallowed.=$value;
 8862:                 } else {
 8863:                     my @blockers = &has_comm_blocking($priv,$symb,$uri,$ignorecache);
 8864:                     if (@blockers > 0) {
 8865:                         $thisallowed = 'B';
 8866:                     } else {
 8867:                         $thisallowed.=$value;
 8868:                     }
 8869:                 }
 8870:             }
 8871:         } else {
 8872:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
 8873:             if ($refuri) {
 8874:                 if ($refuri =~ m|^/adm/|) {
 8875:                     $thisallowed='F';
 8876:                 } else {
 8877:                     $refuri=&declutter($refuri);
 8878:                     my ($match) = &is_on_map($refuri);
 8879:                     if ($match) {
 8880:                         my $deeplinkblock;
 8881:                         unless ($nodeeplinkcheck) {
 8882:                             $deeplinkblock = &deeplink_check($priv,$symb,$refuri);
 8883:                         }
 8884:                         if ($deeplinkblock) {
 8885:                             $thisallowed='D';
 8886:                         } elsif ($noblockcheck) {
 8887:                             $thisallowed='F';
 8888:                         } else {
 8889:                             my @blockers = &has_comm_blocking($priv,'',$refuri,'',1);
 8890:                             if (@blockers > 0) {
 8891:                                 $thisallowed = 'B';
 8892:                             } else {
 8893:                                 $thisallowed='F';
 8894:                             }
 8895:                         }
 8896:                     }
 8897:                 }
 8898:             }
 8899:         }
 8900:     }
 8901: 
 8902:     if ($priv eq 'bre'
 8903: 	&& $thisallowed ne 'F' 
 8904: 	&& $thisallowed ne '2'
 8905: 	&& &is_portfolio_url($uri)) {
 8906: 	$thisallowed = &portfolio_access($uri,$clientip);
 8907:     }
 8908: 
 8909: # Full access at system, domain or course-wide level? Exit.
 8910:     if ($thisallowed=~/F/) {
 8911: 	return 'F';
 8912:     }
 8913: 
 8914: # If this is generating or modifying users, exit with special codes
 8915: 
 8916:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:vca:vaa:'=~/\:\Q$priv\E\:/) {
 8917: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
 8918: 	    my ($audom,$auname)=split('/',$uri);
 8919: # no author name given, so this just checks on the general right to make a co-author in this domain
 8920: 	    unless ($auname) { return $thisallowed; }
 8921: # an author name is given, so we are about to actually make a co-author for a certain account
 8922: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
 8923: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
 8924: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
 8925: 	} elsif (($priv eq 'vca') || ($priv eq 'vaa')) {
 8926:             my ($audom,$auname)=split('/',$uri);
 8927:             unless ($auname) { return $thisallowed; }
 8928:             unless (($env{'request.role'} eq "dc./$audom") ||
 8929:                     ($env{'request.role'} eq "ca./$uri")) {
 8930:                 return '';
 8931:             }
 8932: 	}
 8933: 	return $thisallowed;
 8934:     }
 8935: #
 8936: # Gathered so far: system, domain and course wide privileges
 8937: #
 8938: # Course: See if uri or referer is an individual resource that is part of 
 8939: # the course
 8940: 
 8941:     if ($env{'request.course.id'}) {
 8942: 
 8943:         if ($priv eq 'bre') {
 8944:             if (&is_coursetool_logo($uri)) {
 8945:                 return 'F';
 8946:             }
 8947:         }
 8948: 
 8949: # If this is modifying password (internal auth) domains must match for user and user's role.
 8950: 
 8951:         if ($priv eq 'mip') {
 8952:             if ($env{'user.domain'} eq $env{'request.role.domain'}) {
 8953:                 return $thisallowed;
 8954:             } else {
 8955:                 return '';
 8956:             }
 8957:         }
 8958: 
 8959:        $courseprivid=$env{'request.course.id'};
 8960:        if ($env{'request.course.sec'}) {
 8961:           $courseprivid.='/'.$env{'request.course.sec'};
 8962:        }
 8963:        $courseprivid=~s/\_/\//;
 8964:        my $checkreferer=1;
 8965:        my ($match,$cond)=&is_on_map($uri);
 8966:        if ($match) {
 8967:            $statecond=$cond;
 8968:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 8969:                =~/\Q$priv\E\&([^\:]*)/) {
 8970:                my $value = $1;
 8971:                if ($priv eq 'bre') {
 8972:                    my $deeplinkblock;
 8973:                    unless ($nodeeplinkcheck) {
 8974:                        $deeplinkblock = &deeplink_check($priv,$symb,$uri);
 8975:                    }
 8976:                    if ($deeplinkblock) {
 8977:                        $thisallowed = 'D';
 8978:                    } elsif ($noblockcheck) {
 8979:                        $thisallowed.=$value;
 8980:                    } else {
 8981:                        my @blockers = &has_comm_blocking($priv,$symb,$uri,$ignorecache);
 8982:                        if (@blockers > 0) {
 8983:                            $thisallowed = 'B';
 8984:                        } else {
 8985:                            $thisallowed.=$value;
 8986:                        }
 8987:                    }
 8988:                } else {
 8989:                    $thisallowed.=$value;
 8990:                }
 8991:                $checkreferer=0;
 8992:            }
 8993:        }
 8994: 
 8995:        if ($checkreferer) {
 8996: 	  my $refuri=$env{'httpref.'.$orguri};
 8997:             unless ($refuri) {
 8998:                 foreach my $key (keys(%env)) {
 8999: 		    if ($key=~/^httpref\..*\*/) {
 9000: 			my $pattern=$key;
 9001:                         $pattern=~s/^httpref\.\/res\///;
 9002:                         $pattern=~s/\*/\[\^\/\]\+/g;
 9003:                         $pattern=~s/\//\\\//g;
 9004:                         if ($orguri=~/$pattern/) {
 9005: 			    $refuri=$env{$key};
 9006:                         }
 9007:                     }
 9008:                 }
 9009:             }
 9010: 
 9011:          if ($refuri) { 
 9012: 	  $refuri=&declutter($refuri);
 9013:           my ($match,$cond)=&is_on_map($refuri);
 9014:             if ($match) {
 9015:               my $refstatecond=$cond;
 9016:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 9017:                   =~/\Q$priv\E\&([^\:]*)/) {
 9018:                   my $value = $1;
 9019:                   if ($priv eq 'bre') {
 9020:                       my $deeplinkblock;
 9021:                       unless ($nodeeplinkcheck) {
 9022:                           $deeplinkblock = &deeplink_check($priv,$symb,$refuri);
 9023:                       }
 9024:                       if ($deeplinkblock) {
 9025:                           $thisallowed = 'D';
 9026:                       } elsif ($noblockcheck) {
 9027:                           $thisallowed.=$value;
 9028:                       } else {
 9029:                           my @blockers = &has_comm_blocking($priv,'',$refuri,'',1);
 9030:                           if (@blockers > 0) {
 9031:                               $thisallowed = 'B';
 9032:                           } else {
 9033:                               $thisallowed.=$value;
 9034:                           }
 9035:                       }
 9036:                   } else {
 9037:                       $thisallowed.=$value;
 9038:                   }
 9039:                   $uri=$refuri;
 9040:                   $statecond=$refstatecond;
 9041:               }
 9042:           }
 9043:         }
 9044:        }
 9045:    }
 9046: 
 9047: #
 9048: # Gathered now: all privileges that could apply, and condition number
 9049: # 
 9050: #
 9051: # Full or no access?
 9052: #
 9053: 
 9054:     if ($thisallowed=~/F/) {
 9055: 	return 'F';
 9056:     }
 9057: 
 9058:     unless ($thisallowed) {
 9059:         return '';
 9060:     }
 9061: 
 9062: # Restrictions exist, deal with them
 9063: #
 9064: #   C:according to course preferences
 9065: #   R:according to resource settings
 9066: #   L:unless locked
 9067: #   X:according to user session state
 9068: #
 9069: 
 9070: # Possibly locked functionality, check all courses
 9071: # In roles.tab, L (unless locked) available for bre, pch, plc, pac and sma.
 9072: # Locks might take effect only after 10 minutes cache expiration for other
 9073: # courses, and 2 minutes for current course, in which user has st or ta role
 9074: # which is neither expired nor a future role (unless current course).
 9075: 
 9076:     my ($needlockcheck,$now,$crsonly);
 9077:     if ($thisallowed=~/L/) {
 9078:         $now = time;
 9079:         if ($priv eq 'bre') {
 9080:             if ($uri ne '') {
 9081:                 if ($orguri =~ m{^/+res/}) {
 9082:                     if ($uri =~ m{^lib/templates/}) {
 9083:                         if ($env{'request.course.id'}) {
 9084:                             $crsonly = 1;
 9085:                             $needlockcheck = 1;
 9086:                         }
 9087:                     } else {
 9088:                         $needlockcheck = 1;
 9089:                     }
 9090:                 } elsif ($env{'request.course.id'}) {
 9091:                     my ($crsdom,$crsnum) = split('_',$env{'request.course.id'});
 9092:                     if (($uri =~ m{^(adm|uploaded|public)/$crsdom/$crsnum/}) ||
 9093:                         ($uri =~ m{^adm/$match_domain/$match_username/\d+/(smppg|bulletinboard)$})) {
 9094:                         $crsonly = 1;
 9095:                     }
 9096:                     $needlockcheck = 1;
 9097:                 }
 9098:             }
 9099:         } elsif (($priv eq 'pch') || ($priv eq 'plc') || ($priv eq 'pac') || ($priv eq 'sma')) {
 9100:             $needlockcheck = 1;
 9101:         }
 9102:     }
 9103:     if ($needlockcheck) {
 9104:         foreach my $envkey (keys(%env)) {
 9105:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
 9106:                my $courseid=$2;
 9107:                my $roleid=$1.'.'.$2;
 9108:                $courseid=~s/^\///;
 9109:                unless ($env{'request.role'} eq $roleid) {
 9110:                    my ($start,$end) = split(/\./,$env{$envkey});
 9111:                    next unless (($now >= $start) && (!$end || $end > $now));
 9112:                }
 9113:                my $expiretime=600;
 9114:                if ($env{'request.role'} eq $roleid) {
 9115: 		  $expiretime=120;
 9116:                }
 9117: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
 9118:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
 9119:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
 9120: 		   &coursedescription($courseid,{'freshen_cache' => 1});
 9121:                }
 9122:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
 9123:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
 9124: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
 9125:                        &log($env{'user.domain'},$env{'user.name'},
 9126:                             $env{'user.home'},
 9127:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
 9128:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 9129:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 9130: 		       return '';
 9131:                    }
 9132:                }
 9133:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
 9134:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
 9135: 		   if ($env{$prefix.'priv.'.$priv.'.lock.expire'}>time) {
 9136:                        &log($env{'user.domain'},$env{'user.name'},
 9137:                             $env{'user.home'},
 9138:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
 9139:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 9140:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 9141: 		       return '';
 9142:                    }
 9143:                }
 9144: 	   }
 9145:        }
 9146:     }
 9147: 
 9148: #
 9149: # Rest of the restrictions depend on selected course
 9150: #
 9151: 
 9152:     unless ($env{'request.course.id'}) {
 9153: 	if ($thisallowed eq 'A') {
 9154: 	    return 'A';
 9155:         } elsif ($thisallowed eq 'B') {
 9156:             return 'B';
 9157: 	} else {
 9158: 	    return '1';
 9159: 	}
 9160:     }
 9161: 
 9162: #
 9163: # Now user is definitely in a course
 9164: #
 9165: 
 9166: 
 9167: # Course preferences
 9168: 
 9169:    if ($thisallowed=~/C/) {
 9170:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 9171:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
 9172:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
 9173: 	   =~/\Q$rolecode\E/) {
 9174: 	   if (($priv ne 'pch') && ($priv ne 'plc') && ($priv ne 'pac')) {
 9175: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 9176: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
 9177: 			$env{'request.course.id'});
 9178: 	   }
 9179:            return '';
 9180:        }
 9181: 
 9182:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
 9183: 	   =~/\Q$unamedom\E/) {
 9184: 	   if (($priv ne 'pch') && ($priv ne 'plc') && ($priv ne 'pac')) {
 9185: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
 9186: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
 9187: 			$env{'request.course.id'});
 9188: 	   }
 9189:            return '';
 9190:        }
 9191:    }
 9192: 
 9193: # Resource preferences
 9194: 
 9195:    if ($thisallowed=~/R/) {
 9196:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 9197:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
 9198: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
 9199: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 9200: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
 9201: 	   }
 9202: 	   return '';
 9203:        }
 9204:    }
 9205: 
 9206: # Restricted for deeplinked session?
 9207: 
 9208:     if ($env{'request.deeplink.login'}) {
 9209:         if ($env{'acc.deeplinkout'} && !$nodeeplinkout) {
 9210:             if (!$symb) { $symb=&symbread($uri,1); }
 9211:             if (($symb) && ($env{'acc.deeplinkout'}=~/\&\Q$symb\E\&/)) {
 9212:                 return '';
 9213:             }
 9214:         }
 9215:     }
 9216: 
 9217: # Restricted by state or randomout?
 9218: 
 9219:    if ($thisallowed=~/X/) {
 9220:       if ($env{'acc.randomout'}) {
 9221: 	 if (!$symb) { $symb=&symbread($uri,1); }
 9222:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
 9223:             return ''; 
 9224:          }
 9225:       }
 9226:       if (&condval($statecond)) {
 9227: 	 return '2';
 9228:       } else {
 9229:          return '';
 9230:       }
 9231:    }
 9232: 
 9233:     if ($thisallowed eq 'A') {
 9234: 	return 'A';
 9235:     } elsif ($thisallowed eq 'B') {
 9236:         return 'B';
 9237:     } elsif ($thisallowed eq 'D') {
 9238:         return 'D';
 9239:     }
 9240:    return 'F';
 9241: }
 9242: 
 9243: # ------------------------------------------- Check construction space access
 9244: 
 9245: sub constructaccess {
 9246:     my ($url,$setpriv)=@_;
 9247: 
 9248: # We do not allow editing of previous versions of files
 9249:     if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
 9250: 
 9251: # Get username and domain from URL
 9252:     my ($ownername,$ownerdomain,$ownerhome);
 9253: 
 9254:     ($ownerdomain,$ownername) =
 9255:         ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)(?:/daxepage|/daxeopen)?/priv/($match_domain)/($match_username)(?:/|$)});
 9256: 
 9257: # The URL does not really point to any authorspace, forget it
 9258:     unless (($ownername) && ($ownerdomain)) { return ''; }
 9259: 
 9260: # Now we need to see if the user has access to the authorspace of
 9261: # $ownername at $ownerdomain
 9262: 
 9263:     if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
 9264: # Real author for this?
 9265:        $ownerhome = $env{'user.home'};
 9266:        if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
 9267:           return ($ownername,$ownerdomain,$ownerhome);
 9268:        }
 9269:     } elsif (&is_course($ownerdomain,$ownername)) {
 9270: # Course Authoring Space?
 9271:         if ($env{'request.course.id'}) {
 9272:             if (($ownername eq $env{'course.'.$env{'request.course.id'}.'.num'}) &&
 9273:                 ($ownerdomain eq $env{'course.'.$env{'request.course.id'}.'.domain'})) {
 9274:                 if (&allowed('mdc',$env{'request.course.id'})) {
 9275:                     return if ($env{'course.'.$env{'request.course.id'}.'.internal.crsauthor'} eq '0');
 9276:                     unless ($env{'course.'.$env{'request.course.id'}.'.internal.crsauthor'}) {
 9277:                         my %domdefs = &get_domain_defaults($ownerdomain);
 9278:                         my $type = lc($env{'course.'.$env{'request.course.id'}.'.type'});
 9279:                         unless (($type eq 'community') || ($type eq 'placement')) {
 9280:                             $type = 'unofficial';
 9281:                             if ($env{'course.'.$env{'request.course.id'}.'internal.coursecode'} ne '') {
 9282:                                 $type = 'official';
 9283:                             } elsif ($env{'course.'.$env{'request.course.id'}.'internal.textbook'} ne '') {
 9284:                                 $type = 'textbook';
 9285:                             } else {
 9286:                                 $type = 'unofficial';
 9287:                             }
 9288:                         }
 9289:                         return if ($domdefs{$type.'crsauthor'} eq '0');
 9290:                     }
 9291:                     $ownerhome = $env{'course.'.$env{'request.course.id'}.'.home'};
 9292:                     return ($ownername,$ownerdomain,$ownerhome);
 9293:                 }
 9294:             }
 9295:         }
 9296:         return '';
 9297:     } else {
 9298: # Co-author for this?
 9299:         if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
 9300:             exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
 9301:             $ownerhome = &homeserver($ownername,$ownerdomain);
 9302:             return ($ownername,$ownerdomain,$ownerhome);
 9303:         }
 9304:     }
 9305: 
 9306: # We don't have any access right now. If we are not possibly going to do anything about this,
 9307: # we might as well leave
 9308:    unless ($setpriv) { return ''; }
 9309: 
 9310: # Backdoor access?
 9311:     my $allowed=&allowed('eco',$ownerdomain);
 9312: # Nope
 9313:     unless ($allowed) { return ''; }
 9314: # Looks like we may have access, but could be locked by the owner of the construction space
 9315:     if ($allowed eq 'U') {
 9316:         my %blocked=&get('environment',['domcoord.author'],
 9317:                          $ownerdomain,$ownername);
 9318: # Is blocked by owner
 9319:         if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
 9320:     }
 9321:     if (($allowed eq 'F') || ($allowed eq 'U')) {
 9322: # Grant temporary access
 9323:         my $then=$env{'user.login.time'};
 9324:         my $update=$env{'user.update.time'};
 9325:         if (!$update) { $update = $then; }
 9326:         my $refresh=$env{'user.refresh.time'};
 9327:         if (!$refresh) { $refresh = $update; }
 9328:         my $now = time;
 9329:         &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
 9330:                            $now,'ca','constructaccess');
 9331:         $ownerhome = &homeserver($ownername,$ownerdomain);
 9332:         return($ownername,$ownerdomain,$ownerhome);
 9333:     }
 9334: # No business here
 9335:     return '';
 9336: }
 9337: 
 9338: # ----------------------------------------------------------- Content Blocking
 9339: 
 9340: {
 9341: # Caches for faster Course Contents display where content blocking
 9342: # is in operation (i.e., interval param set) for timed quiz.
 9343: #
 9344: # User for whom data are being temporarily cached.
 9345: my $cacheduser='';
 9346: # Course for which data are being temporarily cached.
 9347: my $cachedcid='';
 9348: # Cached blockers for this user (a hash of blocking items). 
 9349: my %cachedblockers=();
 9350: # When the data were last cached.
 9351: my $cachedlast='';
 9352: 
 9353: sub load_all_blockers {
 9354:     my ($uname,$udom)=@_;
 9355:     if (($uname ne '') && ($udom ne '')) { 
 9356:         if (($cacheduser eq $uname.':'.$udom) &&
 9357:             ($cachedcid eq $env{'request.course.id'}) &&
 9358:             (abs($cachedlast-time)<5)) {
 9359:             return;
 9360:         }
 9361:     }
 9362:     $cachedlast=time;
 9363:     $cacheduser=$uname.':'.$udom;
 9364:     $cachedcid=$env{'request.course.id'};
 9365:     %cachedblockers = &get_commblock_resources();
 9366:     return;
 9367: }
 9368: 
 9369: sub get_comm_blocks {
 9370:     my ($cdom,$cnum) = @_;
 9371:     if ($cdom eq '' || $cnum eq '') {
 9372:         return unless ($env{'request.course.id'});
 9373:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 9374:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 9375:     }
 9376:     my %commblocks;
 9377:     my $hashid=$cdom.'_'.$cnum;
 9378:     my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
 9379:     if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
 9380:         %commblocks = %{$blocksref};
 9381:     } else {
 9382:         %commblocks = &dump('comm_block',$cdom,$cnum);
 9383:         my $cachetime = 600;
 9384:         &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
 9385:     }
 9386:     return %commblocks;
 9387: }
 9388: 
 9389: sub get_commblock_resources {
 9390:     my ($blocks) = @_;
 9391:     my %blockers = ();
 9392:     return %blockers unless ($env{'request.course.id'});
 9393:     my $courseurl = &courseid_to_courseurl($env{'request.course.id'});
 9394:     if ($env{'request.course.sec'}) {
 9395:         $courseurl .= '/'.$env{'request.course.sec'};
 9396:     }
 9397:     return %blockers if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseurl} =~/evb\&([^\:]*)/);
 9398:     my %commblocks;
 9399:     if (ref($blocks) eq 'HASH') {
 9400:         %commblocks = %{$blocks};
 9401:     } else {
 9402:         %commblocks = &get_comm_blocks();
 9403:     }
 9404:     return %blockers unless (keys(%commblocks) > 0); 
 9405:     my $navmap = Apache::lonnavmaps::navmap->new();
 9406:     return %blockers unless (ref($navmap));
 9407:     my $now = time;
 9408:     foreach my $block (keys(%commblocks)) {
 9409:         if ($block =~ /^(\d+)____(\d+)$/) {
 9410:             my ($start,$end) = ($1,$2);
 9411:             if ($start <= $now && $end >= $now) {
 9412:                 if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
 9413:                     if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
 9414:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
 9415:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
 9416:                                 $blockers{$block}{maps} = $commblocks{$block}{'blocks'}{'docs'}{'maps'}; 
 9417:                             }
 9418:                         }
 9419:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
 9420:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
 9421:                                 $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
 9422:                             }
 9423:                         }
 9424:                     }
 9425:                 }
 9426:             }
 9427:         } elsif ($block =~ /^firstaccess____(.+)$/) {
 9428:             my $item = $1;
 9429:             if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
 9430:                 if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
 9431:                     my (@interval,$mapname);
 9432:                     my $type = 'map';
 9433:                     if ($item eq 'course') {
 9434:                         $type = 'course';
 9435:                         @interval=&EXT("resource.0.interval");
 9436:                     } else {
 9437:                         if ($item =~ /___\d+___/) {
 9438:                             $type = 'resource';
 9439:                             @interval=&EXT("resource.0.interval",$item);
 9440:                         } else {
 9441:                             $mapname = &deversion($item);
 9442:                             if (ref($navmap)) {
 9443:                                 my $timelimit = $navmap->get_mapparam(undef,$mapname,'0.interval');
 9444:                                 @interval = ($timelimit,'map');
 9445:                             }
 9446:                         }
 9447:                     }
 9448:                     if ($interval[0] =~ /^(\d+)/) {
 9449:                         my $timelimit = $1; 
 9450:                         my $first_access;
 9451:                         if ($type eq 'resource') {
 9452:                             $first_access=&get_first_access($interval[1],$item);
 9453:                         } elsif ($type eq 'map') {
 9454:                             $first_access=&get_first_access($interval[1],undef,$item);
 9455:                         } else {
 9456:                             $first_access=&get_first_access($interval[1]);
 9457:                         }
 9458:                         if ($first_access) {
 9459:                             my $timesup = $first_access+$timelimit;
 9460:                             if ($timesup > $now) {
 9461:                                 my $activeblock;
 9462:                                 if ($type eq 'resource') {
 9463:                                     if (ref($navmap)) {
 9464:                                         my $res = $navmap->getBySymb($item);
 9465:                                         if ($res->answerable()) {
 9466:                                             $activeblock = 1;
 9467:                                         }
 9468:                                     }
 9469:                                 } elsif ($type eq 'map') {
 9470:                                     my $mapsymb = &symbread($mapname,1);
 9471:                                     if (($mapsymb) && (ref($navmap))) {
 9472:                                         my $mapres = $navmap->getBySymb($mapsymb);
 9473:                                         if (ref($mapres)) {
 9474:                                             my $first = $mapres->map_start();
 9475:                                             my $finish = $mapres->map_finish();
 9476:                                             my $it = $navmap->getIterator($first,$finish,undef,0,0);
 9477:                                             if (ref($it)) {
 9478:                                                 my $res;
 9479:                                                 while ($res = $it->next(undef,1)) {
 9480:                                                     next unless (ref($res));
 9481:                                                     my $symb = $res->symb();
 9482:                                                     next if (($symb eq $mapsymb) || ($symb eq ''));
 9483:                                                     @interval=&EXT("resource.0.interval",$symb);
 9484:                                                     if ($interval[1] eq 'map') {
 9485:                                                         if ($res->answerable()) {
 9486:                                                             $activeblock = 1;
 9487:                                                             last;
 9488:                                                         }
 9489:                                                     }
 9490:                                                 }
 9491:                                             }
 9492:                                         }
 9493:                                     }
 9494:                                 }
 9495:                                 if ($activeblock) {
 9496:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
 9497:                                          if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
 9498:                                              $blockers{$block}{'maps'} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
 9499:                                          }
 9500:                                     }
 9501:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
 9502:                                         if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
 9503:                                             $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
 9504:                                         }
 9505:                                     }
 9506:                                 }
 9507:                             }
 9508:                         }
 9509:                     }
 9510:                 }
 9511:             }
 9512:         }
 9513:     }
 9514:     return %blockers;
 9515: }
 9516: 
 9517: sub has_comm_blocking {
 9518:     my ($priv,$symb,$uri,$ignoresymbdb,$noenccheck,$blocked,$blocks) = @_;
 9519:     my @blockers;
 9520:     return unless ($env{'request.course.id'});
 9521:     return unless ($priv eq 'bre');
 9522:     return if ($env{'request.state'} eq 'construct');
 9523:     my $courseurl = &courseid_to_courseurl($env{'request.course.id'});
 9524:     if ($env{'request.course.sec'}) {
 9525:         $courseurl .= '/'.$env{'request.course.sec'};
 9526:     }
 9527:     return if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseurl} =~/evb\&([^\:]*)/);
 9528:     my %blockinfo;
 9529:     if (ref($blocks) eq 'HASH') {
 9530:         %blockinfo = &get_commblock_resources($blocks);
 9531:     } else {
 9532:         &load_all_blockers($env{'user.name'},$env{'user.domain'});
 9533:         %blockinfo = %cachedblockers;
 9534:     }
 9535:     return unless (keys(%blockinfo) > 0);
 9536:     my (%possibles,@symbs);
 9537:     if (!$symb) {
 9538:         $symb = &symbread($uri,1,1,1,\%possibles,$ignoresymbdb,$noenccheck);
 9539:     }
 9540:     if ($symb) {
 9541:         @symbs = ($symb);
 9542:     } elsif (keys(%possibles)) { 
 9543:         @symbs = keys(%possibles);
 9544:     }
 9545:     my $noblock;
 9546:     foreach my $symb (@symbs) {
 9547:         last if ($noblock);
 9548:         my ($map,$resid,$resurl)=&decode_symb($symb);
 9549:         foreach my $block (keys(%blockinfo)) {
 9550:             if ($block =~ /^firstaccess____(.+)$/) {
 9551:                 my $item = $1;
 9552:                 unless ($blocked) {
 9553:                     if (($item eq $map) || ($item eq $symb)) {
 9554:                         $noblock = 1;
 9555:                         last;
 9556:                     }
 9557:                 }
 9558:             }
 9559:             if (ref($blockinfo{$block}) eq 'HASH') {
 9560:                 if (ref($blockinfo{$block}{'resources'}) eq 'HASH') {
 9561:                     if ($blockinfo{$block}{'resources'}{$symb}) {
 9562:                         unless (grep(/^\Q$block\E$/,@blockers)) {
 9563:                             push(@blockers,$block);
 9564:                         }
 9565:                     }
 9566:                 }
 9567:                 if (ref($blockinfo{$block}{'maps'}) eq 'HASH') {
 9568:                     if ($blockinfo{$block}{'maps'}{$map}) {
 9569:                         unless (grep(/^\Q$block\E$/,@blockers)) {
 9570:                             push(@blockers,$block);
 9571:                         }
 9572:                     }
 9573:                 }
 9574:             }
 9575:         }
 9576:     }
 9577:     unless ($noblock) { 
 9578:         return @blockers;
 9579:     }
 9580:     return;
 9581: }
 9582: }
 9583: 
 9584: sub deeplink_check {
 9585:     my ($priv,$symb,$uri) = @_;
 9586:     return unless ($env{'request.course.id'});
 9587:     return unless ($priv eq 'bre');
 9588:     return if ($env{'request.state'} eq 'construct');
 9589:     return if ($env{'request.role.adv'});
 9590:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 9591:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 9592:     my (%possibles,@symbs);
 9593:     if (!$symb) {
 9594:         $symb = &symbread($uri,1,1,1,\%possibles);
 9595:     }
 9596:     if ($symb) {
 9597:         @symbs = ($symb);
 9598:     } elsif (keys(%possibles)) {
 9599:         @symbs = keys(%possibles);
 9600:     }
 9601: 
 9602:     my ($deeplink_symb,$allow);
 9603:     if ($env{'request.deeplink.login'}) {
 9604:         $deeplink_symb = &Apache::loncommon::deeplink_login_symb($cnum,$cdom);
 9605:     }
 9606:     foreach my $symb (@symbs) {
 9607:         last if ($allow);
 9608:         my $deeplink = &EXT("resource.0.deeplink",$symb);
 9609:         if ($deeplink eq '') {
 9610:             $allow = 1;
 9611:         } else {
 9612:             my ($state,$others,$listed,$scope,$protect) = split(/,/,$deeplink);
 9613:             if ($state ne 'only') {
 9614:                 $allow = 1;
 9615:             } else {
 9616:                 my $check_deeplink_entry;
 9617:                 if ($protect ne 'none') {
 9618:                     my ($acctype,$item) = split(/:/,$protect);
 9619:                     if (($acctype eq 'ltic') && ($env{'user.linkprotector'})) {
 9620:                         if (grep(/^\Q$item\Ec$/,split(/,/,$env{'user.linkprotector'}))) {
 9621:                             $check_deeplink_entry = 1
 9622:                         }
 9623:                     } elsif (($acctype eq 'ltid') && ($env{'user.linkprotector'})) {
 9624:                         if (grep(/^\Q$item\Ed$/,split(/,/,$env{'user.linkprotector'}))) {
 9625:                             $check_deeplink_entry = 1;
 9626:                         }
 9627:                     } elsif (($acctype eq 'key') && ($env{'user.deeplinkkey'})) {
 9628:                         if (grep(/^\Q$item\E$/,split(/,/,$env{'user.deeplinkkey'}))) {
 9629:                             $check_deeplink_entry = 1;
 9630:                         }
 9631:                     }
 9632:                 }
 9633:                 if (($protect eq 'none') || ($check_deeplink_entry)) {
 9634:                     if ($scope eq 'res') {
 9635:                         if ($symb eq $deeplink_symb) {
 9636:                             $allow = 1;
 9637:                         }
 9638:                     } elsif (($scope eq 'map') || ($scope eq 'rec')) {
 9639:                         my ($map_from_symb,$map_from_login);
 9640:                         $map_from_symb = &deversion((&decode_symb($symb))[0]);
 9641:                         if ($deeplink_symb =~ /\.(page|sequence)$/) {
 9642:                             $map_from_login = &deversion((&decode_symb($deeplink_symb))[2]);
 9643:                         } else {
 9644:                             $map_from_login = &deversion((&decode_symb($deeplink_symb))[0]);
 9645:                         }
 9646:                         if (($map_from_symb) && ($map_from_login)) {
 9647:                             if ($map_from_symb eq $map_from_login) {
 9648:                                 $allow = 1;
 9649:                             } elsif ($scope eq 'rec') {
 9650:                                 my @recurseup = &get_map_hierarchy($map_from_symb,$env{'request.course.id'});
 9651:                                 if (grep(/^\Q$map_from_login\E$/,@recurseup)) {
 9652:                                     $allow = 1;
 9653:                                 }
 9654:                             }
 9655:                         }
 9656:                     }
 9657:                 }
 9658:             }
 9659:         }
 9660:     }
 9661:     return if ($allow);
 9662:     return 1;
 9663: }
 9664: 
 9665: # -------------------------------- Deversion and split uri into path an filename   
 9666: 
 9667: #
 9668: #   Removes the version from a URI and
 9669: #   splits it in to its filename and path to the filename.
 9670: #   Seems like File::Basename could have done this more clearly.
 9671: #   Parameters:
 9672: #      $uri   - input URI
 9673: #   Returns:
 9674: #     Two element list consisting of 
 9675: #     $pathname  - the URI up to and excluding the trailing /
 9676: #     $filename  - The part of the URI following the last /
 9677: #  NOTE:
 9678: #    Another realization of this is simply:
 9679: #    use File::Basename;
 9680: #    ...
 9681: #    $uri = shift;
 9682: #    $filename = basename($uri);
 9683: #    $path     = dirname($uri);
 9684: #    return ($filename, $path);
 9685: #
 9686: #     The implementation below is probably faster however.
 9687: #
 9688: sub split_uri_for_cond {
 9689:     my $uri=&deversion(&declutter(shift));
 9690:     my @uriparts=split(/\//,$uri);
 9691:     my $filename=pop(@uriparts);
 9692:     my $pathname=join('/',@uriparts);
 9693:     return ($pathname,$filename);
 9694: }
 9695: # --------------------------------------------------- Is a resource on the map?
 9696: 
 9697: sub is_on_map {
 9698:     my ($pathname,$filename) = &split_uri_for_cond(shift);
 9699:     #Trying to find the conditional for the file
 9700:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
 9701: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
 9702:     if ($match) {
 9703: 	return (1,$1);
 9704:     } else {
 9705: 	return (0,0);
 9706:     }
 9707: }
 9708: 
 9709: # --------------------------------------------------------- Get symb from alias
 9710: 
 9711: sub get_symb_from_alias {
 9712:     my $symb=shift;
 9713:     my ($map,$resid,$url)=&decode_symb($symb);
 9714: # Already is a symb
 9715:     if ($url) { return $symb; }
 9716: # Must be an alias
 9717:     my $aliassymb='';
 9718:     my %bighash;
 9719:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 9720:                             &GDBM_READER(),0640)) {
 9721:         my $rid=$bighash{'mapalias_'.$symb};
 9722: 	if ($rid) {
 9723: 	    my ($mapid,$resid)=split(/\./,$rid);
 9724: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
 9725: 				    $resid,$bighash{'src_'.$rid});
 9726: 	}
 9727:         untie %bighash;
 9728:     }
 9729:     return $aliassymb;
 9730: }
 9731: 
 9732: # ----------------------------------------------------------------- Define Role
 9733: 
 9734: sub definerole {
 9735:   if (allowed('mcr','/')) {
 9736:     my ($rolename,$sysrole,$domrole,$courole,$uname,$udom)=@_;
 9737:     foreach my $role (split(':',$sysrole)) {
 9738: 	my ($crole,$cqual)=split(/\&/,$role);
 9739:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
 9740:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
 9741: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 9742:                return "refused:s:$crole&$cqual"; 
 9743:             }
 9744:         }
 9745:     }
 9746:     foreach my $role (split(':',$domrole)) {
 9747: 	my ($crole,$cqual)=split(/\&/,$role);
 9748:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
 9749:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
 9750: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
 9751:                return "refused:d:$crole&$cqual"; 
 9752:             }
 9753:         }
 9754:     }
 9755:     foreach my $role (split(':',$courole)) {
 9756: 	my ($crole,$cqual)=split(/\&/,$role);
 9757:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
 9758:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
 9759: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 9760:                return "refused:c:$crole&$cqual"; 
 9761:             }
 9762:         }
 9763:     }
 9764:     my $uhome;
 9765:     if (($uname ne '') && ($udom ne '')) {
 9766:         $uhome = &homeserver($uname,$udom);
 9767:         return $uhome if ($uhome eq 'no_host');
 9768:     } else {
 9769:         $uname = $env{'user.name'};
 9770:         $udom = $env{'user.domain'};
 9771:         $uhome = $env{'user.home'};
 9772:     }
 9773:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
 9774:                 "$udom:$uname:rolesdef_$rolename=".
 9775:                 escape($sysrole.'_'.$domrole.'_'.$courole);
 9776:     return reply($command,$uhome);
 9777:   } else {
 9778:     return 'refused';
 9779:   }
 9780: }
 9781: 
 9782: # ---------------- Make a metadata query against the network of library servers
 9783: 
 9784: sub metadata_query {
 9785:     my ($query,$custom,$customshow,$server_array,$domains_hash)=@_;
 9786:     my %rhash;
 9787:     my %libserv = &all_library();
 9788:     my @server_list = (defined($server_array) ? @$server_array
 9789:                                               : keys(%libserv) );
 9790:     for my $server (@server_list) {
 9791:         my $domains = ''; 
 9792:         if (ref($domains_hash) eq 'HASH') {
 9793:             $domains = $domains_hash->{$server}; 
 9794:         }
 9795: 	unless ($custom or $customshow) {
 9796: 	    my $reply=&reply("querysend:".&escape($query).':::'.&escape($domains),$server);
 9797: 	    $rhash{$server}=$reply;
 9798: 	}
 9799: 	else {
 9800: 	    my $reply=&reply("querysend:".&escape($query).':'.
 9801: 			     &escape($custom).':'.&escape($customshow).':'.&escape($domains),
 9802: 			     $server);
 9803: 	    $rhash{$server}=$reply;
 9804: 	}
 9805:     }
 9806:     return \%rhash;
 9807: }
 9808: 
 9809: # ----------------------------------------- Send log queries and wait for reply
 9810: 
 9811: sub log_query {
 9812:     my ($uname,$udom,$query,%filters)=@_;
 9813:     my $uhome=&homeserver($uname,$udom);
 9814:     if ($uhome eq 'no_host') { return 'error: no_host'; }
 9815:     my $uhost=&hostname($uhome);
 9816:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
 9817:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
 9818:                        $uhome);
 9819:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
 9820:     return get_query_reply($queryid);
 9821: }
 9822: 
 9823: # -------------------------- Update MySQL table for portfolio file
 9824: 
 9825: sub update_portfolio_table {
 9826:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
 9827:     if ($group ne '') {
 9828:         $file_name =~s /^\Q$group\E//;
 9829:     }
 9830:     my $homeserver = &homeserver($uname,$udom);
 9831:     my $queryid=
 9832:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
 9833:                ':'.&escape($file_name).':'.$action,$homeserver);
 9834:     my $reply = &get_query_reply($queryid);
 9835:     return $reply;
 9836: }
 9837: 
 9838: # -------------------------- Update MySQL allusers table
 9839: 
 9840: sub update_allusers_table {
 9841:     my ($uname,$udom,$names) = @_;
 9842:     my $homeserver = &homeserver($uname,$udom);
 9843:     my $queryid=
 9844:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
 9845:                'lastname='.&escape($names->{'lastname'}).'%%'.
 9846:                'firstname='.&escape($names->{'firstname'}).'%%'.
 9847:                'middlename='.&escape($names->{'middlename'}).'%%'.
 9848:                'generation='.&escape($names->{'generation'}).'%%'.
 9849:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
 9850:                'id='.&escape($names->{'id'}),$homeserver);
 9851:     return;
 9852: }
 9853: 
 9854: # ------- Request retrieval of institutional classlists for course(s)
 9855: 
 9856: sub fetch_enrollment_query {
 9857:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
 9858:     my ($homeserver,$sleep,$loopmax);
 9859:     my $maxtries = 1;
 9860:     if ($context eq 'automated') {
 9861:         $homeserver = $perlvar{'lonHostID'};
 9862:         $sleep = 2;
 9863:         $loopmax = 100;
 9864:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
 9865:     } else {
 9866:         $homeserver = &homeserver($cnum,$dom);
 9867:     }
 9868:     my $host=&hostname($homeserver);
 9869:     my $cmd = '';
 9870:     foreach my $affiliate (keys(%{$affiliatesref})) {
 9871:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
 9872:     }
 9873:     $cmd =~ s/%%$//;
 9874:     $cmd = &escape($cmd);
 9875:     my $query = 'fetchenrollment';
 9876:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
 9877:     unless ($queryid=~/^\Q$host\E\_/) { 
 9878:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
 9879:         return 'error: '.$queryid;
 9880:     }
 9881:     my $reply = &get_query_reply($queryid,$sleep,$loopmax);
 9882:     my $tries = 1;
 9883:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 9884:         $reply = &get_query_reply($queryid,$sleep,$loopmax);
 9885:         $tries ++;
 9886:     }
 9887:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 9888:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 9889:     } else {
 9890:         my @responses = split(/:/,$reply);
 9891:         if (grep { $_ eq $homeserver } &current_machine_ids()) {
 9892:             foreach my $line (@responses) {
 9893:                 my ($key,$value) = split(/=/,$line,2);
 9894:                 $$replyref{$key} = $value;
 9895:             }
 9896:         } else {
 9897:             my $pathname = LONCAPA::tempdir();
 9898:             foreach my $line (@responses) {
 9899:                 my ($key,$value) = split(/=/,$line);
 9900:                 $$replyref{$key} = $value;
 9901:                 if ($value > 0) {
 9902:                     foreach my $item (@{$$affiliatesref{$key}}) {
 9903:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
 9904:                         my $destname = $pathname.'/'.$filename;
 9905:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
 9906:                         if ($xml_classlist =~ /^error/) {
 9907:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
 9908:                         } else {
 9909:                             if ( open(FILE,">",$destname) ) {
 9910:                                 print FILE &unescape($xml_classlist);
 9911:                                 close(FILE);
 9912:                             } else {
 9913:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
 9914:                             }
 9915:                         }
 9916:                     }
 9917:                 }
 9918:             }
 9919:         }
 9920:         return 'ok';
 9921:     }
 9922:     return 'error';
 9923: }
 9924: 
 9925: sub get_query_reply {
 9926:     my ($queryid,$sleep,$loopmax) = @_;
 9927:     if (($sleep eq '') || ($sleep !~ /^\d+\.?\d*$/)) {
 9928:         $sleep = 0.2;
 9929:     }
 9930:     if (($loopmax eq '') || ($loopmax =~ /\D/)) {
 9931:         $loopmax = 100;
 9932:     }
 9933:     my $replyfile=LONCAPA::tempdir().$queryid;
 9934:     my $reply='';
 9935:     for (1..$loopmax) {
 9936: 	sleep($sleep);
 9937:         if (-e $replyfile.'.end') {
 9938: 	    if (open(my $fh,"<",$replyfile)) {
 9939: 		$reply = join('',<$fh>);
 9940: 		close($fh);
 9941: 	   } else { return 'error: reply_file_error'; }
 9942:            return &unescape($reply);
 9943: 	}
 9944:     }
 9945:     return 'timeout:'.$queryid;
 9946: }
 9947: 
 9948: sub courselog_query {
 9949: #
 9950: # possible filters:
 9951: # url: url or symb
 9952: # username
 9953: # domain
 9954: # action: view, submit, grade
 9955: # start: timestamp
 9956: # end: timestamp
 9957: #
 9958:     my (%filters)=@_;
 9959:     unless ($env{'request.course.id'}) { return 'no_course'; }
 9960:     if ($filters{'url'}) {
 9961: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
 9962:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
 9963:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
 9964:     }
 9965:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 9966:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 9967:     return &log_query($cname,$cdom,'courselog',%filters);
 9968: }
 9969: 
 9970: sub userlog_query {
 9971: #
 9972: # possible filters:
 9973: # action: log check role
 9974: # start: timestamp
 9975: # end: timestamp
 9976: #
 9977:     my ($uname,$udom,%filters)=@_;
 9978:     return &log_query($uname,$udom,'userlog',%filters);
 9979: }
 9980: 
 9981: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
 9982: 
 9983: sub auto_run {
 9984:     my ($cnum,$cdom) = @_;
 9985:     my $response = 0;
 9986:     my $settings;
 9987:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
 9988:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
 9989:         $settings = $domconfig{'autoenroll'};
 9990:         if ($settings->{'run'} eq '1') {
 9991:             $response = 1;
 9992:         }
 9993:     } else {
 9994:         my $homeserver;
 9995:         if (&is_course($cdom,$cnum)) {
 9996:             $homeserver = &homeserver($cnum,$cdom);
 9997:         } else {
 9998:             $homeserver = &domain($cdom,'primary');
 9999:         }
10000:         if ($homeserver ne 'no_host') {
10001:             $response = &reply('autorun:'.$cdom,$homeserver);
10002:         }
10003:     }
10004:     return $response;
10005: }
10006: 
10007: sub auto_get_sections {
10008:     my ($cnum,$cdom,$inst_coursecode) = @_;
10009:     my $homeserver;
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:     my @secs;
10019:     if (defined($homeserver)) {
10020:         my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
10021:         unless ($response eq 'refused') {
10022:             @secs = split(/:/,$response);
10023:         }
10024:     }
10025:     return @secs;
10026: }
10027: 
10028: sub auto_new_course {
10029:     my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
10030:     my $homeserver = &homeserver($cnum,$cdom);
10031:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
10032:     return $response;
10033: }
10034: 
10035: sub auto_validate_courseID {
10036:     my ($cnum,$cdom,$inst_course_id) = @_;
10037:     my $homeserver = &homeserver($cnum,$cdom);
10038:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
10039:     return $response;
10040: }
10041: 
10042: sub auto_validate_instcode {
10043:     my ($cnum,$cdom,$instcode,$owner) = @_;
10044:     my ($homeserver,$response);
10045:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
10046:         $homeserver = &homeserver($cnum,$cdom);
10047:     }
10048:     if (!defined($homeserver)) {
10049:         if ($cdom =~ /^$match_domain$/) {
10050:             $homeserver = &domain($cdom,'primary');
10051:         }
10052:     }
10053:     $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
10054:                         &escape($instcode).':'.&escape($owner),$homeserver));
10055:     my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
10056:     return ($outcome,$description,$defaultcredits);
10057: }
10058: 
10059: sub auto_validate_inst_crosslist {
10060:     my ($cnum,$cdom,$instcode,$inst_xlist,$coowner) = @_;
10061:     my ($homeserver,$response);
10062:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
10063:         $homeserver = &homeserver($cnum,$cdom);
10064:     }
10065:     if (!defined($homeserver)) {
10066:         if ($cdom =~ /^$match_domain$/) {
10067:             $homeserver = &domain($cdom,'primary');
10068:         }
10069:     }
10070:     unless (($homeserver eq '') || ($homeserver eq 'no_host')) {
10071:         $response=&reply('autovalidateinstcrosslist:'.$cdom.':'.
10072:                          &escape($instcode).':'.&escape($inst_xlist).':'.
10073:                          &escape($coowner),$homeserver);
10074:     }
10075:     return $response;
10076: }
10077: 
10078: sub auto_create_password {
10079:     my ($cnum,$cdom,$authparam,$udom) = @_;
10080:     my ($homeserver,$response);
10081:     my $create_passwd = 0;
10082:     my $authchk = '';
10083:     if ($udom =~ /^$match_domain$/) {
10084:         $homeserver = &domain($udom,'primary');
10085:     }
10086:     if ($homeserver eq '') {
10087:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
10088:             $homeserver = &homeserver($cnum,$cdom);
10089:         }
10090:     }
10091:     if ($homeserver eq '') {
10092:         $authchk = 'nodomain';
10093:     } else {
10094:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
10095:         if ($response eq 'refused') {
10096:             $authchk = 'refused';
10097:         } else {
10098:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
10099:         }
10100:     }
10101:     return ($authparam,$create_passwd,$authchk);
10102: }
10103: 
10104: sub auto_photo_permission {
10105:     my ($cnum,$cdom,$students) = @_;
10106:     my $homeserver = &homeserver($cnum,$cdom);
10107:     my ($outcome,$perm_reqd,$conditions) = 
10108: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
10109:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
10110: 	return (undef,undef);
10111:     }
10112:     return ($outcome,$perm_reqd,$conditions);
10113: }
10114: 
10115: sub auto_checkphotos {
10116:     my ($uname,$udom,$pid) = @_;
10117:     my $homeserver = &homeserver($uname,$udom);
10118:     my ($result,$resulttype);
10119:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
10120: 				   &escape($uname).':'.&escape($pid),
10121: 				   $homeserver));
10122:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
10123: 	return (undef,undef);
10124:     }
10125:     if ($outcome) {
10126:         ($result,$resulttype) = split(/:/,$outcome);
10127:     } 
10128:     return ($result,$resulttype);
10129: }
10130: 
10131: sub auto_photochoice {
10132:     my ($cnum,$cdom) = @_;
10133:     my $homeserver = &homeserver($cnum,$cdom);
10134:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
10135: 						       &escape($cdom),
10136: 						       $homeserver)));
10137:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
10138: 	return (undef,undef);
10139:     }
10140:     return ($update,$comment);
10141: }
10142: 
10143: sub auto_photoupdate {
10144:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
10145:     my $homeserver = &homeserver($cnum,$dom);
10146:     my $host=&hostname($homeserver);
10147:     my $cmd = '';
10148:     my $maxtries = 1;
10149:     foreach my $affiliate (keys(%{$affiliatesref})) {
10150:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
10151:     }
10152:     $cmd =~ s/%%$//;
10153:     $cmd = &escape($cmd);
10154:     my $query = 'institutionalphotos';
10155:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
10156:     unless ($queryid=~/^\Q$host\E\_/) {
10157:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
10158:         return 'error: '.$queryid;
10159:     }
10160:     my $reply = &get_query_reply($queryid);
10161:     my $tries = 1;
10162:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
10163:         $reply = &get_query_reply($queryid);
10164:         $tries ++;
10165:     }
10166:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
10167:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
10168:     } else {
10169:         my @responses = split(/:/,$reply);
10170:         my $outcome = shift(@responses); 
10171:         foreach my $item (@responses) {
10172:             my ($key,$value) = split(/=/,$item);
10173:             $$photo{$key} = $value;
10174:         }
10175:         return $outcome;
10176:     }
10177:     return 'error';
10178: }
10179: 
10180: sub auto_instcode_format {
10181:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
10182: 	$cat_order) = @_;
10183:     my $courses = '';
10184:     my @homeservers;
10185:     if ($caller eq 'global') {
10186: 	my %servers = &get_servers($codedom,'library');
10187: 	foreach my $tryserver (keys(%servers)) {
10188: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
10189: 		push(@homeservers,$tryserver);
10190: 	    }
10191:         }
10192:     } elsif ($caller eq 'requests') {
10193:         if ($codedom =~ /^$match_domain$/) {
10194:             my $chome = &domain($codedom,'primary');
10195:             unless ($chome eq 'no_host') {
10196:                 push(@homeservers,$chome);
10197:             }
10198:         }
10199:     } else {
10200:         push(@homeservers,&homeserver($caller,$codedom));
10201:     }
10202:     foreach my $code (keys(%{$instcodes})) {
10203:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
10204:     }
10205:     chop($courses);
10206:     my $ok_response = 0;
10207:     my $response;
10208:     while (@homeservers > 0 && $ok_response == 0) {
10209:         my $server = shift(@homeservers); 
10210:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
10211:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
10212:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
10213: 		split(/:/,$response);
10214:             %{$codes} = (%{$codes},&str2hash($codes_str));
10215:             push(@{$codetitles},&str2array($codetitles_str));
10216:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
10217:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
10218:             $ok_response = 1;
10219:         }
10220:     }
10221:     if ($ok_response) {
10222:         return 'ok';
10223:     } else {
10224:         return $response;
10225:     }
10226: }
10227: 
10228: sub auto_instcode_defaults {
10229:     my ($domain,$returnhash,$code_order) = @_;
10230:     my @homeservers;
10231: 
10232:     my %servers = &get_servers($domain,'library');
10233:     foreach my $tryserver (keys(%servers)) {
10234: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
10235: 	    push(@homeservers,$tryserver);
10236: 	}
10237:     }
10238: 
10239:     my $response;
10240:     foreach my $server (@homeservers) {
10241:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
10242:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
10243: 	
10244: 	foreach my $pair (split(/\&/,$response)) {
10245: 	    my ($name,$value)=split(/\=/,$pair);
10246: 	    if ($name eq 'code_order') {
10247: 		@{$code_order} = split(/\&/,&unescape($value));
10248: 	    } else {
10249: 		$returnhash->{&unescape($name)}=&unescape($value);
10250: 	    }
10251: 	}
10252: 	return 'ok';
10253:     }
10254: 
10255:     return $response;
10256: }
10257: 
10258: sub auto_possible_instcodes {
10259:     my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
10260:     unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') && 
10261:             (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
10262:         return;
10263:     }
10264:     my (@homeservers,$uhome);
10265:     if (defined(&domain($domain,'primary'))) {
10266:         $uhome=&domain($domain,'primary');
10267:         push(@homeservers,&domain($domain,'primary'));
10268:     } else {
10269:         my %servers = &get_servers($domain,'library');
10270:         foreach my $tryserver (keys(%servers)) {
10271:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
10272:                 push(@homeservers,$tryserver);
10273:             }
10274:         }
10275:     }
10276:     my $response;
10277:     foreach my $server (@homeservers) {
10278:         $response=&reply('autopossibleinstcodes:'.$domain,$server);
10279:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
10280:         my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) = 
10281:             split(':',$response);
10282:         @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
10283:         @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
10284:         foreach my $item (split('&',$cat_title)) {   
10285:             my ($name,$value)=split('=',$item);
10286:             $cat_titles->{&unescape($name)}=&thaw_unescape($value);
10287:         }
10288:         foreach my $item (split('&',$cat_order)) {
10289:             my ($name,$value)=split('=',$item);
10290:             $cat_orders->{&unescape($name)}=&thaw_unescape($value);
10291:         }
10292:         return 'ok';
10293:     }
10294:     return $response;
10295: }
10296: 
10297: sub auto_courserequest_checks {
10298:     my ($dom) = @_;
10299:     my ($homeserver,%validations);
10300:     if ($dom =~ /^$match_domain$/) {
10301:         $homeserver = &domain($dom,'primary');
10302:     }
10303:     unless ($homeserver eq 'no_host') {
10304:         my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
10305:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
10306:             my @items = split(/&/,$response);
10307:             foreach my $item (@items) {
10308:                 my ($key,$value) = split('=',$item);
10309:                 $validations{&unescape($key)} = &thaw_unescape($value);
10310:             }
10311:         }
10312:     }
10313:     return %validations; 
10314: }
10315: 
10316: sub auto_courserequest_validation {
10317:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist,$custominfo) = @_;
10318:     my ($homeserver,$response);
10319:     if ($dom =~ /^$match_domain$/) {
10320:         $homeserver = &domain($dom,'primary');
10321:     }
10322:     unless ($homeserver eq 'no_host') {
10323:         my $customdata;
10324:         if (ref($custominfo) eq 'HASH') {
10325:             $customdata = &freeze_escape($custominfo);
10326:         }
10327:         $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
10328:                                     ':'.&escape($crstype).':'.&escape($inststatuslist).
10329:                                     ':'.&escape($instcode).':'.&escape($instseclist).':'.
10330:                                     $customdata,$homeserver));
10331:     }
10332:     return $response;
10333: }
10334: 
10335: sub auto_validate_class_sec {
10336:     my ($cdom,$cnum,$owners,$inst_class) = @_;
10337:     my $homeserver = &homeserver($cnum,$cdom);
10338:     my $ownerlist;
10339:     if (ref($owners) eq 'ARRAY') {
10340:         $ownerlist = join(',',@{$owners});
10341:     } else {
10342:         $ownerlist = $owners;
10343:     }
10344:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
10345:                         &escape($ownerlist).':'.$cdom,$homeserver);
10346:     return $response;
10347: }
10348: 
10349: sub auto_instsec_reformat {
10350:     my ($cdom,$action,$instsecref) = @_;
10351:     return unless(($action eq 'clutter') || ($action eq 'declutter'));
10352:     my @homeservers;
10353:     if (defined(&domain($cdom,'primary'))) {
10354:         push(@homeservers,&domain($cdom,'primary'));
10355:     } else {
10356:         my %servers = &get_servers($cdom,'library');
10357:         foreach my $tryserver (keys(%servers)) {
10358:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
10359:                 push(@homeservers,$tryserver);
10360:             }
10361:         }
10362:     }
10363:     my $response;
10364:     my %reformatted = %{$instsecref};
10365:     foreach my $server (@homeservers) {
10366:         if (ref($instsecref) eq 'HASH') {
10367:             my $info = &freeze_escape($instsecref);
10368:             my $response=&reply('autoinstsecreformat:'.$cdom.':'.
10369:                                 $action.':'.$info,$server);
10370:             next if ($response =~ /(con_lost|error|no_such_host|refused|unknown_command)/);
10371:             my @items = split(/&/,$response);
10372:             foreach my $item (@items) {
10373:                 my ($key,$value) = split(/=/,$item);
10374:                 $reformatted{&unescape($key)} = &thaw_unescape($value);
10375:             }
10376:         }
10377:     }
10378:     return %reformatted;
10379: }
10380: 
10381: sub auto_validate_instclasses {
10382:     my ($cdom,$cnum,$owners,$classesref) = @_;
10383:     my ($homeserver,%validations);
10384:     $homeserver = &homeserver($cnum,$cdom);
10385:     unless ($homeserver eq 'no_host') {
10386:         my $ownerlist;
10387:         if (ref($owners) eq 'ARRAY') {
10388:             $ownerlist = join(',',@{$owners});
10389:         } else {
10390:             $ownerlist = $owners;
10391:         }
10392:         if (ref($classesref) eq 'HASH') {
10393:             my $classes = &freeze_escape($classesref);
10394:             my $response=&reply('autovalidateinstclasses:'.&escape($ownerlist).
10395:                                 ':'.$cdom.':'.$classes,$homeserver);
10396:             unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
10397:                 my @items = split(/&/,$response);
10398:                 foreach my $item (@items) {
10399:                     my ($key,$value) = split('=',$item);
10400:                     $validations{&unescape($key)} = &thaw_unescape($value);
10401:                 }
10402:             }
10403:         }
10404:     }
10405:     return %validations;
10406: }
10407: 
10408: sub auto_crsreq_update {
10409:     my ($cdom,$cnum,$crstype,$action,$ownername,$ownerdomain,$fullname,$title,
10410:         $code,$accessstart,$accessend,$inbound) = @_;
10411:     my ($homeserver,%crsreqresponse);
10412:     if ($cdom =~ /^$match_domain$/) {
10413:         $homeserver = &domain($cdom,'primary');
10414:     }
10415:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
10416:         my $info;
10417:         if (ref($inbound) eq 'HASH') {
10418:             $info = &freeze_escape($inbound);
10419:         }
10420:         my $response=&reply('autocrsrequpdate:'.$cdom.':'.$cnum.':'.&escape($crstype).
10421:                             ':'.&escape($action).':'.&escape($ownername).':'.
10422:                             &escape($ownerdomain).':'.&escape($fullname).':'.
10423:                             &escape($title).':'.&escape($code).':'.
10424:                             &escape($accessstart).':'.&escape($accessend).':'.$info,
10425:                             $homeserver);
10426:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
10427:             my @items = split(/&/,$response);
10428:             foreach my $item (@items) {
10429:                 my ($key,$value) = split('=',$item);
10430:                 $crsreqresponse{&unescape($key)} = &thaw_unescape($value);
10431:             }
10432:         }
10433:     }
10434:     return \%crsreqresponse;
10435: }
10436: 
10437: sub auto_export_grades {
10438:     my ($cdom,$cnum,$inforef,$gradesref) = @_;
10439:     my ($homeserver,%exportresponse);
10440:     if ($cdom =~ /^$match_domain$/) {
10441:         $homeserver = &domain($cdom,'primary');
10442:     }
10443:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
10444:         my $info;
10445:         if (ref($inforef) eq 'HASH') {
10446:             $info = &freeze_escape($inforef);
10447:         }
10448:         if (ref($gradesref) eq 'HASH') {
10449:             my $grades = &freeze_escape($gradesref);
10450:             my $response=&reply('encrypt:autoexportgrades:'.$cdom.':'.$cnum.':'.
10451:                                 $info.':'.$grades,$homeserver);
10452:             unless ($response =~ /(con_lost|error|no_such_host|refused|unknown_command)/) {
10453:                 my @items = split(/&/,$response);
10454:                 foreach my $item (@items) {
10455:                     my ($key,$value) = split('=',$item);
10456:                     $exportresponse{&unescape($key)} = &thaw_unescape($value);
10457:                 }
10458:             }
10459:         }
10460:     }
10461:     return \%exportresponse;
10462: }
10463: 
10464: sub check_instcode_cloning {
10465:     my ($codedefaults,$code_order,$cloner,$clonefromcode,$clonetocode) = @_;
10466:     unless ((ref($codedefaults) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
10467:         return;
10468:     }
10469:     my $canclone;
10470:     if (@{$code_order} > 0) {
10471:         my $instcoderegexp ='^';
10472:         my @clonecodes = split(/\&/,$cloner);
10473:         foreach my $item (@{$code_order}) {
10474:             if (grep(/^\Q$item\E=/,@clonecodes)) {
10475:                 foreach my $pair (@clonecodes) {
10476:                     my ($key,$val) = split(/\=/,$pair,2);
10477:                     $val = &unescape($val);
10478:                     if ($key eq $item) {
10479:                         $instcoderegexp .= '('.$val.')';
10480:                         last;
10481:                     }
10482:                 }
10483:             } else {
10484:                 $instcoderegexp .= $codedefaults->{$item};
10485:             }
10486:         }
10487:         $instcoderegexp .= '$';
10488:         my (@from,@to);
10489:         eval {
10490:                (@from) = ($clonefromcode =~ /$instcoderegexp/);
10491:                (@to) = ($clonetocode =~ /$instcoderegexp/);
10492:         };
10493:         if ((@from > 0) && (@to > 0)) {
10494:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
10495:             if (!@diffs) {
10496:                 $canclone = 1;
10497:             }
10498:         }
10499:     }
10500:     return $canclone;
10501: }
10502: 
10503: sub default_instcode_cloning {
10504:     my ($clonedom,$domdefclone,$clonefromcode,$clonetocode,$codedefaultsref,$codeorderref) = @_;
10505:     my (%codedefaults,@code_order,$canclone);
10506:     if ((ref($codedefaultsref) eq 'HASH') && (ref($codeorderref) eq 'ARRAY')) {
10507:         %codedefaults = %{$codedefaultsref};
10508:         @code_order = @{$codeorderref};
10509:     } elsif ($clonedom) {
10510:         &auto_instcode_defaults($clonedom,\%codedefaults,\@code_order);
10511:     }
10512:     if (($domdefclone) && (@code_order)) {
10513:         my @clonecodes = split(/\+/,$domdefclone);
10514:         my $instcoderegexp ='^';
10515:         foreach my $item (@code_order) {
10516:             if (grep(/^\Q$item\E$/,@clonecodes)) {
10517:                 $instcoderegexp .= '('.$codedefaults{$item}.')';
10518:             } else {
10519:                 $instcoderegexp .= $codedefaults{$item};
10520:             }
10521:         }
10522:         $instcoderegexp .= '$';
10523:         my (@from,@to);
10524:         eval {
10525:             (@from) = ($clonefromcode =~ /$instcoderegexp/);
10526:             (@to) = ($clonetocode =~ /$instcoderegexp/);
10527:         };
10528:         if ((@from > 0) && (@to > 0)) {
10529:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
10530:             if (!@diffs) {
10531:                 $canclone = 1;
10532:             }
10533:         }
10534:     }
10535:     return $canclone;
10536: }
10537: 
10538: # ------------------------------------------------------- Course Group routines
10539: 
10540: sub get_coursegroups {
10541:     my ($cdom,$cnum,$group,$namespace) = @_;
10542:     return(&dump($namespace,$cdom,$cnum,$group));
10543: }
10544: 
10545: sub modify_coursegroup {
10546:     my ($cdom,$cnum,$groupsettings) = @_;
10547:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
10548: }
10549: 
10550: sub toggle_coursegroup_status {
10551:     my ($cdom,$cnum,$group,$action) = @_;
10552:     my ($from_namespace,$to_namespace);
10553:     if ($action eq 'delete') {
10554:         $from_namespace = 'coursegroups';
10555:         $to_namespace = 'deleted_groups';
10556:     } else {
10557:         $from_namespace = 'deleted_groups';
10558:         $to_namespace = 'coursegroups';
10559:     }
10560:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
10561:     if (my $tmp = &error(%curr_group)) {
10562:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
10563:         return ('read error',$tmp);
10564:     } else {
10565:         my %savedsettings = %curr_group; 
10566:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
10567:         my $deloutcome;
10568:         if ($result eq 'ok') {
10569:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
10570:         } else {
10571:             return ('write error',$result);
10572:         }
10573:         if ($deloutcome eq 'ok') {
10574:             return 'ok';
10575:         } else {
10576:             return ('delete error',$deloutcome);
10577:         }
10578:     }
10579: }
10580: 
10581: sub modify_group_roles {
10582:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context,
10583:         $othdomby,$requester) = @_;
10584:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
10585:     my $role = 'gr/'.&escape($userprivs);
10586:     my ($uname,$udom) = split(/:/,$user);
10587:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context,
10588:                              $othdomby,$requester);
10589:     if ($result eq 'ok') {
10590:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
10591:     }
10592:     return $result;
10593: }
10594: 
10595: sub modify_coursegroup_membership {
10596:     my ($cdom,$cnum,$membership) = @_;
10597:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
10598:     return $result;
10599: }
10600: 
10601: sub get_active_groups {
10602:     my ($udom,$uname,$cdom,$cnum) = @_;
10603:     my $now = time;
10604:     my %groups = ();
10605:     foreach my $key (keys(%env)) {
10606:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
10607:             my ($start,$end) = split(/\./,$env{$key});
10608:             if (($end!=0) && ($end<$now)) { next; }
10609:             if (($start!=0) && ($start>$now)) { next; }
10610:             if ($1 eq $cdom && $2 eq $cnum) {
10611:                 $groups{$3} = $env{$key} ;
10612:             }
10613:         }
10614:     }
10615:     return %groups;
10616: }
10617: 
10618: sub get_group_membership {
10619:     my ($cdom,$cnum,$group) = @_;
10620:     return(&dump('groupmembership',$cdom,$cnum,$group));
10621: }
10622: 
10623: sub get_users_groups {
10624:     my ($udom,$uname,$courseid) = @_;
10625:     my @usersgroups;
10626:     my $cachetime=1800;
10627: 
10628:     my $hashid="$udom:$uname:$courseid";
10629:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
10630:     if (defined($cached)) {
10631:         @usersgroups = split(/:/,$grouplist);
10632:     } else {  
10633:         $grouplist = '';
10634:         my $courseurl = &courseid_to_courseurl($courseid);
10635:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
10636:         my $access_end = $env{'course.'.$courseid.
10637:                               '.default_enrollment_end_date'};
10638:         my $now = time;
10639:         foreach my $key (keys(%roleshash)) {
10640:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
10641:                 my $group = $1;
10642:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
10643:                     my $start = $2;
10644:                     my $end = $1;
10645:                     if ($start == -1) { next; } # deleted from group
10646:                     if (($start!=0) && ($start>$now)) { next; }
10647:                     if (($end!=0) && ($end<$now)) {
10648:                         if ($access_end && $access_end < $now) {
10649:                             if ($access_end - $end < 86400) {
10650:                                 push(@usersgroups,$group);
10651:                             }
10652:                         }
10653:                         next;
10654:                     }
10655:                     push(@usersgroups,$group);
10656:                 }
10657:             }
10658:         }
10659:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
10660:         $grouplist = join(':',@usersgroups);
10661:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
10662:     }
10663:     return @usersgroups;
10664: }
10665: 
10666: sub devalidate_getgroups_cache {
10667:     my ($udom,$uname,$cdom,$cnum)=@_;
10668:     my $courseid = $cdom.'_'.$cnum;
10669: 
10670:     my $hashid="$udom:$uname:$courseid";
10671:     &devalidate_cache_new('getgroups',$hashid);
10672: }
10673: 
10674: # ------------------------------------------------------------------ Plain Text
10675: 
10676: sub plaintext {
10677:     my ($short,$type,$cid,$forcedefault) = @_;
10678:     if ($short =~ m{^cr/}) {
10679: 	return (split('/',$short))[-1];
10680:     }
10681:     if (!defined($cid)) {
10682:         $cid = $env{'request.course.id'};
10683:     }
10684:     my %rolenames = (
10685:                       Course    => 'std',
10686:                       Community => 'alt1',
10687:                       Placement => 'std',
10688:                     );
10689:     if ($cid ne '') {
10690:         if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
10691:             unless ($forcedefault) {
10692:                 my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
10693:                 &Apache::lonlocal::mt_escape(\$roletext);
10694:                 return &Apache::lonlocal::mt($roletext);
10695:             }
10696:         }
10697:     }
10698:     if ((defined($type)) && (defined($rolenames{$type})) &&
10699:         (defined($rolenames{$type})) && 
10700:         (defined($prp{$short}{$rolenames{$type}}))) {
10701:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
10702:     } elsif ($cid ne '') {
10703:         my $crstype = $env{'course.'.$cid.'.type'};
10704:         if (($crstype ne '') && (defined($rolenames{$crstype})) &&
10705:             (defined($prp{$short}{$rolenames{$crstype}}))) {
10706:             return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
10707:         }
10708:     }
10709:     return &Apache::lonlocal::mt($prp{$short}{'std'});
10710: }
10711: 
10712: # ----------------------------------------------------------------- Assign Role
10713: 
10714: sub assignrole {
10715:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
10716:         $context,$othdomby,$requester,$reqsec,$reqrole)=@_;
10717:     my ($mrole,$rolelogcontext);
10718:     if ($role =~ /^cr\//) {
10719:         my $cwosec=$url;
10720:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
10721:         if ((!&allowed('ccr',$cwosec)) && (!&allowed('ccr',$udom))) {
10722:             my $refused = 1;
10723:             if ($context eq 'requestcourses') {
10724:                 if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
10725:                     if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
10726:                         if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
10727:                             my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
10728:                             my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
10729:                             if ($crsenv{'internal.courseowner'} eq
10730:                                 $env{'user.name'}.':'.$env{'user.domain'}) {
10731:                                 $refused = '';
10732:                             }
10733:                         }
10734:                     }
10735:                 }
10736:             } elsif (($context eq 'course') && ($othdomby eq 'othdombyuser')) {
10737:                 my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
10738:                 my ($sec) = ($url =~ m{^/\Q$cwosec\E/(.*)$});
10739:                 my $key = "$uname:$udom:$role:$sec";
10740:                 my %queuedrolereq = &Apache::lonnet::get('nohist_othdomqueued',[$key],$cdom,$cnum);
10741:                 if ((exists($queuedrolereq{$key})) && (ref($queuedrolereq{$key}) eq 'HASH')) {
10742:                     if (($queuedrolereq{$key}{'adj'} eq 'user') && ($queuedrolereq{$key}{'requester'} eq $requester)) {
10743:                         $refused = '';
10744:                     }
10745:                 }
10746:             }
10747:             if ($refused) {
10748:                 &logthis('Refused custom assignrole: '.
10749:                          $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
10750:                          ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
10751:                 return 'refused';
10752:             }
10753:         }
10754:         $mrole='cr';
10755:     } elsif ($role =~ /^gr\//) {
10756:         my $cwogrp=$url;
10757:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
10758:         if (!&allowed('mdg',$cwogrp)) {
10759:             my $refused = 1;
10760:             if (($refused) && ($othdomby eq 'othdombyuser') && ($requester ne '') && ($reqrole ne '')) {
10761:                 my ($cdom,$cnum) = ($cwogrp =~ m{^/?($match_domain)/($match_courseid)$});
10762:                 my $key = "$uname:$udom:$reqrole:$reqsec";
10763:                 my %queuedrolereq = &Apache::lonnet::get('nohist_othdomqueued',[$key],$cdom,$cnum);
10764:                 if ((exists($queuedrolereq{$key})) && (ref($queuedrolereq{$key}) eq 'HASH')) {
10765:                     if (($queuedrolereq{$key}{'adj'} eq 'user') && ($queuedrolereq{$key}{'requester'} eq $requester)) {
10766:                         $refused = '';
10767:                     }
10768:                 }
10769:             }
10770:             if ($refused) {
10771:                 &logthis('Refused group assignrole: '.
10772:                          $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
10773:                          $env{'user.name'}.' at '.$env{'user.domain'});
10774:                 return 'refused';
10775:             }
10776:         }
10777:         $mrole='gr';
10778:     } else {
10779:         my $cwosec=$url;
10780:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
10781:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
10782:             my $refused;
10783:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
10784:                 if (!(&allowed('c'.$role,$url))) {
10785:                     $refused = 1;
10786:                 }
10787:             } else {
10788:                 $refused = 1;
10789:             }
10790:             if ($refused) {
10791:                 my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
10792:                 if (!$selfenroll && ($othdomby ne 'othdombyuser') &&
10793:                    (($context eq 'course') || ($context eq 'ltienroll' && $env{'request.lti.login'}))) {
10794:                     my %crsenv;
10795:                     if ($role eq 'cc' || $role eq 'co') {
10796:                         %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
10797:                         if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
10798:                             if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
10799:                                 if ($crsenv{'internal.courseowner'} eq 
10800:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
10801:                                     $refused = '';
10802:                                 }
10803:                             }
10804:                         } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) { 
10805:                             if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
10806:                                 if ($crsenv{'internal.courseowner'} eq 
10807:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
10808:                                     $refused = '';
10809:                                 }
10810:                             }
10811:                         }
10812:                     }
10813:                 } elsif (($selfenroll == 1) && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
10814:                     if ($role eq 'st') {
10815:                         $refused = '';
10816:                     } elsif (($context eq 'ltienroll') && ($env{'request.lti.login'})) {
10817:                         $refused = '';
10818:                     }
10819:                 } elsif ($othdomby eq 'othdombyuser') {
10820:                     my ($key,%queuedrolereq);
10821:                     if ($context eq 'course') {
10822:                         my ($sec) = ($url =~ m{^/\Q$cwosec\E/(.*)$});
10823:                         $key = "$uname:$udom:$role:$sec";
10824:                         %queuedrolereq = &Apache::lonnet::get('nohist_othdomqueued',[$key],$cdom,$cnum);
10825:                         if ((exists($queuedrolereq{$key})) && (ref($queuedrolereq{$key}) eq 'HASH')) {
10826:                             if (($queuedrolereq{$key}{'adj'} eq 'user') && ($queuedrolereq{$key}{'requester'} eq $requester)) {
10827:                                 if ((($role eq 'cc') && ($cnum !~ /^$match_community$/)) || 
10828:                                     (($role eq 'co') && ($cnum =~ /^$match_community$/))) {
10829:                                     my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
10830:                                     if ($crsenv{'internal.courseowner'} eq $requester) {
10831:                                         $refused = '';
10832:                                     }
10833:                                 } elsif ($role =~ /^(?:in|ta|ep|st)$/) {
10834:                                     $refused = '';
10835:                                 }
10836:                             }
10837:                         }
10838:                     } elsif (($context eq 'author') && ($role =~ /^ca|aa$/)) {
10839:                         my $key = "$uname:$udom:$role"; 
10840:                         my ($audom,$auname) = ($url =~ m{^/($match_domain)/($match_username)$});
10841:                         if (($audom ne '') && ($auname ne '')) {
10842:                             my %queuedrolereq = &Apache::lonnet::get('nohist_othdomqueued',[$key],$audom,$auname);
10843:                             if ((exists($queuedrolereq{$key})) && (ref($queuedrolereq{$key}) eq 'HASH')) {
10844:                                 if (($queuedrolereq{$key}{'adj'} eq 'user') && ($queuedrolereq{$key}{'requester'} eq $requester)) {
10845:                                     $refused = '';
10846:                                 }
10847:                             }
10848:                         }
10849:                     } elsif (($context eq 'domain') && ($role ne 'dc') && ($role ne 'su')) {
10850:                         my $key = "$uname:$udom:$role";
10851:                         my ($roledom) = ($url =~ m{^/($match_domain)/\Q$role\E$});
10852:                         if ($roledom ne '') {
10853:                             my $confname = $roledom.'-domainconfig';
10854:                             my %queuedrolereq = &Apache::lonnet::get('nohist_othdomqueued',[$key],$roledom,$confname);
10855:                             if ((exists($queuedrolereq{$key})) && (ref($queuedrolereq{$key}) eq 'HASH')) {
10856:                                 if (($queuedrolereq{$key}{'adj'} eq 'user') && ($queuedrolereq{$key}{'requester'} eq $requester)) {
10857:                                     $refused = '';
10858:                                 }
10859:                             }
10860:                         }
10861:                     }
10862:                 } elsif ($context eq 'requestcourses') {
10863:                     my @possroles = ('st','ta','ep','in','cc','co');
10864:                     if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
10865:                         my $wrongcc;
10866:                         if ($cnum =~ /^$match_community$/) {
10867:                             $wrongcc = 1 if ($role eq 'cc');
10868:                         } else {
10869:                             $wrongcc = 1 if ($role eq 'co');
10870:                         }
10871:                         unless ($wrongcc) {
10872:                             my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
10873:                             if ($crsenv{'internal.courseowner'} eq 
10874:                                  $env{'user.name'}.':'.$env{'user.domain'}) {
10875:                                 $refused = '';
10876:                             }
10877:                         }
10878:                     }
10879:                 } elsif ($context eq 'requestauthor') {
10880:                     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) && 
10881:                         ($url eq '/'.$udom.'/') && ($role eq 'au')) {
10882:                         if ($env{'environment.requestauthor'} eq 'automatic') {
10883:                             $refused = '';
10884:                         } else {
10885:                             my %domdefaults = &get_domain_defaults($udom);
10886:                             if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
10887:                                 my $checkbystatus;
10888:                                 if ($env{'user.adv'}) { 
10889:                                     my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
10890:                                     if ($disposition eq 'automatic') {
10891:                                         $refused = '';
10892:                                     } elsif ($disposition eq '') {
10893:                                         $checkbystatus = 1;
10894:                                     } 
10895:                                 } else {
10896:                                     $checkbystatus = 1;
10897:                                 }
10898:                                 if ($checkbystatus) {
10899:                                     if ($env{'environment.inststatus'}) {
10900:                                         my @inststatuses = split(/,/,$env{'environment.inststatus'});
10901:                                         foreach my $type (@inststatuses) {
10902:                                             if (($type ne '') &&
10903:                                                 ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
10904:                                                 $refused = '';
10905:                                             }
10906:                                         }
10907:                                     } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
10908:                                         $refused = '';
10909:                                     }
10910:                                 }
10911:                             }
10912:                         }
10913:                     }
10914:                 } elsif (($context eq 'author') && (($role eq 'ca' || $role eq 'aa'))) {
10915:                     if ($url =~ m{^/($match_domain)/($match_username)$}) {
10916:                         my ($audom,$auname) = ($1,$2);
10917:                         if ((&Apache::lonnet::allowed('v'.$role,"$audom/$auname")) &&
10918:                             ($env{"environment.internal.manager.$url"})) {
10919:                             $refused = '';
10920:                             $rolelogcontext = 'coauthor';
10921:                         }
10922:                     }
10923:                 }
10924:                 if ($refused) {
10925:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
10926:                              ' '.$role.' '.$end.' '.$start.' by '.
10927: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
10928:                     return 'refused';
10929:                 }
10930:             }
10931:         } elsif ($role eq 'au') {
10932:             if ($url ne '/'.$udom.'/') {
10933:                 &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
10934:                          ' to assign author role for '.$uname.':'.$udom.
10935:                          ' in domain: '.$url.' refused (wrong domain).');
10936:                 return 'refused';
10937:             }
10938:         }
10939:         $mrole=$role;
10940:     }
10941:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
10942:                 "$udom:$uname:$url".'_'."$mrole=$role";
10943:     if ($end) { $command.='_'.$end; }
10944:     if ($start) {
10945: 	if ($end) { 
10946:            $command.='_'.$start; 
10947:         } else {
10948:            $command.='_0_'.$start;
10949:         }
10950:     }
10951:     my $origstart = $start;
10952:     my $origend = $end;
10953:     my $delflag;
10954: # actually delete
10955:     if ($deleteflag) {
10956: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
10957: # modify command to delete the role
10958:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
10959:                 "$udom:$uname:$url".'_'."$mrole";
10960: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
10961: # set start and finish to negative values for userrolelog
10962:            $start=-1;
10963:            $end=-1;
10964:            $delflag = 1;
10965:         }
10966:     }
10967: # send command
10968:     my $answer=&reply($command,&homeserver($uname,$udom));
10969: # log new user role if status is ok
10970:     if ($answer eq 'ok') {
10971: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
10972:         if (($role eq 'cc') || ($role eq 'in') ||
10973:             ($role eq 'ep') || ($role eq 'ad') ||
10974:             ($role eq 'ta') || ($role eq 'st') ||
10975:             ($role=~/^cr/) || ($role eq 'gr') ||
10976:             ($role eq 'co')) {
10977: # for course roles, perform group memberships changes triggered by role change.
10978:             unless ($role =~ /^gr/) {
10979:                 &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
10980:                                                  $origstart,$selfenroll,$context);
10981:             }
10982:             &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
10983:                            $selfenroll,$context,$othdomby,$requester);
10984:         } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
10985:                  ($role eq 'au') || ($role eq 'dc') || ($role eq 'dh') ||
10986:                  ($role eq 'da')) {
10987:             &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
10988:                            $context,$othdomby,$requester);
10989:         } elsif (($role eq 'ca') || ($role eq 'aa')) {
10990:             if ($rolelogcontext eq '') {
10991:                 $rolelogcontext = $context;
10992:             }
10993:             &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
10994:                              $rolelogcontext,$othdomby,$requester); 
10995:         }
10996:         if ($role eq 'cc') {
10997:             &autoupdate_coowners($url,$end,$start,$uname,$udom);
10998:         }
10999:     }
11000:     return $answer;
11001: }
11002: 
11003: sub autoupdate_coowners {
11004:     my ($url,$end,$start,$uname,$udom) = @_;
11005:     my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
11006:     if (($cdom ne '') && ($cnum ne '')) {
11007:         my $now = time;
11008:         my %domdesign = &Apache::loncommon::get_domainconf($cdom);
11009:         if ($domdesign{$cdom.'.autoassign.co-owners'}) {
11010:             my %coursehash = &coursedescription($cdom.'_'.$cnum);
11011:             my $instcode = $coursehash{'internal.coursecode'};
11012:             my $xlists = $coursehash{'internal.crosslistings'};
11013:             if ($instcode ne '') {
11014:                 if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
11015:                     unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
11016:                         my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
11017:                         my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
11018:                         unless ($result eq 'valid') {
11019:                             if ($xlists ne '') {
11020:                                 foreach my $xlist (split(',',$xlists)) {
11021:                                     my ($inst_crosslist,$lcsec) = split(':',$xlist);
11022:                                     $result =
11023:                                         &auto_validate_inst_crosslist($cnum,$cdom,$instcode,
11024:                                                                       $inst_crosslist,$uname.':'.$udom);
11025:                                     last if ($result eq 'valid');
11026:                                 }
11027:                             }
11028:                         }
11029:                         if ($result eq 'valid') {
11030:                             if ($coursehash{'internal.co-owners'}) {
11031:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
11032:                                     push(@newcoowners,$coowner);
11033:                                 }
11034:                                 unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
11035:                                     push(@newcoowners,$uname.':'.$udom);
11036:                                 }
11037:                                 @newcoowners = sort(@newcoowners);
11038:                             } else {
11039:                                 push(@newcoowners,$uname.':'.$udom);
11040:                             }
11041:                         } elsif ($coursehash{'internal.co-owners'}) {
11042:                             foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
11043:                                 unless ($coowner eq $uname.':'.$udom) {
11044:                                     push(@newcoowners,$coowner);
11045:                                 }
11046:                             }
11047:                             unless (@newcoowners > 0) {
11048:                                 $delcoowners = 1;
11049:                                 $coowners = '';
11050:                             }
11051:                         }
11052:                         if (@newcoowners || $delcoowners) {
11053:                             &store_coowners($cdom,$cnum,$coursehash{'home'},
11054:                                             $delcoowners,@newcoowners);
11055:                         }
11056:                     }
11057:                 }
11058:             }
11059:         }
11060:     }
11061: }
11062: 
11063: sub store_coowners {
11064:     my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
11065:     my $cid = $cdom.'_'.$cnum;
11066:     my ($coowners,$delresult,$putresult);
11067:     if (@newcoowners) {
11068:         $coowners = join(',',@newcoowners);
11069:         my %coownershash = (
11070:                             'internal.co-owners' => $coowners,
11071:                            );
11072:         $putresult = &put('environment',\%coownershash,$cdom,$cnum);
11073:         if ($putresult eq 'ok') {
11074:             if ($env{'course.'.$cid.'.num'} eq $cnum) {
11075:                 &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
11076:             }
11077:         }
11078:     }
11079:     if ($delcoowners) {
11080:         $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
11081:         if ($delresult eq 'ok') {
11082:             if ($env{'course.'.$cid.'.internal.co-owners'}) {
11083:                 &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
11084:             }
11085:         }
11086:     }
11087:     if (($putresult eq 'ok') || ($delresult eq 'ok')) {
11088:         my %crsinfo =
11089:             &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
11090:         if (ref($crsinfo{$cid}) eq 'HASH') {
11091:             $crsinfo{$cid}{'co-owners'} = \@newcoowners;
11092:             my $cidput = &courseidput($cdom,\%crsinfo,$chome,'notime');
11093:         }
11094:     }
11095: }
11096: 
11097: # -------------------------------------------------- Modify user authentication
11098: # Overrides without validation
11099: 
11100: sub modifyuserauth {
11101:     my ($udom,$uname,$umode,$upass)=@_;
11102:     my $uhome=&homeserver($uname,$udom);
11103:     my $allowed;
11104:     if (&allowed('mau',$udom)) {
11105:         $allowed = 1;
11106:     } elsif (($umode eq 'internal') && ($udom eq $env{'user.domain'}) &&
11107:              ($env{'request.course.id'}) && (&allowed('mip',$env{'request.course.id'})) &&
11108:              (!$env{'course.'.$env{'request.course.id'}.'.internal.nopasswdchg'})) {
11109:         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
11110:         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
11111:         if (($cdom ne '') && ($cnum ne '')) {
11112:             my $is_owner = &is_course_owner($cdom,$cnum);
11113:             if ($is_owner) {
11114:                 $allowed = 1;
11115:             }
11116:         }
11117:     }
11118:     unless ($allowed) { return 'refused'; }
11119:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
11120:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
11121:              ' in domain '.$env{'request.role.domain'});  
11122:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
11123: 		     &escape($upass),$uhome);
11124:     my $ip = &get_requestor_ip();
11125:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
11126:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
11127:          '(Remote '.$ip.'): '.$reply);
11128:     &log($udom,,$uname,$uhome,
11129:         'Authentication changed by '.$env{'user.domain'}.', '.
11130:                                      $env{'user.name'}.', '.$umode.
11131:          '(Remote '.$ip.'): '.$reply);
11132:     unless ($reply eq 'ok') {
11133:         &logthis('Authentication mode error: '.$reply);
11134: 	return 'error: '.$reply;
11135:     }   
11136:     return 'ok';
11137: }
11138: 
11139: # --------------------------------------------------------------- Modify a user
11140: 
11141: sub modifyuser {
11142:     my ($udom,    $uname, $uid,
11143:         $umode,   $upass, $first,
11144:         $middle,  $last,  $gene,
11145:         $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
11146:     $udom= &LONCAPA::clean_domain($udom);
11147:     $uname=&LONCAPA::clean_username($uname);
11148:     my $showcandelete = 'none';
11149:     if (ref($candelete) eq 'ARRAY') {
11150:         if (@{$candelete} > 0) {
11151:             $showcandelete = join(', ',@{$candelete});
11152:         }
11153:     }
11154:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
11155:              $umode.', '.$first.', '.$middle.', '.
11156: 	     $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
11157:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
11158:                                      ' desiredhome not specified'). 
11159:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
11160:              ' in domain '.$env{'request.role.domain'});
11161:     my $uhome=&homeserver($uname,$udom,'true');
11162:     my $newuser;
11163:     if ($uhome eq 'no_host') {
11164:         $newuser = 1;
11165:         unless (($umode && ($upass ne '')) || ($umode eq 'localauth') ||
11166:                 ($umode eq 'lti')) {
11167:             return 'error: more information needed to create new user';
11168:         }
11169:     }
11170: # ----------------------------------------------------------------- Create User
11171:     if (($uhome eq 'no_host') && 
11172: 	(($umode && $upass) || ($umode eq 'localauth') || ($umode eq 'lti'))) {
11173:         my $unhome='';
11174:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
11175:             $unhome = $desiredhome;
11176: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
11177: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
11178:         } else { # load balancing routine for determining $unhome
11179:             my $loadm=10000000;
11180: 	    my %servers = &get_servers($udom,'library');
11181: 	    foreach my $tryserver (keys(%servers)) {
11182: 		my $answer=reply('load',$tryserver);
11183: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
11184: 		    $loadm=$answer;
11185: 		    $unhome=$tryserver;
11186: 		}
11187: 	    }
11188:         }
11189:         if (($unhome eq '') || ($unhome eq 'no_host')) {
11190: 	    return 'error: unable to find a home server for '.$uname.
11191:                    ' in domain '.$udom;
11192:         }
11193:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
11194:                          &escape($upass),$unhome);
11195: 	unless ($reply eq 'ok') {
11196:             return 'error: '.$reply;
11197:         }   
11198:         $uhome=&homeserver($uname,$udom,'true');
11199:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
11200: 	    return 'error: unable verify users home machine.';
11201:         }
11202:     }   # End of creation of new user
11203: # ---------------------------------------------------------------------- Add ID
11204:     if ($uid) {
11205:        $uid=~tr/A-Z/a-z/;
11206:        my %uidhash=&idrget($udom,$uname);
11207:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
11208:          && (!$forceid)) {
11209: 	  unless ($uid eq $uidhash{$uname}) {
11210: 	      return 'error: user id "'.$uid.'" does not match '.
11211:                   'current user id "'.$uidhash{$uname}.'".';
11212:           }
11213:        } else {
11214: 	  &idput($udom,{$uname => $uid},$uhome,'ids');
11215:        }
11216:     }
11217: # -------------------------------------------------------------- Add names, etc
11218:     my @tmp=&get('environment',
11219: 		   ['firstname','middlename','lastname','generation','id',
11220:                     'permanentemail','inststatus'],
11221: 		   $udom,$uname);
11222:     my (%names,%oldnames);
11223:     if ($tmp[0] =~ m/^error:.*/) { 
11224:         %names=(); 
11225:     } else {
11226:         %names = @tmp;
11227:         %oldnames = %names;
11228:     }
11229: #
11230: # If name, email and/or uid are blank (e.g., because an uploaded file
11231: # of users did not contain them), do not overwrite existing values
11232: # unless field is in $candelete array ref.  
11233: #
11234: 
11235:     my @fields = ('firstname','middlename','lastname','generation',
11236:                   'permanentemail','id');
11237:     my %newvalues;
11238:     if (ref($candelete) eq 'ARRAY') {
11239:         foreach my $field (@fields) {
11240:             if (grep(/^\Q$field\E$/,@{$candelete})) {
11241:                 if ($field eq 'firstname') {
11242:                     $names{$field} = $first;
11243:                 } elsif ($field eq 'middlename') {
11244:                     $names{$field} = $middle;
11245:                 } elsif ($field eq 'lastname') {
11246:                     $names{$field} = $last;
11247:                 } elsif ($field eq 'generation') { 
11248:                     $names{$field} = $gene;
11249:                 } elsif ($field eq 'permanentemail') {
11250:                     $names{$field} = $email;
11251:                 } elsif ($field eq 'id') {
11252:                     $names{$field}  = $uid;
11253:                 }
11254:             }
11255:         }
11256:     }
11257:     if ($first)  { $names{'firstname'}  = $first; }
11258:     if (defined($middle)) { $names{'middlename'} = $middle; }
11259:     if ($last)   { $names{'lastname'}   = $last; }
11260:     if (defined($gene))   { $names{'generation'} = $gene; }
11261:     if ($email) {
11262:        $email=~s/[^\w\@\.\-\,]//gs;
11263:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
11264:     }
11265:     if ($uid) { $names{'id'}  = $uid; }
11266:     if (defined($inststatus)) {
11267:         $names{'inststatus'} = '';
11268:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
11269:         if (ref($usertypes) eq 'HASH') {
11270:             my @okstatuses; 
11271:             foreach my $item (split(/:/,$inststatus)) {
11272:                 if (defined($usertypes->{$item})) {
11273:                     push(@okstatuses,$item);  
11274:                 }
11275:             }
11276:             if (@okstatuses) {
11277:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
11278:             }
11279:         }
11280:     }
11281:     my $logmsg = $udom.', '.$uname.', '.$uid.', '.
11282:                  $umode.', '.$first.', '.$middle.', '.
11283:                  $last.', '.$gene.', '.$email.', '.$inststatus;
11284:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
11285:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
11286:     } else {
11287:         $logmsg .= ' during self creation';
11288:     }
11289:     my $changed;
11290:     if ($newuser) {
11291:         $changed = 1;
11292:     } else {
11293:         foreach my $field (@fields) {
11294:             if ($names{$field} ne $oldnames{$field}) {
11295:                 $changed = 1;
11296:                 last;
11297:             }
11298:         }
11299:     }
11300:     unless ($changed) {
11301:         $logmsg = 'No changes in user information needed for: '.$logmsg;
11302:         &logthis($logmsg);
11303:         return 'ok';
11304:     }
11305:     my $reply = &put('environment', \%names, $udom,$uname);
11306:     if ($reply ne 'ok') { 
11307:         return 'error: '.$reply;
11308:     }
11309:     if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
11310:         &devalidate_cache_new('emailscache',$uname.':'.$udom);
11311:     }
11312:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
11313:     &devalidate_cache_new('namescache',$uname.':'.$udom);
11314:     $logmsg = 'Success modifying user '.$logmsg;
11315:     &logthis($logmsg);
11316:     return 'ok';
11317: }
11318: 
11319: # -------------------------------------------------------------- Modify student
11320: 
11321: sub modifystudent {
11322:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
11323:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
11324:         $selfenroll,$context,$inststatus,$credits,$instsec)=@_;
11325:     if (!$cid) {
11326: 	unless ($cid=$env{'request.course.id'}) {
11327: 	    return 'not_in_class';
11328: 	}
11329:     }
11330: # --------------------------------------------------------------- Make the user
11331:     my $reply=&modifyuser
11332: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
11333:          $desiredhome,$email,$inststatus);
11334:     unless ($reply eq 'ok') { return $reply; }
11335:     # This will cause &modify_student_enrollment to get the uid from the
11336:     # student's environment
11337:     $uid = undef if (!$forceid);
11338:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
11339:                                         $gene,$usec,$end,$start,$type,$locktype,
11340:                                         $cid,$selfenroll,$context,$credits,$instsec);
11341:     return $reply;
11342: }
11343: 
11344: sub modify_student_enrollment {
11345:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,
11346:         $locktype,$cid,$selfenroll,$context,$credits,$instsec,$othdomby,$requester) = @_;
11347:     my ($cdom,$cnum,$chome);
11348:     if (!$cid) {
11349: 	unless ($cid=$env{'request.course.id'}) {
11350: 	    return 'not_in_class';
11351: 	}
11352: 	$cdom=$env{'course.'.$cid.'.domain'};
11353: 	$cnum=$env{'course.'.$cid.'.num'};
11354:     } else {
11355: 	($cdom,$cnum)=split(/_/,$cid);
11356:     }
11357:     $chome=$env{'course.'.$cid.'.home'};
11358:     if (!$chome) {
11359: 	$chome=&homeserver($cnum,$cdom);
11360:     }
11361:     if (!$chome) { return 'unknown_course'; }
11362:     # Make sure the user exists
11363:     my $uhome=&homeserver($uname,$udom);
11364:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
11365: 	return 'error: no such user';
11366:     }
11367:     # Get student data if we were not given enough information
11368:     if (!defined($first)  || $first  eq '' || 
11369:         !defined($last)   || $last   eq '' || 
11370:         !defined($uid)    || $uid    eq '' || 
11371:         !defined($middle) || $middle eq '' || 
11372:         !defined($gene)   || $gene   eq '') {
11373:         # They did not supply us with enough data to enroll the student, so
11374:         # we need to pick up more information.
11375:         my %tmp = &get('environment',
11376:                        ['firstname','middlename','lastname', 'generation','id']
11377:                        ,$udom,$uname);
11378: 
11379:         #foreach my $key (keys(%tmp)) {
11380:         #    &logthis("key $key = ".$tmp{$key});
11381:         #}
11382:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
11383:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
11384:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
11385:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
11386:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
11387:     }
11388:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
11389:     my $user = "$uname:$udom";
11390:     my %old_entry = &get('classlist',[$user],$cdom,$cnum);
11391:     my $reply=cput('classlist',
11392: 		   {$user => 
11393: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits,$instsec) },
11394: 		   $cdom,$cnum);
11395:     if (($reply eq 'ok') || ($reply eq 'delayed')) {
11396:         &devalidate_getsection_cache($udom,$uname,$cid);
11397:     } else { 
11398: 	return 'error: '.$reply;
11399:     }
11400:     # Add student role to user
11401:     my $uurl='/'.$cid;
11402:     $uurl=~s/\_/\//g;
11403:     if ($usec) {
11404: 	$uurl.='/'.$usec;
11405:     }
11406:     my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
11407:                              $selfenroll,$context,$othdomby,$requester);
11408:     if ($result ne 'ok') {
11409:         if ($old_entry{$user} ne '') {
11410:             $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
11411:         } else {
11412:             $reply = &del('classlist',[$user],$cdom,$cnum);
11413:         }
11414:     }
11415:     return $result; 
11416: }
11417: 
11418: sub format_name {
11419:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
11420:     my $name;
11421:     if ($first ne 'lastname') {
11422: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
11423:     } else {
11424: 	if ($lastname=~/\S/) {
11425: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
11426: 	    $name=~s/\s+,/,/;
11427: 	} else {
11428: 	    $name.= $firstname.' '.$middlename.' '.$generation;
11429: 	}
11430:     }
11431:     $name=~s/^\s+//;
11432:     $name=~s/\s+$//;
11433:     $name=~s/\s+/ /g;
11434:     return $name;
11435: }
11436: 
11437: # ------------------------------------------------- Write to course preferences
11438: 
11439: sub writecoursepref {
11440:     my ($courseid,%prefs)=@_;
11441:     $courseid=~s/^\///;
11442:     $courseid=~s/\_/\//g;
11443:     my ($cdomain,$cnum)=split(/\//,$courseid);
11444:     my $chome=homeserver($cnum,$cdomain);
11445:     if (($chome eq '') || ($chome eq 'no_host')) { 
11446: 	return 'error: no such course';
11447:     }
11448:     my $cstring='';
11449:     foreach my $pref (keys(%prefs)) {
11450: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
11451:     }
11452:     $cstring=~s/\&$//;
11453:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
11454: }
11455: 
11456: # ---------------------------------------------------------- Make/modify course
11457: 
11458: sub createcourse {
11459:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
11460:         $course_owner,$crstype,$cnum,$context,$category,$callercontext)=@_;
11461:     $url=&declutter($url);
11462:     my $cid='';
11463:     if ($context eq 'requestcourses') {
11464:         my $can_create = 0;
11465:         my ($ownername,$ownerdom) = split(':',$course_owner);
11466:         if ($udom eq $ownerdom) {
11467:             my $reload;
11468:             if (($callercontext eq 'auto') &&
11469:                ($ownerdom eq $env{'user.domain'}) && ($ownername eq $env{'user.name'})) {
11470:                 $reload = 'reload';
11471:             }
11472:             if (&usertools_access($ownername,$ownerdom,$category,$reload,
11473:                                   $context)) {
11474:                 $can_create = 1;
11475:             }
11476:         } else {
11477:             my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
11478:                                            $category);
11479:             if ($userenv{'reqcrsotherdom.'.$category} ne '') {
11480:                 my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
11481:                 if (@curr > 0) {
11482:                     my @options = qw(approval validate autolimit);
11483:                     my $optregex = join('|',@options);
11484:                     if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
11485:                         $can_create = 1;
11486:                     }
11487:                 }
11488:             }
11489:         }
11490:         if ($can_create) {
11491:             unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
11492:                 unless (&allowed('ccc',$udom)) {
11493:                     return 'refused'; 
11494:                 }
11495:             }
11496:         } else {
11497:             return 'refused';
11498:         }
11499:     } elsif (!&allowed('ccc',$udom)) {
11500:         return 'refused';
11501:     }
11502: # --------------------------------------------------------------- Get Unique ID
11503:     my $uname;
11504:     if ($cnum =~ /^$match_courseid$/) {
11505:         my $chome=&homeserver($cnum,$udom,'true');
11506:         if (($chome eq '') || ($chome eq 'no_host')) {
11507:             $uname = $cnum;
11508:         } else {
11509:             $uname = &generate_coursenum($udom,$crstype);
11510:         }
11511:     } else {
11512:         $uname = &generate_coursenum($udom,$crstype);
11513:     }
11514:     return $uname if ($uname =~ /^error/);
11515: # -------------------------------------------------- Check supplied server name
11516:     if (!defined($course_server)) {
11517:         if (defined(&domain($udom,'primary'))) {
11518:             $course_server = &domain($udom,'primary');
11519:         } else {
11520:             $course_server = $env{'user.home'}; 
11521:         }
11522:     }
11523:     my %host_servers =
11524:         &get_servers($udom,'library');
11525:     unless ($host_servers{$course_server}) {
11526:         return 'error: invalid home server for course: '.$course_server;
11527:     }
11528: # ------------------------------------------------------------- Make the course
11529:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
11530:                       $course_server);
11531:     unless ($reply eq 'ok') { return 'error: '.$reply; }
11532:     my $uhome=&homeserver($uname,$udom,'true');
11533:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
11534: 	return 'error: no such course';
11535:     }
11536: # ----------------------------------------------------------------- Course made
11537: # log existence
11538:     my $now = time;
11539:     my $newcourse = {
11540:                     $udom.'_'.$uname => {
11541:                                      description => $description,
11542:                                      inst_code   => $inst_code,
11543:                                      owner       => $course_owner,
11544:                                      type        => $crstype,
11545:                                      creator     => $env{'user.name'}.':'.
11546:                                                     $env{'user.domain'},
11547:                                      created     => $now,
11548:                                      context     => $context,
11549:                                                 },
11550:                     };
11551:     &courseidput($udom,$newcourse,$uhome,'notime');
11552: # set toplevel url
11553:     my $topurl=$url;
11554:     unless ($nonstandard) {
11555: # ------------------------------------------ For standard courses, make top url
11556:         my $mapurl=&clutter($url);
11557:         if ($mapurl eq '/res/') { $mapurl=''; }
11558:         $env{'form.initmap'}=(<<ENDINITMAP);
11559: <map>
11560: <resource id="1" type="start"></resource>
11561: <resource id="2" src="$mapurl"></resource>
11562: <resource id="3" type="finish"></resource>
11563: <link index="1" from="1" to="2"></link>
11564: <link index="2" from="2" to="3"></link>
11565: </map>
11566: ENDINITMAP
11567:         $topurl=&declutter(
11568:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
11569:                           );
11570:     }
11571: # ----------------------------------------------------------- Write preferences
11572:     &writecoursepref($udom.'_'.$uname,
11573:                      ('description'              => $description,
11574:                       'url'                      => $topurl,
11575:                       'internal.creator'         => $env{'user.name'}.':'.
11576:                                                     $env{'user.domain'},
11577:                       'internal.created'         => $now,
11578:                       'internal.creationcontext' => $context)
11579:                     );
11580:     return '/'.$udom.'/'.$uname;
11581: }
11582: 
11583: # ------------------------------------------------------------------- Create ID
11584: sub generate_coursenum {
11585:     my ($udom,$crstype) = @_;
11586:     my $domdesc = &domain($udom);
11587:     return 'error: invalid domain' if ($domdesc eq '');
11588:     my $first;
11589:     if ($crstype eq 'Community') {
11590:         $first = '0';
11591:     } else {
11592:         $first = int(1+rand(9)); 
11593:     } 
11594:     my $uname=$first.
11595:         ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
11596:         substr($$.time,0,5).unpack("H8",pack("I32",time)).
11597:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
11598: # ----------------------------------------------- Make sure that does not exist
11599:     my $uhome=&homeserver($uname,$udom,'true');
11600:     unless (($uhome eq '') || ($uhome eq 'no_host')) {
11601:         if ($crstype eq 'Community') {
11602:             $first = '0';
11603:         } else {
11604:             $first = int(1+rand(9));
11605:         }
11606:         $uname=$first.
11607:                ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
11608:                substr($$.time,0,5).unpack("H8",pack("I32",time)).
11609:                unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
11610:         $uhome=&homeserver($uname,$udom,'true');
11611:         unless (($uhome eq '') || ($uhome eq 'no_host')) {
11612:             return 'error: unable to generate unique course-ID';
11613:         }
11614:     }
11615:     return $uname;
11616: }
11617: 
11618: sub is_course {
11619:     my ($cdom, $cnum) = scalar(@_) == 1 ? 
11620:          ($_[0] =~ /^($match_domain)_($match_courseid)$/)  :  @_;
11621: 
11622:     return unless (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/));
11623:     my $uhome=&homeserver($cnum,$cdom);
11624:     my $iscourse;
11625:     if (grep { $_ eq $uhome } current_machine_ids()) {
11626:         $iscourse = &LONCAPA::Lond::is_course($cdom,$cnum);
11627:     } else {
11628:         my $hashid = $cdom.':'.$cnum;
11629:         ($iscourse,my $cached) = &is_cached_new('iscourse',$hashid);
11630:         unless (defined($cached)) {
11631:             my %courses = &courseiddump($cdom, '.', 1, '.', '.',
11632:                                         $cnum,undef,undef,'.');
11633:             $iscourse = 0;
11634:             if (exists($courses{$cdom.'_'.$cnum})) {
11635:                 $iscourse = 1;
11636:             }
11637:             &do_cache_new('iscourse',$hashid,$iscourse,3600);
11638:         }
11639:     }
11640:     return unless ($iscourse);
11641:     return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
11642: }
11643: 
11644: sub store_userdata {
11645:     my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
11646:     my $result;
11647:     if ($datakey ne '') {
11648:         if (ref($storehash) eq 'HASH') {
11649:             if ($udom eq '' || $uname eq '') {
11650:                 $udom = $env{'user.domain'};
11651:                 $uname = $env{'user.name'};
11652:             }
11653:             my $uhome=&homeserver($uname,$udom);
11654:             if (($uhome eq '') || ($uhome eq 'no_host')) {
11655:                 $result = 'error: no_host';
11656:             } else {
11657:                 $storehash->{'ip'} = &get_requestor_ip();
11658:                 $storehash->{'host'} = $perlvar{'lonHostID'};
11659: 
11660:                 my $namevalue='';
11661:                 foreach my $key (keys(%{$storehash})) {
11662:                     $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
11663:                 }
11664:                 $namevalue=~s/\&$//;
11665:                 unless ($namespace eq 'courserequests') {
11666:                     $datakey = &escape($datakey);
11667:                 }
11668:                 $result =  &reply("store:$udom:$uname:$namespace:$datakey:".
11669:                                   $namevalue,$uhome);
11670:             }
11671:         } else {
11672:             $result = 'error: data to store was not a hash reference'; 
11673:         }
11674:     } else {
11675:         $result= 'error: invalid requestkey'; 
11676:     }
11677:     return $result;
11678: }
11679: 
11680: # ---------------------------------------------------------- Assign Custom Role
11681: 
11682: sub assigncustomrole {
11683:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,
11684:         $selfenroll,$context,$othdomby,$requester)=@_;
11685:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
11686:                        $end,$start,$deleteflag,$selfenroll,$context,$othdomby,
11687:                        $requester);
11688: }
11689: 
11690: # ----------------------------------------------------------------- Revoke Role
11691: 
11692: sub revokerole {
11693:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
11694:     my $now=time;
11695:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
11696: }
11697: 
11698: # ---------------------------------------------------------- Revoke Custom Role
11699: 
11700: sub revokecustomrole {
11701:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
11702:     my $now=time;
11703:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
11704:            $deleteflag,$selfenroll,$context);
11705: }
11706: 
11707: # ------------------------------------------------------------ Disk usage
11708: sub diskusage {
11709:     my ($udom,$uname,$directorypath,$getpropath)=@_;
11710:     $directorypath =~ s/\/$//;
11711:     my $listing=&reply('du2:'.&escape($directorypath).':'
11712:                        .&escape($getpropath).':'.&escape($uname).':'
11713:                        .&escape($udom),homeserver($uname,$udom));
11714:     if ($listing eq 'unknown_cmd') {
11715:         if ($getpropath) {
11716:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
11717:         }
11718:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
11719:     }
11720:     return $listing;
11721: }
11722: 
11723: sub is_locked {
11724:     my ($file_name, $domain, $user, $which) = @_;
11725:     my @check;
11726:     my $is_locked;
11727:     push (@check,$file_name);
11728:     my %locked = &get('file_permissions',\@check,
11729: 		      $env{'user.domain'},$env{'user.name'});
11730:     my ($tmp)=keys(%locked);
11731:     if ($tmp=~/^error:/) { undef(%locked); }
11732:     
11733:     if (ref($locked{$file_name}) eq 'ARRAY') {
11734:         $is_locked = 'false';
11735:         foreach my $entry (@{$locked{$file_name}}) {
11736:            if (ref($entry) eq 'ARRAY') {
11737:                $is_locked = 'true';
11738:                if (ref($which) eq 'ARRAY') {
11739:                    push(@{$which},$entry);
11740:                } else {
11741:                    last;
11742:                }
11743:            }
11744:        }
11745:     } else {
11746:         $is_locked = 'false';
11747:     }
11748:     return $is_locked;
11749: }
11750: 
11751: sub declutter_portfile {
11752:     my ($file) = @_;
11753:     $file =~ s{^(/portfolio/|portfolio/)}{/};
11754:     return $file;
11755: }
11756: 
11757: # ------------------------------------------------------------- Mark as Read Only
11758: 
11759: sub mark_as_readonly {
11760:     my ($domain,$user,$files,$what) = @_;
11761:     my %current_permissions = &dump('file_permissions',$domain,$user);
11762:     my ($tmp)=keys(%current_permissions);
11763:     if ($tmp=~/^error:/) { undef(%current_permissions); }
11764:     foreach my $file (@{$files}) {
11765: 	$file = &declutter_portfile($file);
11766:         push(@{$current_permissions{$file}},$what);
11767:     }
11768:     &put('file_permissions',\%current_permissions,$domain,$user);
11769:     return;
11770: }
11771: 
11772: # ------------------------------------------------------------Save Selected Files
11773: 
11774: sub save_selected_files {
11775:     my ($user, $path, @files) = @_;
11776:     my $filename = $user."savedfiles";
11777:     my @other_files = &files_not_in_path($user, $path);
11778:     open (OUT,'>',LONCAPA::tempdir().$filename);
11779:     foreach my $file (@files) {
11780:         print (OUT $env{'form.currentpath'}.$file."\n");
11781:     }
11782:     foreach my $file (@other_files) {
11783:         print (OUT $file."\n");
11784:     }
11785:     close (OUT);
11786:     return 'ok';
11787: }
11788: 
11789: sub clear_selected_files {
11790:     my ($user) = @_;
11791:     my $filename = $user."savedfiles";
11792:     open (OUT,'>',LONCAPA::tempdir().$filename);
11793:     print (OUT undef);
11794:     close (OUT);
11795:     return ("ok");    
11796: }
11797: 
11798: sub files_in_path {
11799:     my ($user, $path) = @_;
11800:     my $filename = $user."savedfiles";
11801:     my %return_files;
11802:     open (IN,'<',LONCAPA::tempdir().$filename);
11803:     while (my $line_in = <IN>) {
11804:         chomp ($line_in);
11805:         my @paths_and_file = split (m!/!, $line_in);
11806:         my $file_part = pop (@paths_and_file);
11807:         my $path_part = join ('/', @paths_and_file);
11808:         $path_part.='/';
11809:         my $path_and_file = $path_part.$file_part;
11810:         if ($path_part eq $path) {
11811:             $return_files{$file_part}= 'selected';
11812:         }
11813:     }
11814:     close (IN);
11815:     return (\%return_files);
11816: }
11817: 
11818: # called in portfolio select mode, to show files selected NOT in current directory
11819: sub files_not_in_path {
11820:     my ($user, $path) = @_;
11821:     my $filename = $user."savedfiles";
11822:     my @return_files;
11823:     my $path_part;
11824:     open(IN, '<',LONCAPA::tempdir().$filename);
11825:     while (my $line = <IN>) {
11826:         #ok, I know it's clunky, but I want it to work
11827:         my @paths_and_file = split(m|/|, $line);
11828:         my $file_part = pop(@paths_and_file);
11829:         chomp($file_part);
11830:         my $path_part = join('/', @paths_and_file);
11831:         $path_part .= '/';
11832:         my $path_and_file = $path_part.$file_part;
11833:         if ($path_part ne $path) {
11834:             push(@return_files, ($path_and_file));
11835:         }
11836:     }
11837:     close(OUT);
11838:     return (@return_files);
11839: }
11840: 
11841: #------------------------------Submitted/Handedback Portfolio Files Versioning
11842:  
11843: sub portfiles_versioning {
11844:     my ($symb,$domain,$stu_name,$portfiles,$versioned_portfiles) = @_;
11845:     my $portfolio_root = '/userfiles/portfolio';
11846:     return unless ((ref($portfiles) eq 'ARRAY') && (ref($versioned_portfiles) eq 'ARRAY'));
11847:     foreach my $file (@{$portfiles}) {
11848:         &unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
11849:         my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
11850:         my ($answer_name,$answer_ver,$answer_ext) = &file_name_version_ext($answer_file);
11851:         my $getpropath = 1;
11852:         my ($dir_list,$listerror) = &dirlist($portfolio_root.$directory,$domain,
11853:                                              $stu_name,$getpropath);
11854:         my $version = &get_next_version($answer_name,$answer_ext,$dir_list);
11855:         my $new_answer = 
11856:             &version_selected_portfile($domain,$stu_name,$directory,$answer_file,$version);
11857:         if ($new_answer ne 'problem getting file') {
11858:             push(@{$versioned_portfiles}, $directory.$new_answer);
11859:             &mark_as_readonly($domain,$stu_name,[$directory.$new_answer],
11860:                               [$symb,$env{'request.course.id'},'graded']);
11861:         }
11862:     }
11863: }
11864: 
11865: sub get_next_version {
11866:     my ($answer_name, $answer_ext, $dir_list) = @_;
11867:     my $version;
11868:     if (ref($dir_list) eq 'ARRAY') {
11869:         foreach my $row (@{$dir_list}) {
11870:             my ($file) = split(/\&/,$row,2);
11871:             my ($file_name,$file_version,$file_ext) =
11872:                 &file_name_version_ext($file);
11873:             if (($file_name eq $answer_name) &&
11874:                 ($file_ext eq $answer_ext)) {
11875:                      # gets here if filename and extension match,
11876:                      # regardless of version
11877:                 if ($file_version ne '') {
11878:                     # a versioned file is found  so save it for later
11879:                     if ($file_version > $version) {
11880:                         $version = $file_version;
11881:                     }
11882:                 }
11883:             }
11884:         }
11885:     }
11886:     $version ++;
11887:     return($version);
11888: }
11889: 
11890: sub version_selected_portfile {
11891:     my ($domain,$stu_name,$directory,$file_name,$version) = @_;
11892:     my ($answer_name,$answer_ver,$answer_ext) =
11893:         &file_name_version_ext($file_name);
11894:     my $new_answer;
11895:     $env{'form.copy'} =
11896:         &getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
11897:     if($env{'form.copy'} eq '-1') {
11898:         $new_answer = 'problem getting file';
11899:     } else {
11900:         $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
11901:         my $copy_result = 
11902:             &finishuserfileupload($stu_name,$domain,'copy',
11903:                                   '/portfolio'.$directory.$new_answer);
11904:     }
11905:     undef($env{'form.copy'});
11906:     return ($new_answer);
11907: }
11908: 
11909: sub file_name_version_ext {
11910:     my ($file)=@_;
11911:     my @file_parts = split(/\./, $file);
11912:     my ($name,$version,$ext);
11913:     if (@file_parts > 1) {
11914:         $ext=pop(@file_parts);
11915:         if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
11916:             $version=pop(@file_parts);
11917:         }
11918:         $name=join('.',@file_parts);
11919:     } else {
11920:         $name=join('.',@file_parts);
11921:     }
11922:     return($name,$version,$ext);
11923: }
11924: 
11925: #----------------------------------------------Get portfolio file permissions
11926: 
11927: sub get_portfile_permissions {
11928:     my ($domain,$user) = @_;
11929:     my %current_permissions = &dump('file_permissions',$domain,$user);
11930:     my ($tmp)=keys(%current_permissions);
11931:     if ($tmp=~/^error:/) { undef(%current_permissions); }
11932:     return \%current_permissions;
11933: }
11934: 
11935: #---------------------------------------------Get portfolio file access controls
11936: 
11937: sub get_access_controls {
11938:     my ($current_permissions,$group,$file) = @_;
11939:     my %access;
11940:     my $real_file = $file;
11941:     $file =~ s/\.meta$//;
11942:     if (defined($file)) {
11943:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
11944:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
11945:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
11946:             }
11947:         }
11948:     } else {
11949:         foreach my $key (keys(%{$current_permissions})) {
11950:             if ($key =~ /\0accesscontrol$/) {
11951:                 if (defined($group)) {
11952:                     if ($key !~ m-^\Q$group\E/-) {
11953:                         next;
11954:                     }
11955:                 }
11956:                 my ($fullpath) = split(/\0/,$key);
11957:                 if (ref($$current_permissions{$key}) eq 'HASH') {
11958:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
11959:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
11960:                     }
11961:                 }
11962:             }
11963:         }
11964:     }
11965:     return %access;
11966: }
11967: 
11968: sub modify_access_controls {
11969:     my ($file_name,$changes,$domain,$user)=@_;
11970:     my ($outcome,$deloutcome);
11971:     my %store_permissions;
11972:     my %new_values;
11973:     my %new_control;
11974:     my %translation;
11975:     my @deletions = ();
11976:     my $now = time;
11977:     if (exists($$changes{'activate'})) {
11978:         if (ref($$changes{'activate'}) eq 'HASH') {
11979:             my @newitems = sort(keys(%{$$changes{'activate'}}));
11980:             my $numnew = scalar(@newitems);
11981:             for (my $i=0; $i<$numnew; $i++) {
11982:                 my $newkey = $newitems[$i];
11983:                 my $newid = &Apache::loncommon::get_cgi_id();
11984:                 if ($newkey =~ /^\d+:/) { 
11985:                     $newkey =~ s/^(\d+)/$newid/;
11986:                     $translation{$1} = $newid;
11987:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
11988:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
11989:                     $translation{$1} = $newid;
11990:                 }
11991:                 $new_values{$file_name."\0".$newkey} = 
11992:                                           $$changes{'activate'}{$newitems[$i]};
11993:                 $new_control{$newkey} = $now;
11994:             }
11995:         }
11996:     }
11997:     my %todelete;
11998:     my %changed_items;
11999:     foreach my $action ('delete','update') {
12000:         if (exists($$changes{$action})) {
12001:             if (ref($$changes{$action}) eq 'HASH') {
12002:                 foreach my $key (keys(%{$$changes{$action}})) {
12003:                     my ($itemnum) = ($key =~ /^([^:]+):/);
12004:                     if ($action eq 'delete') { 
12005:                         $todelete{$itemnum} = 1;
12006:                     } else {
12007:                         $changed_items{$itemnum} = $key;
12008:                     }
12009:                 }
12010:             }
12011:         }
12012:     }
12013:     # get lock on access controls for file.
12014:     my $lockhash = {
12015:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
12016:                                                        ':'.$env{'user.domain'},
12017:                    }; 
12018:     my $tries = 0;
12019:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
12020:    
12021:     while (($gotlock ne 'ok') && $tries < 10) {
12022:         $tries ++;
12023:         sleep(0.1);
12024:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
12025:     }
12026:     if ($gotlock eq 'ok') {
12027:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
12028:         my ($tmp)=keys(%curr_permissions);
12029:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
12030:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
12031:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
12032:             if (ref($curr_controls) eq 'HASH') {
12033:                 foreach my $control_item (keys(%{$curr_controls})) {
12034:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
12035:                     if (defined($todelete{$itemnum})) {
12036:                         push(@deletions,$file_name."\0".$control_item);
12037:                     } else {
12038:                         if (defined($changed_items{$itemnum})) {
12039:                             $new_control{$changed_items{$itemnum}} = $now;
12040:                             push(@deletions,$file_name."\0".$control_item);
12041:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
12042:                         } else {
12043:                             $new_control{$control_item} = $$curr_controls{$control_item};
12044:                         }
12045:                     }
12046:                 }
12047:             }
12048:         }
12049:         my ($group);
12050:         if (&is_course($domain,$user)) {
12051:             ($group,my $file) = split(/\//,$file_name,2);
12052:         }
12053:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
12054:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
12055:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
12056:         #  remove lock
12057:         my @del_lock = ($file_name."\0".'locked_access_records');
12058:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
12059:         my $sqlresult =
12060:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
12061:                                     $group);
12062:     } else {
12063:         $outcome = "error: could not obtain lockfile\n";  
12064:     }
12065:     return ($outcome,$deloutcome,\%new_values,\%translation);
12066: }
12067: 
12068: sub make_public_indefinitely {
12069:     my (@requrl) = @_;
12070:     return &automated_portfile_access('public',\@requrl);
12071: }
12072: 
12073: sub automated_portfile_access {
12074:     my ($accesstype,$addsref,$delsref,$info) = @_;
12075:     unless (($accesstype eq 'public') || ($accesstype eq 'ip')) {
12076:         return 'invalid';
12077:     }
12078:     my %urls;
12079:     if (ref($addsref) eq 'ARRAY') {
12080:         foreach my $requrl (@{$addsref}) {
12081:             if (&is_portfolio_url($requrl)) {
12082:                 unless (exists($urls{$requrl})) {
12083:                     $urls{$requrl} = 'add';
12084:                 }
12085:             }
12086:         }
12087:     }
12088:     if (ref($delsref) eq 'ARRAY') {
12089:         foreach my $requrl (@{$delsref}) { 
12090:             if (&is_portfolio_url($requrl)) {
12091:                 unless (exists($urls{$requrl})) {
12092:                     $urls{$requrl} = 'delete'; 
12093:                 }
12094:             }
12095:         }
12096:     }
12097:     unless (keys(%urls)) {
12098:         return 'invalid';
12099:     }
12100:     my $ip;
12101:     if ($accesstype eq 'ip') {
12102:         if (ref($info) eq 'HASH') {
12103:             if ($info->{'ip'} ne '') {
12104:                 $ip = $info->{'ip'};
12105:             }
12106:         }
12107:         if ($ip eq '') {
12108:             return 'invalid';
12109:         }
12110:     }
12111:     my $errors;
12112:     my $now = time;
12113:     my %current_perms;
12114:     foreach my $requrl (sort(keys(%urls))) {
12115:         my $action;
12116:         if ($urls{$requrl} eq 'add') {
12117:             $action = 'activate';
12118:         } else {
12119:             $action = 'none';
12120:         }
12121:         my $aclnum = 0;
12122:         my (undef,$udom,$unum,$file_name,$group) =
12123:             &parse_portfolio_url($requrl);
12124:         unless (exists($current_perms{$unum.':'.$udom})) {
12125:             $current_perms{$unum.':'.$udom} = &get_portfile_permissions($udom,$unum);
12126:         }
12127:         my %access_controls = &get_access_controls($current_perms{$unum.':'.$udom},
12128:                                                    $group,$file_name);
12129:         foreach my $key (keys(%{$access_controls{$file_name}})) {
12130:             my ($num,$scope,$end,$start) = 
12131:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
12132:             if ($scope eq $accesstype) {
12133:                 if (($start <= $now) && ($end == 0)) {
12134:                     if ($accesstype eq 'ip') {
12135:                         if (ref($access_controls{$file_name}{$key}) eq 'HASH') {
12136:                             if (ref($access_controls{$file_name}{$key}{'ip'}) eq 'ARRAY') {
12137:                                 if (grep(/^\Q$ip\E$/,@{$access_controls{$file_name}{$key}{'ip'}})) {
12138:                                     if ($urls{$requrl} eq 'add') {
12139:                                         $action = 'none';
12140:                                         last;
12141:                                     } else {
12142:                                         $action = 'delete';
12143:                                         $aclnum = $num;
12144:                                         last;
12145:                                     }
12146:                                 }
12147:                             }
12148:                         }
12149:                     } elsif ($accesstype eq 'public') {
12150:                         if ($urls{$requrl} eq 'add') {
12151:                             $action = 'none';
12152:                             last;
12153:                         } else {
12154:                             $action = 'delete';
12155:                             $aclnum = $num;
12156:                             last;
12157:                         }
12158:                     }
12159:                 } elsif ($accesstype eq 'public') {
12160:                     $action = 'update';
12161:                     $aclnum = $num;
12162:                     last;
12163:                 }
12164:             }
12165:         }
12166:         if ($action eq 'none') {
12167:             next;
12168:         } else {
12169:             my %changes;
12170:             my $newend = 0;
12171:             my $newstart = $now;
12172:             my $newkey = $aclnum.':'.$accesstype.'_'.$newend.'_'.$newstart;
12173:             $changes{$action}{$newkey} = {
12174:                 type => $accesstype,
12175:                 time => {
12176:                     start => $newstart,
12177:                     end   => $newend,
12178:                 },
12179:             };
12180:             if ($accesstype eq 'ip') {
12181:                 $changes{$action}{$newkey}{'ip'} = [$ip];
12182:             }
12183:             my ($outcome,$deloutcome,$new_values,$translation) =
12184:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
12185:             unless ($outcome eq 'ok') {
12186:                 $errors .= $outcome.' ';
12187:             }
12188:         }
12189:     }
12190:     if ($errors) {
12191:         $errors =~ s/\s$//;
12192:         return $errors;
12193:     } else {
12194:         return 'ok';
12195:     }
12196: }
12197: 
12198: #------------------------------------------------------Get Marked as Read Only
12199: 
12200: sub get_marked_as_readonly {
12201:     my ($domain,$user,$what,$group) = @_;
12202:     my $current_permissions = &get_portfile_permissions($domain,$user);
12203:     my @readonly_files;
12204:     my $cmp1=$what;
12205:     if (ref($what)) { $cmp1=join('',@{$what}) };
12206:     while (my ($file_name,$value) = each(%{$current_permissions})) {
12207:         if (defined($group)) {
12208:             if ($file_name !~ m-^\Q$group\E/-) {
12209:                 next;
12210:             }
12211:         }
12212:         if (ref($value) eq "ARRAY"){
12213:             foreach my $stored_what (@{$value}) {
12214:                 my $cmp2=$stored_what;
12215:                 if (ref($stored_what) eq 'ARRAY') {
12216:                     $cmp2=join('',@{$stored_what});
12217:                 }
12218:                 if ($cmp1 eq $cmp2) {
12219:                     push(@readonly_files, $file_name);
12220:                     last;
12221:                 } elsif (!defined($what)) {
12222:                     push(@readonly_files, $file_name);
12223:                     last;
12224:                 }
12225:             }
12226:         }
12227:     }
12228:     return @readonly_files;
12229: }
12230: #-----------------------------------------------------------Get Marked as Read Only Hash
12231: 
12232: sub get_marked_as_readonly_hash {
12233:     my ($current_permissions,$group,$what) = @_;
12234:     my %readonly_files;
12235:     while (my ($file_name,$value) = each(%{$current_permissions})) {
12236:         if (defined($group)) {
12237:             if ($file_name !~ m-^\Q$group\E/-) {
12238:                 next;
12239:             }
12240:         }
12241:         if (ref($value) eq "ARRAY"){
12242:             foreach my $stored_what (@{$value}) {
12243:                 if (ref($stored_what) eq 'ARRAY') {
12244:                     foreach my $lock_descriptor(@{$stored_what}) {
12245:                         if ($lock_descriptor eq 'graded') {
12246:                             $readonly_files{$file_name} = 'graded';
12247:                         } elsif ($lock_descriptor eq 'handback') {
12248:                             $readonly_files{$file_name} = 'handback';
12249:                         } else {
12250:                             if (!exists($readonly_files{$file_name})) {
12251:                                 $readonly_files{$file_name} = 'locked';
12252:                             }
12253:                         }
12254:                     }
12255:                 } 
12256:             }
12257:         } 
12258:     }
12259:     return %readonly_files;
12260: }
12261: # ------------------------------------------------------------ Unmark as Read Only
12262: 
12263: sub unmark_as_readonly {
12264:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
12265:     # for portfolio submissions, $what contains [$symb,$crsid] 
12266:     my ($domain,$user,$what,$file_name,$group) = @_;
12267:     $file_name = &declutter_portfile($file_name);
12268:     my $symb_crs = $what;
12269:     if (ref($what)) { $symb_crs=join('',@$what); }
12270:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
12271:     my ($tmp)=keys(%current_permissions);
12272:     if ($tmp=~/^error:/) { undef(%current_permissions); }
12273:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
12274:     foreach my $file (@readonly_files) {
12275: 	my $clean_file = &declutter_portfile($file);
12276: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
12277: 	my $current_locks = $current_permissions{$file};
12278:         my @new_locks;
12279:         my @del_keys;
12280:         if (ref($current_locks) eq "ARRAY"){
12281:             foreach my $locker (@{$current_locks}) {
12282:                 my $compare=$locker;
12283:                 if (ref($locker) eq 'ARRAY') {
12284:                     $compare=join('',@{$locker});
12285:                     if ($compare ne $symb_crs) {
12286:                         push(@new_locks, $locker);
12287:                     }
12288:                 }
12289:             }
12290:             if (scalar(@new_locks) > 0) {
12291:                 $current_permissions{$file} = \@new_locks;
12292:             } else {
12293:                 push(@del_keys, $file);
12294:                 &del('file_permissions',\@del_keys, $domain, $user);
12295:                 delete($current_permissions{$file});
12296:             }
12297:         }
12298:     }
12299:     &put('file_permissions',\%current_permissions,$domain,$user);
12300:     return;
12301: }
12302: 
12303: # ------------------------------------------------------------ Directory lister
12304: 
12305: sub dirlist {
12306:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
12307:     $uri=~s/^\///;
12308:     $uri=~s/\/$//;
12309:     my ($udom, $uname);
12310:     if ($getuserdir) {
12311:         $udom = $userdomain;
12312:         $uname = $username;
12313:     } else {
12314:         (undef,$udom,$uname)=split(/\//,$uri);
12315:         if(defined($userdomain)) {
12316:             $udom = $userdomain;
12317:         }
12318:         if(defined($username)) {
12319:             $uname = $username;
12320:         }
12321:     }
12322:     my ($dirRoot,$listing,@listing_results);
12323: 
12324:     $dirRoot = $perlvar{'lonDocRoot'};
12325:     if (defined($getpropath)) {
12326:         $dirRoot = &propath($udom,$uname);
12327:         $dirRoot =~ s/\/$//;
12328:     } elsif (defined($getuserdir)) {
12329:         my $subdir=$uname.'__';
12330:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
12331:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
12332:                    ."/$udom/$subdir/$uname";
12333:     } elsif (defined($alternateRoot)) {
12334:         $dirRoot = $alternateRoot;
12335:     }
12336: 
12337:     if($udom) {
12338:         if($uname) {
12339:             my $uhome = &homeserver($uname,$udom);
12340:             if ($uhome eq 'no_host') {
12341:                 return ([],'no_host');
12342:             }
12343:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
12344:                               .$getuserdir.':'.&escape($dirRoot)
12345:                               .':'.&escape($uname).':'.&escape($udom),$uhome);
12346:             if ($listing eq 'unknown_cmd') {
12347:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
12348:             } else {
12349:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
12350:             }
12351:             if ($listing eq 'unknown_cmd') {
12352:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
12353:                 @listing_results = split(/:/,$listing);
12354:             } else {
12355:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
12356:             }
12357:             if (($listing eq 'no_such_host') || ($listing eq 'con_lost') || 
12358:                 ($listing eq 'rejected') || ($listing eq 'refused') ||
12359:                 ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
12360:                 return ([],$listing);
12361:             } else {
12362:                 return (\@listing_results);
12363:             }
12364:         } elsif(!$alternateRoot) {
12365:             my (%allusers,%listerror);
12366: 	    my %servers = &get_servers($udom,'library');
12367:  	    foreach my $tryserver (keys(%servers)) {
12368:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
12369:                                   &escape($udom),$tryserver);
12370:                 if ($listing eq 'unknown_cmd') {
12371: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
12372: 				      $udom, $tryserver);
12373:                 } else {
12374:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
12375:                 }
12376: 		if ($listing eq 'unknown_cmd') {
12377: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
12378: 				      $udom, $tryserver);
12379: 		    @listing_results = split(/:/,$listing);
12380: 		} else {
12381: 		    @listing_results =
12382: 			map { &unescape($_); } split(/:/,$listing);
12383: 		}
12384:                 if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
12385:                     ($listing eq 'rejected') || ($listing eq 'refused') ||
12386:                     ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
12387:                     $listerror{$tryserver} = $listing;
12388:                 } else {
12389: 		    foreach my $line (@listing_results) {
12390: 			my ($entry) = split(/&/,$line,2);
12391: 			$allusers{$entry} = 1;
12392: 		    }
12393: 		}
12394:             }
12395:             my @alluserslist=();
12396:             foreach my $user (sort(keys(%allusers))) {
12397:                 push(@alluserslist,$user.'&user');
12398:             }
12399: 
12400:             if (!%listerror) {
12401:                 # no errors
12402:                 return (\@alluserslist);
12403:             } elsif (scalar(keys(%servers)) == 1) {
12404:                 # one library server, one error 
12405:                 my ($key) = keys(%listerror);
12406:                 return (\@alluserslist, $listerror{$key});
12407:             } elsif ( grep { $_ eq 'con_lost' } values(%listerror) ) {
12408:                 # con_lost indicates that we might miss data from at least one
12409:                 # library server
12410:                 return (\@alluserslist, 'con_lost');
12411:             } else {
12412:                 # multiple library servers and no con_lost -> data should be
12413:                 # complete. 
12414:                 return (\@alluserslist);
12415:             }
12416: 
12417:         } else {
12418:             return ([],'missing username');
12419:         }
12420:     } elsif(!defined($getpropath)) {
12421:         my $path = $perlvar{'lonDocRoot'}.'/res/'; 
12422:         my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
12423:         return (\@all_domains);
12424:     } else {
12425:         return ([],'missing domain');
12426:     }
12427: }
12428: 
12429: # --------------------------------------------- GetFileTimestamp
12430: # This function utilizes dirlist and returns the date stamp for
12431: # when it was last modified.  It will also return an error of -1
12432: # if an error occurs
12433: 
12434: sub GetFileTimestamp {
12435:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
12436:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
12437:     $studentName   = &LONCAPA::clean_username($studentName);
12438:     my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
12439:                                     undef,$getuserdir);
12440:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
12441:         return -1;
12442:     }
12443:     if (ref($fileref) eq 'ARRAY') {
12444:         my @stats = split('&',$fileref->[0]);
12445:         # @stats contains first the filename, then the stat output
12446:         return $stats[10]; # so this is 10 instead of 9.
12447:     } else {
12448:         return -1;
12449:     }
12450: }
12451: 
12452: sub stat_file {
12453:     my ($uri) = @_;
12454:     $uri = &clutter_with_no_wrapper($uri);
12455: 
12456:     my ($udom,$uname,$file);
12457:     if ($uri =~ m-^/(uploaded|editupload)/-) {
12458: 	($udom,$uname,$file) =
12459: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
12460: 	$file = 'userfiles/'.$file;
12461:     }
12462:     if ($uri =~ m-^/res/-) {
12463: 	($udom,$uname) = 
12464: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
12465: 	$file = $uri;
12466:     }
12467: 
12468:     if (!$udom || !$uname || !$file) {
12469: 	# unable to handle the uri
12470: 	return ();
12471:     }
12472:     my $getpropath;
12473:     if ($file =~ /^userfiles\//) {
12474:         $getpropath = 1;
12475:     }
12476:     my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
12477:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
12478:         return ();
12479:     } else {
12480:         if (ref($listref) eq 'ARRAY') {
12481:             my @stats = split('&',$listref->[0]);
12482: 	    shift(@stats); #filename is first
12483: 	    return @stats;
12484:         }
12485:     }
12486:     return ();
12487: }
12488: 
12489: # --------------------------------------------------------- recursedirs
12490: # Recursive function to traverse either a specific user's Authoring Space
12491: # or corresponding Published Resource Space, and populate the hash ref:
12492: # $dirhashref with URLs of all directories, and if $filehashref hash
12493: # ref arg is provided, the URLs of any files, excluding versioned, .meta,
12494: # or .rights files in resource space, and .meta, .save, .log, .bak and
12495: # .rights files in Authoring Space.
12496: #
12497: # Inputs:
12498: #
12499: # $is_home - true if current server is home server for user's space
12500: # $recurse - if true will also traverse subdirectories recursively
12501: # $include - reference to hash containing allowed file extensions.  If provided,
12502: #             files which do not have a matching extension will be ignored.
12503: # $exclude - reference to hash containing excluded file extensions.  If provided,
12504: #             files which have a matching extension will be ignored.
12505: # $nonemptydir - if true, will only populate $fileshashref hash entry for a particular
12506: #             directory with first file found (with acceptable extension).
12507: # $addtopdir - if true, set $dirhashref->{'/'} = 1 
12508: # $toppath - Top level directory (i.e., /res/$dom/$uname or /priv/$dom/$uname
12509: # $relpath - Current path (relative to top level).
12510: # $dirhashref - reference to hash to populate with URLs of directories (Required)
12511: # $filehashref - reference to hash to populate with URLs of files (Optional)
12512: #
12513: # Returns: nothing
12514: #
12515: # Side Effects: populates $dirhashref, and $filehashref (if provided).
12516: #
12517: # Currently used by interface/londocs.pm to create linked select boxes for
12518: # directory and filename to import a Course "Author" resource into a course, and
12519: # also to create linked select boxes for Authoring Space and Directory to choose
12520: # save location for creation of a new "standard" problem from the Course Editor.
12521: #
12522: 
12523: sub recursedirs {
12524:     my ($is_home,$recurse,$include,$exclude,$nonemptydir,$addtopdir,$toppath,$relpath,$dirhashref,$filehashref) = @_;
12525:     return unless (ref($dirhashref) eq 'HASH');
12526:     my $docroot = $perlvar{'lonDocRoot'};
12527:     my $currpath = $docroot.$toppath;
12528:     if ($relpath ne '') {
12529:         $currpath .= "/$relpath";
12530:     }
12531:     my ($savefile,$checkinc,$checkexc);
12532:     if (ref($filehashref)) {
12533:         $savefile = 1;
12534:     }
12535:     if (ref($include) eq 'HASH') {
12536:         $checkinc = 1;
12537:     }
12538:     if (ref($exclude) eq 'HASH') {
12539:         $checkexc = 1;
12540:     }
12541:     if ($is_home) {
12542:         if ((-e $currpath) && (opendir(my $dirh,$currpath))) {
12543:             my $filecount = 0;
12544:             foreach my $item (sort { lc($a) cmp lc($b) } grep(!/^\.+$/,readdir($dirh))) {
12545:                 next if ($item eq '');
12546:                 if (-d "$currpath/$item") {
12547:                     my $newpath;
12548:                     if ($relpath ne '') {
12549:                         $newpath = "$relpath/$item";
12550:                     } else {
12551:                         $newpath = $item;
12552:                     }
12553:                     $dirhashref->{&Apache::lonlocal::js_escape($newpath)} = 1;
12554:                     if ($recurse) {
12555:                         &recursedirs($is_home,$recurse,$include,$exclude,$nonemptydir,$addtopdir,$toppath,$newpath,$dirhashref,$filehashref);
12556:                     }
12557:                 } elsif (($savefile) || ($relpath eq '')) {
12558:                     next if ($nonemptydir && $filecount);
12559:                     if ($checkinc || $checkexc) {
12560:                         my ($extension) = ($item =~ /\.(\w+)$/);
12561:                         if ($checkinc) {
12562:                             next unless ($extension && $include->{$extension});
12563:                         }
12564:                         if ($checkexc) {
12565:                             next if ($extension && $exclude->{$extension});
12566:                         }
12567:                     }
12568:                     if (($relpath eq '') && (!exists($dirhashref->{'/'}))) {
12569:                         $dirhashref->{'/'} = 1;
12570:                     }
12571:                     if ($savefile) {
12572:                         if ($relpath eq '') {
12573:                             $filehashref->{'/'}{$item} = 1;
12574:                         } else {
12575:                             $filehashref->{&Apache::lonlocal::js_escape($relpath)}{$item} = 1;
12576:                         }
12577:                     }
12578:                     $filecount ++;
12579:                 }
12580:             }
12581:             closedir($dirh);
12582:         }
12583:     } else {
12584:         my ($dirlistref,$listerror) =
12585:             &dirlist($toppath.$relpath);
12586:         my @dir_lines;
12587:         my $dirptr=16384;
12588:         if (ref($dirlistref) eq 'ARRAY') {
12589:             my $filecount = 0;
12590:             foreach my $dir_line (sort
12591:                               {
12592:                                   my ($afile)=split('&',$a,2);
12593:                                   my ($bfile)=split('&',$b,2);
12594:                                   return (lc($afile) cmp lc($bfile));
12595:                               } (@{$dirlistref})) {
12596:                 my ($item,$dom,undef,$testdir,undef,undef,undef,undef,$size,undef,$mtime,undef,undef,undef,$obs,undef) =
12597:                     split(/\&/,$dir_line,16);
12598:                 $item =~ s/\s+$//;
12599:                 next if (($item =~ /^\.\.?$/) || ($obs));
12600:                 if ($dirptr&$testdir) {
12601:                     my $newpath;
12602:                     if ($relpath) {
12603:                         $newpath = "$relpath/$item";
12604:                     } else {
12605:                         $newpath = $item;
12606:                     }
12607:                     $dirhashref->{&Apache::lonlocal::js_escape($newpath)} = 1;
12608:                     if ($recurse) {
12609:                         &recursedirs($is_home,$recurse,$include,$exclude,$nonemptydir,$addtopdir,$toppath,$newpath,$dirhashref,$filehashref);
12610:                     }
12611:                 } elsif (($savefile) || ($relpath eq '')) {
12612:                     next if ($nonemptydir && $filecount);
12613:                     if ($checkinc || $checkexc) {
12614:                         my $extension;
12615:                         if ($checkinc) {
12616:                             next unless ($extension && $include->{$extension});
12617:                         }
12618:                         if ($checkexc) {
12619:                             next if ($extension && $exclude->{$extension});
12620:                         }
12621:                     }
12622:                     if (($relpath eq '') && (!exists($dirhashref->{'/'}))) {
12623:                         $dirhashref->{'/'} = 1;
12624:                     }
12625:                     if ($savefile) {
12626:                         if ($relpath eq '') {
12627:                             $filehashref->{'/'}{$item} = 1;
12628:                         } else {
12629:                             $filehashref->{&Apache::lonlocal::js_escape($relpath)}{$item} = 1;
12630:                         }
12631:                     }
12632:                     $filecount ++; 
12633:                 }
12634:             }
12635:         }
12636:     }
12637:     if ($addtopdir) {
12638:         if (($relpath eq '') && (!exists($dirhashref->{'/'}))) {
12639:             $dirhashref->{'/'} = 1;
12640:         }
12641:     }
12642:     return;
12643: }
12644: 
12645: sub priv_exclude {
12646:     return {
12647:              meta => 1,
12648:              save => 1,
12649:              log => 1,
12650:              bak => 1,
12651:              rights => 1,
12652:              DS_Store => 1,
12653:            };
12654: }
12655: 
12656: # -------------------------------------------------------- Value of a Condition
12657: 
12658: # gets the value of a specific preevaluated condition
12659: #    stored in the string  $env{user.state.<cid>}
12660: # or looks up a condition reference in the bighash and if if hasn't
12661: # already been evaluated recurses into docondval to get the value of
12662: # the condition, then memoizing it to 
12663: #   $env{user.state.<cid>.<condition>}
12664: sub directcondval {
12665:     my $number=shift;
12666:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
12667: 	&Apache::lonuserstate::evalstate();
12668:     }
12669:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
12670: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
12671:     } elsif ($number =~ /^_/) {
12672: 	my $sub_condition;
12673: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
12674: 		&GDBM_READER(),0640)) {
12675: 	    $sub_condition=$bighash{'conditions'.$number};
12676: 	    untie(%bighash);
12677: 	}
12678: 	my $value = &docondval($sub_condition);
12679: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
12680: 	return $value;
12681:     }
12682:     if ($env{'user.state.'.$env{'request.course.id'}}) {
12683:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
12684:     } else {
12685:        return 2;
12686:     }
12687: }
12688: 
12689: # get the collection of conditions for this resource
12690: sub condval {
12691:     my $condidx=shift;
12692:     my $allpathcond='';
12693:     foreach my $cond (split(/\|/,$condidx)) {
12694: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
12695: 	    $allpathcond.=
12696: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
12697: 	}
12698:     }
12699:     $allpathcond=~s/\|$//;
12700:     return &docondval($allpathcond);
12701: }
12702: 
12703: #evaluates an expression of conditions
12704: sub docondval {
12705:     my ($allpathcond) = @_;
12706:     my $result=0;
12707:     if ($env{'request.course.id'}
12708: 	&& defined($allpathcond)) {
12709: 	my $operand='|';
12710: 	my @stack;
12711: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
12712: 	    if ($chunk eq '(') {
12713: 		push @stack,($operand,$result);
12714: 	    } elsif ($chunk eq ')') {
12715: 		my $before=pop @stack;
12716: 		if (pop @stack eq '&') {
12717: 		    $result=$result>$before?$before:$result;
12718: 		} else {
12719: 		    $result=$result>$before?$result:$before;
12720: 		}
12721: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
12722: 		$operand=$chunk;
12723: 	    } else {
12724: 		my $new=directcondval($chunk);
12725: 		if ($operand eq '&') {
12726: 		    $result=$result>$new?$new:$result;
12727: 		} else {
12728: 		    $result=$result>$new?$result:$new;
12729: 		}
12730: 	    }
12731: 	}
12732:     }
12733:     return $result;
12734: }
12735: 
12736: # ---------------------------------------------------- Devalidate courseresdata
12737: 
12738: sub devalidatecourseresdata {
12739:     my ($coursenum,$coursedomain)=@_;
12740:     my $hashid=$coursenum.':'.$coursedomain;
12741:     &devalidate_cache_new('courseres',$hashid);
12742: }
12743: 
12744: 
12745: # --------------------------------------------------- Course Resourcedata Query
12746: #
12747: #  Parameters:
12748: #      $coursenum    - Number of the course.
12749: #      $coursedomain - Domain at which the course was created.
12750: #  Returns:
12751: #     A hash of the course parameters along (I think) with timestamps
12752: #     and version info.
12753: 
12754: sub get_courseresdata {
12755:     my ($coursenum,$coursedomain)=@_;
12756:     my $coursehom=&homeserver($coursenum,$coursedomain);
12757:     my $hashid=$coursenum.':'.$coursedomain;
12758:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
12759:     my %dumpreply;
12760:     unless (defined($cached)) {
12761: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
12762: 	$result=\%dumpreply;
12763: 	my ($tmp) = keys(%dumpreply);
12764: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
12765: 	    &do_cache_new('courseres',$hashid,$result,600);
12766: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
12767: 	    return $tmp;
12768: 	} elsif ($tmp =~ /^(error)/) {
12769: 	    $result=undef;
12770: 	    &do_cache_new('courseres',$hashid,$result,600);
12771: 	}
12772:     }
12773:     return $result;
12774: }
12775: 
12776: sub devalidateuserresdata {
12777:     my ($uname,$udom)=@_;
12778:     my $hashid="$udom:$uname";
12779:     &devalidate_cache_new('userres',$hashid);
12780: }
12781: 
12782: sub get_userresdata {
12783:     my ($uname,$udom)=@_;
12784:     #most student don\'t have any data set, check if there is some data
12785:     if (&EXT_cache_status($udom,$uname)) { return undef; }
12786: 
12787:     my $hashid="$udom:$uname";
12788:     my ($result,$cached)=&is_cached_new('userres',$hashid);
12789:     if (!defined($cached)) {
12790: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
12791: 	$result=\%resourcedata;
12792: 	&do_cache_new('userres',$hashid,$result,600);
12793:     }
12794:     my ($tmp)=keys(%$result);
12795:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
12796: 	return $result;
12797:     }
12798:     #error 2 occurs when the .db doesn't exist
12799:     if ($tmp!~/error: 2 /) {
12800:         if ((!defined($cached)) || ($tmp ne 'con_lost')) {
12801: 	    &logthis("<font color=\"blue\">WARNING:".
12802: 		     " Trying to get resource data for ".
12803: 		     $uname." at ".$udom.": ".
12804: 		     $tmp."</font>");
12805:         }
12806:     } elsif ($tmp=~/error: 2 /) {
12807: 	#&EXT_cache_set($udom,$uname);
12808: 	&do_cache_new('userres',$hashid,undef,600);
12809: 	undef($tmp); # not really an error so don't send it back
12810:     }
12811:     return $tmp;
12812: }
12813: #----------------------------------------------- resdata - return resource data
12814: #  Purpose:
12815: #    Return resource data for either users or for a course.
12816: #  Parameters:
12817: #     $name      - Course/user name.
12818: #     $domain    - Name of the domain the user/course is registered on.
12819: #     $type      - Type of thing $name is (must be 'course' or 'user')
12820: #     $mapp      - decluttered URL of enclosing map  
12821: #     $recursed  - Ref to scalar -- set to 1, if nested maps have been recursed.
12822: #     $recurseup - Ref to array of map URLs, starting with map containing
12823: #                  $mapp up through hierarchy of nested maps to top level map.  
12824: #     $courseid  - CourseID (first part of param identifier).
12825: #     $modifier  - Middle part of param identifier.
12826: #     $what      - Last part of param identifier.
12827: #     @which     - Array of names of resources desired.
12828: #  Returns:
12829: #     The value of the first reasource in @which that is found in the
12830: #     resource hash.
12831: #  Exceptional Conditions:
12832: #     If the $type passed in is not valid (not the string 'course' or 
12833: #     'user', an undefined  reference is returned.
12834: #     If none of the resources are found, an undef is returned
12835: sub resdata {
12836:     my ($name,$domain,$type,$mapp,$recursed,$recurseup,$courseid,
12837:         $modifier,$what,@which)=@_;
12838:     my $result;
12839:     if ($type eq 'course') {
12840: 	$result=&get_courseresdata($name,$domain);
12841:     } elsif ($type eq 'user') {
12842: 	$result=&get_userresdata($name,$domain);
12843:     }
12844:     if (!ref($result)) { return $result; }    
12845:     foreach my $item (@which) {
12846:         if ($item->[1] eq 'course') {
12847:             if ((ref($recurseup) eq 'ARRAY') && (ref($recursed) eq 'SCALAR')) {
12848:                 unless ($$recursed) {
12849:                     @{$recurseup} = &get_map_hierarchy($mapp,$courseid);
12850:                     $$recursed = 1;
12851:                 }
12852:                 foreach my $item (@${recurseup}) {
12853:                     my $norecursechk=$courseid.$modifier.$item.'___(all).'.$what;
12854:                     last if (defined($result->{$norecursechk}));
12855:                     my $recursechk=$courseid.$modifier.$item.'___(rec).'.$what;
12856:                     if (defined($result->{$recursechk})) { return [$result->{$recursechk},'map']; }
12857:                 }
12858:             }
12859:         }
12860:         if (defined($result->{$item->[0]})) {
12861: 	    return [$result->{$item->[0]},$item->[1]];
12862: 	}
12863:     }
12864:     return undef;
12865: }
12866: 
12867: sub get_domain_lti {
12868:     my ($cdom,$context) = @_;
12869:     my ($name,$cachename,%lti);
12870:     if ($context eq 'consumer') {
12871:         $name = 'ltitools';
12872:     } elsif ($context eq 'provider') {
12873:         $name = 'lti';
12874:     } elsif ($context eq 'linkprot') {
12875:         $name = 'ltisec';
12876:     } else {
12877:         return %lti;
12878:     }
12879:     if ($context eq 'linkprot') {
12880:         $cachename = $context;
12881:     } else {
12882:         $cachename = $name;
12883:     }
12884:     my ($result,$cached)=&is_cached_new($cachename,$cdom);
12885:     if (defined($cached)) {
12886:         if (ref($result) eq 'HASH') {
12887:             %lti = %{$result};
12888:         }
12889:     } else {
12890:         my %domconfig = &get_dom('configuration',[$name],$cdom);
12891:         if (ref($domconfig{$name}) eq 'HASH') {
12892:             if ($context eq 'linkprot') {
12893:                 if (ref($domconfig{$name}{'linkprot'}) eq 'HASH') {
12894:                     %lti = %{$domconfig{$name}{'linkprot'}};
12895:                 }
12896:             } else {
12897:                 %lti = %{$domconfig{$name}};
12898:             }
12899:         }
12900:         my $cachetime = 24*60*60;
12901:         &do_cache_new($cachename,$cdom,\%lti,$cachetime);
12902:     }
12903:     return %lti;
12904: }
12905: 
12906: sub get_course_lti {
12907:     my ($cnum,$cdom,$context) = @_;
12908:     my ($name,$cachename,%lti);
12909:     if ($context eq 'consumer') {
12910:         $name = 'ltitools';
12911:         $cachename = 'courseltitools';
12912:     } elsif ($context eq 'provider') {
12913:         $name = 'lti';
12914:         $cachename = 'courselti';
12915:     } else {
12916:         return %lti;
12917:     }
12918:     my $hashid=$cdom.'_'.$cnum;
12919:     my ($result,$cached)=&is_cached_new($cachename,$hashid);
12920:     if (defined($cached)) {
12921:         if (ref($result) eq 'HASH') {
12922:             %lti = %{$result};
12923:         }
12924:     } else {
12925:         %lti = &dump($name,$cdom,$cnum,undef,undef,undef,1);
12926:         my $cachetime = 24*60*60;
12927:         &do_cache_new($cachename,$hashid,\%lti,$cachetime);
12928:     }
12929:     return %lti;
12930: }
12931: 
12932: sub courselti_itemid {
12933:     my ($cnum,$cdom,$url,$method,$params,$context) = @_;
12934:     my ($chome,$itemid);
12935:     $chome = &homeserver($cnum,$cdom);
12936:     return if ($chome eq 'no_host');
12937:     if (ref($params) eq 'HASH') {
12938:         my $rep;
12939:         if (grep { $_ eq $chome } current_machine_ids()) {
12940:             $rep = LONCAPA::Lond::crslti_itemid($cdom,$cnum,$url,$method,$params,$perlvar{'lonVersion'});
12941:         } else {
12942:             my $escurl = &escape($url);
12943:             my $escmethod = &escape($method);
12944:             my $items = &freeze_escape($params);
12945:             $rep = &reply("encrypt:lti:$cdom:$cnum:$context:$escurl:$escmethod:$items",$chome);
12946:         }
12947:         unless (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
12948:                 ($rep eq 'unknown_cmd')) {
12949:             $itemid = $rep;
12950:         }
12951:     }
12952:     return $itemid;
12953: }
12954: 
12955: sub domainlti_itemid {
12956:     my ($cdom,$url,$method,$params,$context) = @_;
12957:     my ($primary_id,$itemid);
12958:     $primary_id = &domain($cdom,'primary');
12959:     return if ($primary_id eq '');
12960:     if (ref($params) eq 'HASH') {
12961:         my $rep;
12962:         if (grep { $_ eq $primary_id } current_machine_ids()) {
12963:             $rep = LONCAPA::Lond::domlti_itemid($cdom,$context,$url,$method,$params,$perlvar{'lonVersion'});
12964:         } else {
12965:             my $cnum = '';
12966:             my $escurl = &escape($url);
12967:             my $escmethod = &escape($method);
12968:             my $items = &freeze_escape($params);
12969:             $rep = &reply("encrypt:lti:$cdom:$cnum:$context:$escurl:$escmethod:$items",$primary_id);
12970:         }
12971:         unless (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
12972:                 ($rep eq 'unknown_cmd')) {
12973:             $itemid = $rep;
12974:         }
12975:     }
12976:     return $itemid;
12977: }
12978: 
12979: sub get_ltitools_id {
12980:     my ($context,$cdom,$cnum,$title) = @_;
12981:     my ($lockhash,$tries,$gotlock,$id,$error);
12982: 
12983:     # get lock on ltitools db
12984:     $lockhash = {
12985:                    lock => $env{'user.name'}.
12986:                            ':'.$env{'user.domain'},
12987:                 };
12988:     $tries = 0;
12989:     if ($context eq 'domain') {
12990:         $gotlock = &newput_dom('ltitools',$lockhash,$cdom);
12991:     } else {
12992:         $gotlock = &newput('ltitools',$lockhash,$cdom,$cnum);
12993:     }
12994:     while (($gotlock ne 'ok') && ($tries<10)) {
12995:         $tries ++;
12996:         sleep (0.1);
12997:         if ($context eq 'domain') {
12998:             $gotlock = &newput_dom('ltitools',$lockhash,$cdom);
12999:         } else {
13000:             $gotlock = &newput('ltitools',$lockhash,$cdom,$cnum);
13001:         }
13002:     }
13003:     if ($gotlock eq 'ok') {
13004:         my %currids;
13005:         if ($context eq 'domain') {
13006:             %currids = &dump_dom('ltitools',$cdom);
13007:         } else {
13008:             %currids = &dump('ltitools',$cdom,$cnum);
13009:         }
13010:         if ($currids{'lock'}) {
13011:             delete($currids{'lock'});
13012:             if (keys(%currids)) {
13013:                 my @curr = sort { $a <=> $b } keys(%currids);
13014:                 if ($curr[-1] =~ /^\d+$/) {
13015:                     $id = 1 + $curr[-1];
13016:                 }
13017:             } else {
13018:                 $id = 1;
13019:             }
13020:             if ($id) {
13021:                 if ($context eq 'domain') {
13022:                     unless (&newput_dom('ltitools',{ $id => $title },$cdom) eq 'ok') {
13023:                         $error = 'nostore';
13024:                     }
13025:                 } else {
13026:                     unless (&newput('ltitools',{ $id => $title },$cdom,$cnum) eq 'ok') {
13027:                         $error = 'nostore';
13028:                     }
13029:                 }
13030:             } else {
13031:                 $error = 'nonumber';
13032:             }
13033:         }
13034:         my $dellockoutcome;
13035:         if ($context eq 'domain') {
13036:             $dellockoutcome = &del_dom('ltitools',['lock'],$cdom);
13037:         } else {
13038:             $dellockoutcome = &del('ltitools',['lock'],$cdom,$cnum);
13039:         }
13040:     } else {
13041:         $error = 'nolock';
13042:     }
13043:     return ($id,$error);
13044: }
13045: 
13046: sub count_supptools {
13047:     my ($cnum,$cdom,$ignorecache,$reload)=@_;
13048:     my $hashid=$cnum.':'.$cdom;
13049:     my ($numexttools,$cached);
13050:     unless ($ignorecache) {
13051:         ($numexttools,$cached) = &is_cached_new('supptools',$hashid);
13052:     }
13053:     unless (defined($cached)) {
13054:         my $chome=&homeserver($cnum,$cdom);
13055:         $numexttools = 0;
13056:         unless ($chome eq 'no_host') {
13057:             my ($supplemental) = &Apache::loncommon::get_supplemental($cnum,$cdom,$reload);
13058:             if (ref($supplemental) eq 'HASH') {
13059:                 if ((ref($supplemental->{'ids'}) eq 'HASH') && (ref($supplemental->{'hidden'}) eq 'HASH')) {
13060:                     foreach my $key (keys(%{$supplemental->{'ids'}})) {
13061:                         if ($key =~ m{^/adm/$cdom/$cnum/\d+/ext\.tool$}) {
13062:                             $numexttools ++;
13063:                         }
13064:                     }
13065:                 }
13066:             }
13067:         }
13068:         &do_cache_new('supptools',$hashid,$numexttools,600);
13069:     }
13070:     return $numexttools;
13071: }
13072: 
13073: sub has_unhidden_suppfiles {
13074:     my ($cnum,$cdom,$ignorecache,$possdel)=@_;
13075:     my $hashid=$cnum.':'.$cdom;
13076:     my ($showsupp,$cached);
13077:     unless ($ignorecache) {
13078:         ($showsupp,$cached) = &is_cached_new('showsupp',$hashid);
13079:     }
13080:     unless (defined($cached)) {
13081:         my $chome=&homeserver($cnum,$cdom);
13082:         unless ($chome eq 'no_host') {
13083:             my ($supplemental) = &Apache::loncommon::get_supplemental($cnum,$cdom,$ignorecache,$possdel);
13084:             if (ref($supplemental) eq 'HASH') {
13085:                 if ((ref($supplemental->{'ids'}) eq 'HASH') && (ref($supplemental->{'hidden'}) eq 'HASH')) {
13086:                     foreach my $key (keys(%{$supplemental->{'ids'}})) {
13087:                         next if ($key =~ /\.sequence$/);
13088:                         if (ref($supplemental->{'ids'}->{$key}) eq 'ARRAY') {
13089:                             foreach my $id (@{$supplemental->{'ids'}->{$key}}) {
13090:                                 unless ($supplemental->{'hidden'}->{$id}) {
13091:                                     $showsupp = 1;
13092:                                     last;
13093:                                 }
13094:                             }
13095:                         }
13096:                         last if ($showsupp);
13097:                     }
13098:                 }
13099:             }
13100:         }
13101:         &do_cache_new('showsupp',$hashid,$showsupp,600);
13102:     }
13103:     return $showsupp;
13104: }
13105: 
13106: #
13107: # EXT resource caching routines
13108: #
13109: 
13110: {
13111: # Cache (5 seconds) of map hierarchy for speedup of navmaps display
13112: #
13113: # The course for which we cache
13114: my $cachedmapkey='';
13115: # The cached recursive maps for this course
13116: my %cachedmaps=();
13117: # When this was last done
13118: my $cachedmaptime='';
13119: 
13120: sub clear_EXT_cache_status {
13121:     &delenv('cache.EXT.');
13122: }
13123: 
13124: sub EXT_cache_status {
13125:     my ($target_domain,$target_user) = @_;
13126:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
13127:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
13128:         # We know already the user has no data
13129:         return 1;
13130:     } else {
13131:         return 0;
13132:     }
13133: }
13134: 
13135: sub EXT_cache_set {
13136:     my ($target_domain,$target_user) = @_;
13137:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
13138:     #&appenv({$cachename => time});
13139: }
13140: 
13141: # --------------------------------------------------------- Value of a Variable
13142: sub EXT {
13143: 
13144:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse,$cid,$recurseupref)=@_;
13145:     unless ($varname) { return ''; }
13146:     #get real user name/domain, courseid and symb
13147:     my $courseid;
13148:     my $publicuser;
13149:     if ($symbparm) {
13150: 	$symbparm=&get_symb_from_alias($symbparm);
13151:     }
13152:     if (!($uname && $udom)) {
13153:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
13154:       if (!$symbparm) {	$symbparm=$cursymb; }
13155:     } else {
13156: 	$courseid=$env{'request.course.id'};
13157:     }
13158:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
13159:     my $rest;
13160:     if (defined($therest[0])) {
13161:        $rest=join('.',@therest);
13162:     } else {
13163:        $rest='';
13164:     }
13165: 
13166:     my $qualifierrest=$qualifier;
13167:     if ($rest) { $qualifierrest.='.'.$rest; }
13168:     my $spacequalifierrest=$space;
13169:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
13170:     if ($realm eq 'user') {
13171: # --------------------------------------------------------------- user.resource
13172: 	if ($space eq 'resource') {
13173: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
13174: 		  || defined($Apache::lonhomework::parsing_a_task))
13175: 		 &&
13176: 		 ($symbparm eq &symbread()) ) {
13177: 		# if we are in the middle of processing the resource the
13178: 		# get the value we are planning on committing
13179:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
13180:                     return $Apache::lonhomework::results{$qualifierrest};
13181:                 } else {
13182:                     return $Apache::lonhomework::history{$qualifierrest};
13183:                 }
13184: 	    } else {
13185: 		my %restored;
13186: 		if ($publicuser || $env{'request.state'} eq 'construct') {
13187: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
13188: 		} else {
13189: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
13190: 		}
13191: 		return $restored{$qualifierrest};
13192: 	    }
13193: # ----------------------------------------------------------------- user.access
13194:         } elsif ($space eq 'access') {
13195: 	    # FIXME - not supporting calls for a specific user
13196:             return &allowed($qualifier,$rest);
13197: # ------------------------------------------ user.preferences, user.environment
13198:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
13199: 	    if (($uname eq $env{'user.name'}) &&
13200: 		($udom eq $env{'user.domain'})) {
13201: 		return $env{join('.',('environment',$qualifierrest))};
13202: 	    } else {
13203: 		my %returnhash;
13204: 		if (!$publicuser) {
13205: 		    %returnhash=&userenvironment($udom,$uname,
13206: 						 $qualifierrest);
13207: 		}
13208: 		return $returnhash{$qualifierrest};
13209: 	    }
13210: # ----------------------------------------------------------------- user.course
13211:         } elsif ($space eq 'course') {
13212: 	    # FIXME - not supporting calls for a specific user
13213:             return $env{join('.',('request.course',$qualifier))};
13214: # ------------------------------------------------------------------- user.role
13215:         } elsif ($space eq 'role') {
13216: 	    # FIXME - not supporting calls for a specific user
13217:             my ($role,$where)=split(/\./,$env{'request.role'});
13218:             if ($qualifier eq 'value') {
13219: 		return $role;
13220:             } elsif ($qualifier eq 'extent') {
13221:                 return $where;
13222:             }
13223: # ----------------------------------------------------------------- user.domain
13224:         } elsif ($space eq 'domain') {
13225:             return $udom;
13226: # ------------------------------------------------------------------- user.name
13227:         } elsif ($space eq 'name') {
13228:             return $uname;
13229: # ---------------------------------------------------- Any other user namespace
13230:         } else {
13231: 	    my %reply;
13232: 	    if (!$publicuser) {
13233: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
13234: 	    }
13235: 	    return $reply{$qualifierrest};
13236:         }
13237:     } elsif ($realm eq 'query') {
13238: # ---------------------------------------------- pull stuff out of query string
13239:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
13240: 						[$spacequalifierrest]);
13241: 	return $env{'form.'.$spacequalifierrest}; 
13242:    } elsif ($realm eq 'request') {
13243: # ------------------------------------------------------------- request.browser
13244:         if ($space eq 'browser') {
13245:             return $env{'browser.'.$qualifier};
13246: # ------------------------------------------------------------ request.filename
13247:         } else {
13248:             return $env{'request.'.$spacequalifierrest};
13249:         }
13250:     } elsif ($realm eq 'course') {
13251: # ---------------------------------------------------------- course.description
13252:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
13253:     } elsif ($realm eq 'resource') {
13254: 
13255: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
13256: 	    if (!$symbparm) { $symbparm=&symbread(); }
13257: 	}
13258: 
13259:         if ($qualifier eq '') {
13260: 	    if ($space eq 'title') {
13261: 	        if (!$symbparm) { $symbparm = $env{'request.filename'}; }
13262: 	        return &gettitle($symbparm);
13263: 	    }
13264: 	
13265: 	    if ($space eq 'map') {
13266: 	        my ($map) = &decode_symb($symbparm);
13267: 	        return &symbread($map);
13268: 	    }
13269:             if ($space eq 'maptitle') {
13270:                 my ($map) = &decode_symb($symbparm);
13271:                 return &gettitle($map);
13272:             }
13273: 	    if ($space eq 'filename') {
13274: 	        if ($symbparm) {
13275: 		    return &clutter((&decode_symb($symbparm))[2]);
13276: 	        }
13277: 	        return &hreflocation('',$env{'request.filename'});
13278: 	    }
13279: 
13280:             if ((defined($courseid)) && ($courseid eq $env{'request.course.id'}) && $symbparm) {
13281:                 if ($space eq 'visibleparts') {
13282:                     my $navmap = Apache::lonnavmaps::navmap->new();
13283:                     my $item;
13284:                     if (ref($navmap)) {
13285:                         my $res = $navmap->getBySymb($symbparm);
13286:                         my $parts = $res->parts();
13287:                         if (ref($parts) eq 'ARRAY') {
13288:                             $item = join(',',@{$parts});
13289:                         }
13290:                         undef($navmap);
13291:                     }
13292:                     return $item;
13293:                 }
13294:             }
13295:         }
13296: 
13297: 	my ($section, $group, @groups, @recurseup, $recursed);
13298:         if (ref($recurseupref) eq 'ARRAY') {
13299:             @recurseup = @{$recurseupref};
13300:             $recursed = 1;
13301:         }
13302: 	my ($courselevelm,$courseleveli,$courselevel,$mapp);
13303:         if (($courseid eq '') && ($cid)) {
13304:             $courseid = $cid;
13305:         }
13306: 	if (($symbparm && $courseid) && 
13307: 	    (($courseid eq $env{'request.course.id'}) || ($courseid eq $cid)))  {
13308: 
13309: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
13310: 
13311: # ----------------------------------------------------- Cascading lookup scheme
13312: 	    my $symbp=$symbparm;
13313: 	    $mapp=&deversion((&decode_symb($symbp))[0]);
13314: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
13315:             my $recurseparm=$mapp.'___(rec).'.$spacequalifierrest;
13316: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
13317: 	    if (($env{'user.name'} eq $uname) &&
13318: 		($env{'user.domain'} eq $udom)) {
13319: 		$section=$env{'request.course.sec'};
13320:                 @groups = split(/:/,$env{'request.course.groups'});  
13321:                 @groups=&sort_course_groups($courseid,@groups); 
13322: 	    } else {
13323: 		if (! defined($usection)) {
13324: 		    $section=&getsection($udom,$uname,$courseid);
13325: 		} else {
13326: 		    $section = $usection;
13327: 		}
13328:                 @groups = &get_users_groups($udom,$uname,$courseid);
13329: 	    }
13330: 
13331: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
13332: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
13333:             my $secleveli=$courseid.'.['.$section.'].'.$recurseparm;
13334: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
13335: 
13336: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
13337: 	    my $courselevelr=$courseid.'.'.$symbparm;
13338:             $courseleveli=$courseid.'.'.$recurseparm;
13339: 	    $courselevelm=$courseid.'.'.$mapparm;
13340: 
13341: # ----------------------------------------------------------- first, check user
13342: 
13343: 	    my $userreply=&resdata($uname,$udom,'user',$mapp,\$recursed,
13344:                                    \@recurseup,$courseid,'.',$spacequalifierrest, 
13345: 				       ([$courselevelr,'resource'],
13346: 					[$courselevelm,'map'     ],
13347:                                         [$courseleveli,'map'     ],
13348: 					[$courselevel, 'course'  ]));
13349: 	    if (defined($userreply)) { return &get_reply($userreply); }
13350: 
13351: # ------------------------------------------------ second, check some of course
13352:             my $coursereply;
13353:             if (@groups > 0) {
13354:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
13355:                                        $recurseparm,$mapparm,$spacequalifierrest,
13356:                                        $mapp,\$recursed,\@recurseup);
13357:                 if (defined($coursereply)) { return &get_reply($coursereply); } 
13358:             }
13359: 
13360: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
13361: 				  $env{'course.'.$courseid.'.domain'},
13362: 				  'course',$mapp,\$recursed,\@recurseup,
13363:                                   $courseid,'.['.$section.'].',$spacequalifierrest,
13364: 				  ([$seclevelr,   'resource'],
13365: 				   [$seclevelm,   'map'     ],
13366:                                    [$secleveli,   'map'     ],
13367: 				   [$seclevel,    'course'  ],
13368: 				   [$courselevelr,'resource']));
13369: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
13370: 
13371: # ------------------------------------------------------ third, check map parms
13372: 	    my %parmhash=();
13373: 	    my $thisparm='';
13374: 	    if (tie(%parmhash,'GDBM_File',
13375: 		    $env{'request.course.fn'}.'_parms.db',
13376: 		    &GDBM_READER(),0640)) {
13377: 		$thisparm=$parmhash{$symbparm};
13378: 		untie(%parmhash);
13379: 	    }
13380: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
13381: 	}
13382: # ------------------------------------------ fourth, look in resource metadata
13383:  
13384:         my $what = $spacequalifierrest;
13385: 	$what=~s/\./\_/;
13386: 	my $filename;
13387: 	if (!$symbparm) { $symbparm=&symbread(); }
13388: 	if ($symbparm) {
13389: 	    $filename=(&decode_symb($symbparm))[2];
13390: 	} else {
13391: 	    $filename=$env{'request.filename'};
13392: 	}
13393:         my $toolsymb;
13394:         if (($filename =~ /ext\.tool$/) && ($what ne '0_gradable')) {
13395:             $toolsymb = $symbparm;
13396:         }
13397: 	my $metadata=&metadata($filename,$what,$toolsymb);
13398: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
13399: 	$metadata=&metadata($filename,'parameter_'.$what,$toolsymb);
13400: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
13401: 
13402: # ----------------------------------------------- fifth, look in rest of course
13403: 	if ($symbparm && defined($courseid) && 
13404: 	    $courseid eq $env{'request.course.id'}) {
13405: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
13406: 				     $env{'course.'.$courseid.'.domain'},
13407: 				     'course',$mapp,\$recursed,\@recurseup,
13408:                                      $courseid,'.',$spacequalifierrest,
13409: 				     ([$courselevelm,'map'   ],
13410:                                       [$courseleveli,'map'   ],
13411: 				      [$courselevel, 'course']));
13412: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
13413: 	}
13414: # ------------------------------------------------------------------ Cascade up
13415: 	unless ($space eq '0') {
13416: 	    my @parts=split(/_/,$space);
13417: 	    my $id=pop(@parts);
13418: 	    my $part=join('_',@parts);
13419: 	    if ($part eq '') { $part='0'; }
13420: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
13421: 				 $symbparm,$udom,$uname,$section,1);
13422: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
13423: 	}
13424: 	if ($recurse) { return undef; }
13425: 	my $pack_def=&packages_tab_default($filename,$varname,$toolsymb);
13426: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
13427: # ---------------------------------------------------- Any other user namespace
13428:     } elsif ($realm eq 'environment') {
13429: # ----------------------------------------------------------------- environment
13430: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
13431: 	    return $env{'environment.'.$spacequalifierrest};
13432: 	} else {
13433: 	    if ($uname eq 'anonymous' && $udom eq '') {
13434: 		return '';
13435: 	    }
13436: 	    my %returnhash=&userenvironment($udom,$uname,
13437: 					    $spacequalifierrest);
13438: 	    return $returnhash{$spacequalifierrest};
13439: 	}
13440:     } elsif ($realm eq 'system') {
13441: # ----------------------------------------------------------------- system.time
13442: 	if ($space eq 'time') {
13443: 	    return time;
13444:         }
13445:     } elsif ($realm eq 'server') {
13446: # ----------------------------------------------------------------- system.time
13447: 	if ($space eq 'name') {
13448: 	    return $ENV{'SERVER_NAME'};
13449:         }
13450:     } elsif ($realm eq 'client') {
13451:         if ($space eq 'remote_addr') {
13452:             return &get_requestor_ip();
13453:         }
13454:     }
13455:     return '';
13456: }
13457: 
13458: sub get_reply {
13459:     my ($reply_value) = @_;
13460:     if (ref($reply_value) eq 'ARRAY') {
13461:         if (wantarray) {
13462: 	    return @$reply_value;
13463:         }
13464:         return $reply_value->[0];
13465:     } else {
13466:         return $reply_value;
13467:     }
13468: }
13469: 
13470: sub check_group_parms {
13471:     my ($courseid,$groups,$symbparm,$recurseparm,$mapparm,$what,$mapp,
13472:         $recursed,$recurseupref) = @_;
13473:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$recurseparm,'map'],
13474:                   [$what,'course']);
13475:     my $coursereply;
13476:     foreach my $group (@{$groups}) {
13477:         my @groupitems = ();
13478:         foreach my $level (@levels) {
13479:              my $item = $courseid.'.['.$group.'].'.$level->[0];
13480:              push(@groupitems,[$item,$level->[1]]);
13481:         }
13482:         my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
13483:                                    $env{'course.'.$courseid.'.domain'},
13484:                                    'course',$mapp,$recursed,$recurseupref,
13485:                                    $courseid,'.['.$group.'].',$what,
13486:                                    @groupitems);
13487:         last if (defined($coursereply));
13488:     }
13489:     return $coursereply;
13490: }
13491: 
13492: sub get_map_hierarchy {
13493:     my ($mapname,$courseid) = @_;
13494:     my @recurseup = ();
13495:     if ($mapname) {
13496:         if (($cachedmapkey eq $courseid) &&
13497:             (abs($cachedmaptime-time)<5)) {
13498:             if (ref($cachedmaps{$mapname}) eq 'ARRAY') {
13499:                 return @{$cachedmaps{$mapname}};
13500:             }
13501:         }
13502:         my $navmap = Apache::lonnavmaps::navmap->new();
13503:         if (ref($navmap)) {
13504:             @recurseup = $navmap->recurseup_maps($mapname);
13505:             undef($navmap);
13506:             $cachedmaps{$mapname} = \@recurseup;
13507:             $cachedmaptime=time;
13508:             $cachedmapkey=$courseid;
13509:         }
13510:     }
13511:     return @recurseup;
13512: }
13513: 
13514: }
13515: 
13516: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
13517:     my ($courseid,@groups) = @_;
13518:     @groups = sort(@groups);
13519:     return @groups;
13520: }
13521: 
13522: sub packages_tab_default {
13523:     my ($uri,$varname,$toolsymb)=@_;
13524:     my (undef,$part,$name)=split(/\./,$varname);
13525: 
13526:     my (@extension,@specifics,$do_default);
13527:     foreach my $package (split(/,/,&metadata($uri,'packages',$toolsymb))) {
13528: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
13529: 	if ($pack_type eq 'default') {
13530: 	    $do_default=1;
13531: 	} elsif ($pack_type eq 'extension') {
13532: 	    push(@extension,[$package,$pack_type,$pack_part]);
13533: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
13534: 	    # only look at packages defaults for packages that this id is
13535: 	    push(@specifics,[$package,$pack_type,$pack_part]);
13536: 	}
13537:     }
13538:     # first look for a package that matches the requested part id
13539:     foreach my $package (@specifics) {
13540: 	my (undef,$pack_type,$pack_part)=@{$package};
13541: 	next if ($pack_part ne $part);
13542: 	if (defined($packagetab{"$pack_type&$name&default"})) {
13543: 	    return $packagetab{"$pack_type&$name&default"};
13544: 	}
13545:     }
13546:     # look for any possible matching non extension_ package
13547:     foreach my $package (@specifics) {
13548: 	my (undef,$pack_type,$pack_part)=@{$package};
13549: 	if (defined($packagetab{"$pack_type&$name&default"})) {
13550: 	    return $packagetab{"$pack_type&$name&default"};
13551: 	}
13552: 	if ($pack_type eq 'part') { $pack_part='0'; }
13553: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
13554: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
13555: 	}
13556:     }
13557:     # look for any posible extension_ match
13558:     foreach my $package (@extension) {
13559: 	my ($package,$pack_type)=@{$package};
13560: 	if (defined($packagetab{"$pack_type&$name&default"})) {
13561: 	    return $packagetab{"$pack_type&$name&default"};
13562: 	}
13563: 	if (defined($packagetab{$package."&$name&default"})) {
13564: 	    return $packagetab{$package."&$name&default"};
13565: 	}
13566:     }
13567:     # look for a global default setting
13568:     if ($do_default && defined($packagetab{"default&$name&default"})) {
13569: 	return $packagetab{"default&$name&default"};
13570:     }
13571:     return undef;
13572: }
13573: 
13574: sub add_prefix_and_part {
13575:     my ($prefix,$part)=@_;
13576:     my $keyroot;
13577:     if (defined($prefix) && $prefix !~ /^__/) {
13578: 	# prefix that has a part already
13579: 	$keyroot=$prefix;
13580:     } elsif (defined($prefix)) {
13581: 	# prefix that is missing a part
13582: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
13583:     } else {
13584: 	# no prefix at all
13585: 	if (defined($part)) { $keyroot='_'.$part; }
13586:     }
13587:     return $keyroot;
13588: }
13589: 
13590: # ---------------------------------------------------------------- Get metadata
13591: 
13592: my %metaentry;
13593: my %importedpartids;
13594: my %importedrespids;
13595: sub metadata {
13596:     my ($uri,$what,$toolsymb,$liburi,$prefix,$depthcount)=@_;
13597:     $uri=&declutter($uri);
13598:     # if it is a non metadata possible uri return quickly
13599:     if (($uri eq '') || 
13600: 	(($uri =~ m|^/*adm/|) && 
13601: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard|ext\.tool)$})) ||
13602:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
13603: 	return undef;
13604:     }
13605:     if (($uri =~ /^priv/ || $uri=~m{^home/httpd/html/priv}) 
13606: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
13607: 	return undef;
13608:     }
13609:     my $filename=$uri;
13610:     $uri=~s/\.meta$//;
13611: #
13612: # Is the metadata already cached?
13613: # Look at timestamp of caching
13614: # Everything is cached by the main uri, libraries are never directly cached
13615: #
13616:     if (!defined($liburi)) {
13617: 	my ($result,$cached)=&is_cached_new('meta',$uri);
13618: 	if (defined($cached)) { return $result->{':'.$what}; }
13619:     }
13620: 
13621: #
13622: # If the uri is for an external tool the file from
13623: # which metadata should be retrieved depends on whether
13624: # the tool had been configured to be gradable (set in the Course
13625: # Editor or Resource Editor).
13626: #
13627: # If a valid symb has been included as the third arg in the call
13628: # to &metadata() that can be used to retrieve the value of
13629: # parameter_0_gradable set for the resource, and included in the
13630: # uploaded map containing the tool. The value is retrieved via
13631: # &EXT(), if a valid symb is available.  Otherwise the value of
13632: # gradable in the exttool_$marker.db file for the tool instance
13633: # is retrieved via &get().
13634: #
13635: # When lonuserstate::traceroute() calls lonnet::EXT() for 
13636: # hiddenresource and encrypturl (during course initialization)
13637: # the map-level parameter for resource.0.gradable included in the 
13638: # uploaded map containing the tool will not yet have been stored
13639: # in the user_course_parms.db file for the user's session, so in 
13640: # this case fall back to retrieving gradable status from the
13641: # exttool_$marker.db file.
13642: #
13643: # In order to avoid an infinite loop, &metadata() will return
13644: # before a call to &EXT(), if the uri is for an external tool
13645: # and the $what for which metadata is being requested is
13646: # parameter_0_gradable or 0_gradable.
13647: #
13648: 
13649:     if ($uri =~ /ext\.tool$/) {
13650:         if (($what eq 'parameter_0_gradable') || ($what eq '0_gradable')) {
13651:             return;
13652:         } else {
13653:             my ($checked,$use_passback);
13654:             if ($toolsymb ne '') {
13655:                 (undef,undef,my $tooluri) = &decode_symb($toolsymb);
13656:                 if (($tooluri eq $uri) && (&EXT('resource.0.gradable',$toolsymb))) {
13657:                     $checked = 1;
13658:                     if (&EXT('resource.0.gradable',$toolsymb) =~ /^yes$/i) {
13659:                         $use_passback = 1;
13660:                     }
13661:                 }
13662:             }
13663:             unless ($checked) {
13664:                 my ($ignore,$cdom,$cnum,$marker) = split(m{/},$uri);
13665:                 $marker=~s/\D//g;
13666:                 if ($marker) {
13667:                     my %toolsettings=&get('exttool_'.$marker,['gradable'],$cdom,$cnum);
13668:                     $use_passback = $toolsettings{'gradable'};
13669:                 }
13670:             }
13671:             if ($use_passback) {
13672:                 $filename = '/home/httpd/html/res/lib/templates/LTIpassback.tool';
13673:             } else {
13674:                 $filename = '/home/httpd/html/res/lib/templates/LTIstandard.tool';
13675:             }
13676:         }
13677:     }
13678: 
13679:     {
13680: # Imported parts would go here
13681:         my @origfiletagids=();
13682:         my $importedparts=0;
13683: 
13684: # Imported responseids would go here
13685:         my $importedresponses=0;
13686: #
13687: # Is this a recursive call for a library?
13688: #
13689: #	if (! exists($metacache{$uri})) {
13690: #	    $metacache{$uri}={};
13691: #	}
13692: 	my $cachetime = 60*60;
13693:         if ($liburi) {
13694: 	    $liburi=&declutter($liburi);
13695:             $filename=$liburi;
13696:         } else {
13697: 	    &devalidate_cache_new('meta',$uri);
13698: 	    undef(%metaentry);
13699: 	}
13700:         my %metathesekeys=();
13701:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
13702: 	my $metastring;
13703: 	if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
13704: 	    my $which = &hreflocation('','/'.($liburi || $uri));
13705: 	    $metastring = 
13706: 		&Apache::lonnet::ssi_body($which,
13707: 					  ('grade_target' => 'meta'));
13708: 	    $cachetime = 1; # only want this cached in the child not long term
13709: 	} elsif (($uri !~ m -^(editupload)/-) && 
13710:                  ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
13711: 	    my $file=&filelocation('',&clutter($filename));
13712: 	    #push(@{$metaentry{$uri.'.file'}},$file);
13713: 	    $metastring=&getfile($file);
13714: 	}
13715:         my $parser=HTML::LCParser->new(\$metastring);
13716:         my $token;
13717:         undef %metathesekeys;
13718:         while ($token=$parser->get_token) {
13719: 	    if ($token->[0] eq 'S') {
13720: 		if (defined($token->[2]->{'package'})) {
13721: #
13722: # This is a package - get package info
13723: #
13724: 		    my $package=$token->[2]->{'package'};
13725: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
13726: 		    if (defined($token->[2]->{'id'})) { 
13727: 			$keyroot.='_'.$token->[2]->{'id'}; 
13728: 		    }
13729: 		    if ($metaentry{':packages'}) {
13730: 			$metaentry{':packages'}.=','.$package.$keyroot;
13731: 		    } else {
13732: 			$metaentry{':packages'}=$package.$keyroot;
13733: 		    }
13734: 		    foreach my $pack_entry (keys(%packagetab)) {
13735: 			my $part=$keyroot;
13736: 			$part=~s/^\_//;
13737: 			if ($pack_entry=~/^\Q$package\E\&/ || 
13738: 			    $pack_entry=~/^\Q$package\E_0\&/) {
13739: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
13740: 			    # ignore package.tab specified default values
13741:                             # here &package_tab_default() will fetch those
13742: 			    if ($subp eq 'default') { next; }
13743: 			    my $value=$packagetab{$pack_entry};
13744: 			    my $unikey;
13745: 			    if ($pack =~ /_0$/) {
13746: 				$unikey='parameter_0_'.$name;
13747: 				$part=0;
13748: 			    } else {
13749: 				$unikey='parameter'.$keyroot.'_'.$name;
13750: 			    }
13751: 			    if ($subp eq 'display') {
13752: 				$value.=' [Part: '.$part.']';
13753: 			    }
13754: 			    $metaentry{':'.$unikey.'.part'}=$part;
13755: 			    $metathesekeys{$unikey}=1;
13756: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
13757: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
13758: 			    }
13759: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
13760: 				$metaentry{':'.$unikey}=
13761: 				    $metaentry{':'.$unikey.'.default'};
13762: 			    }
13763: 			}
13764: 		    }
13765: 		} else {
13766: #
13767: # This is not a package - some other kind of start tag
13768: #
13769: 		    my $entry=$token->[1];
13770: 		    my $unikey='';
13771: 
13772: 		    if ($entry eq 'import') {
13773: #
13774: # Importing a library here
13775: #
13776:                         my $location=$parser->get_text('/import');
13777:                         my $dir=$filename;
13778:                         $dir=~s|[^/]*$||;
13779:                         $location=&filelocation($dir,$location);
13780: 
13781:                         my $importid=$token->[2]->{'id'};
13782:                         my $importmode=$token->[2]->{'importmode'};
13783: #
13784: # Check metadata for imported file to
13785: # see if it contained response items
13786: #
13787:                         my ($origfile,@libfilekeys);
13788:                         my %currmetaentry = %metaentry;
13789:                         @libfilekeys = split(/,/,&metadata($location,'keys',undef,undef,undef,
13790:                                                            $depthcount+1));
13791:                         if (grep(/^responseorder$/,@libfilekeys)) {
13792:                             my $libresponseorder = &metadata($location,'responseorder',undef,undef,
13793:                                                              undef,$depthcount+1);
13794:                             if ($libresponseorder ne '') {
13795:                                 if ($#origfiletagids<0) {
13796:                                     undef(%importedrespids);
13797:                                     undef(%importedpartids);
13798:                                 }
13799:                                 my @respids = split(/\s*,\s*/,$libresponseorder);
13800:                                 if (@respids) {
13801:                                     $importedrespids{$importid} = join(',',map { $importid.'_'.$_ } @respids);
13802:                                 }
13803:                                 if ($importedrespids{$importid} ne '') {
13804:                                     $importedresponses = 1;
13805: # We need to get the original file and the imported file to get the response order correct
13806: # Load and inspect original file
13807:                                     if ($#origfiletagids<0) {
13808:                                         my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
13809:                                         $origfile=&getfile($origfilelocation);
13810:                                         @origfiletagids=($origfile=~/<((?:\w+)response|import|part)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
13811:                                     }
13812:                                 }
13813:                             }
13814:                         }
13815: # Do not overwrite contents of %metaentry hash for resource itself with 
13816: # hash populated for imported library file
13817:                         %metaentry = %currmetaentry;
13818:                         undef(%currmetaentry);
13819:                         if ($importmode eq 'part') {
13820: # Import as part(s)
13821:                            $importedparts=1;
13822: # We need to get the original file and the imported file to get the part order correct
13823: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
13824: # Load and inspect original file if we didn't do that already
13825:                            if ($#origfiletagids<0) {
13826:                                undef(%importedrespids);
13827:                                undef(%importedpartids);
13828:                                if ($origfile eq '') {
13829:                                    my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
13830:                                    $origfile=&getfile($origfilelocation);
13831:                                    @origfiletagids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
13832:                                }
13833:                            }
13834:                            my @impfilepartids;
13835: # If <partorder> tag is included in metadata for the imported file
13836: # get the parts in the imported file from that.
13837:                            if (grep(/^partorder$/,@libfilekeys)) {
13838:                                %currmetaentry = %metaentry;
13839:                                my $libpartorder = &metadata($location,'partorder',undef,undef,undef,
13840:                                                             $depthcount+1);
13841:                                %metaentry = %currmetaentry;
13842:                                undef(%currmetaentry);
13843:                                if ($libpartorder ne '') {
13844:                                    @impfilepartids=split(/\s*,\s*/,$libpartorder);
13845:                                }
13846:                            } else {
13847: # If no <partorder> tag available, load and inspect imported file
13848:                                my $impfile=&getfile($location);
13849:                                @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
13850:                            }
13851:                            if ($#impfilepartids>=0) {
13852: # This problem had parts
13853:                                $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
13854:                            } else {
13855: # Importing by turning a single problem into a problem part
13856: # It gets the import-tags ID as part-ID
13857:                                $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
13858:                                $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
13859:                            }
13860:                         } else {
13861: # Import as problem or as normal import
13862:                             $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
13863:                             unless ($importmode eq 'problem') {
13864: # Normal import
13865:                                 if (defined($token->[2]->{'id'})) {
13866:                                     $unikey.='_'.$token->[2]->{'id'};
13867:                                 }
13868:                             }
13869: # Check metadata for imported file to
13870: # see if it contained parts
13871:                             if (grep(/^partorder$/,@libfilekeys)) {
13872:                                 %currmetaentry = %metaentry;
13873:                                 my $libpartorder = &metadata($location,'partorder',undef,undef,undef,
13874:                                                              $depthcount+1);
13875:                                 %metaentry = %currmetaentry;
13876:                                 undef(%currmetaentry);
13877:                                 if ($libpartorder ne '') {
13878:                                     $importedparts = 1;
13879:                                     $importedpartids{$token->[2]->{'id'}}=$libpartorder;
13880:                                 }
13881:                             }
13882:                         }
13883: 			if ($depthcount<20) {
13884: 			    my $metadata = 
13885: 				&metadata($uri,'keys',$toolsymb,$location,$unikey,
13886: 					  $depthcount+1);
13887: 			    foreach my $meta (split(',',$metadata)) {
13888: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
13889: 				$metathesekeys{$meta}=1;
13890: 			    }
13891:                         }
13892: 		    } else {
13893: #
13894: # Not importing, some other kind of non-package, non-library start tag
13895: # 
13896:                         $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
13897:                         if (defined($token->[2]->{'id'})) {
13898:                             $unikey.='_'.$token->[2]->{'id'};
13899:                         }
13900: 			if (defined($token->[2]->{'name'})) { 
13901: 			    $unikey.='_'.$token->[2]->{'name'}; 
13902: 			}
13903: 			$metathesekeys{$unikey}=1;
13904: 			foreach my $param (@{$token->[3]}) {
13905: 			    $metaentry{':'.$unikey.'.'.$param} =
13906: 				$token->[2]->{$param};
13907: 			}
13908: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
13909: 			my $default=$metaentry{':'.$unikey.'.default'};
13910: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
13911: 		 # only ws inside the tag, and not in default, so use default
13912: 		 # as value
13913: 			    $metaentry{':'.$unikey}=$default;
13914: 			} elsif ( $internaltext =~ /\S/ ) {
13915: 		  # something interesting inside the tag
13916: 			    $metaentry{':'.$unikey}=$internaltext;
13917: 			} else {
13918: 		  # no interesting values, don't set a default
13919: 			}
13920: # end of not-a-package not-a-library import
13921: 		    }
13922: # end of not-a-package start tag
13923: 		}
13924: # the next is the end of "start tag"
13925: 	    }
13926: 	}
13927: 	my ($extension) = ($uri =~ /\.(\w+)$/);
13928: 	$extension = lc($extension);
13929: 	if ($extension eq 'htm') { $extension='html'; }
13930: 
13931: 	foreach my $key (keys(%packagetab)) {
13932: 	    #no specific packages #how's our extension
13933: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
13934: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
13935: 					 \%metathesekeys);
13936: 	}
13937: 
13938: 	if (!exists($metaentry{':packages'})
13939: 	    || $packagetab{"import_defaults&extension_$extension"}) {
13940: 	    foreach my $key (keys(%packagetab)) {
13941: 		#no specific packages well let's get default then
13942: 		if ($key!~/^default&/) { next; }
13943: 		&metadata_create_package_def($uri,$key,'default',
13944: 					     \%metathesekeys);
13945: 	    }
13946: 	}
13947: # are there custom rights to evaluate
13948: 	if ($metaentry{':copyright'} eq 'custom') {
13949: 
13950:     #
13951:     # Importing a rights file here
13952:     #
13953: 	    unless ($depthcount) {
13954: 		my $location=$metaentry{':customdistributionfile'};
13955: 		my $dir=$filename;
13956: 		$dir=~s|[^/]*$||;
13957: 		$location=&filelocation($dir,$location);
13958: 		my $rights_metadata =
13959: 		    &metadata($uri,'keys',$toolsymb,$location,'_rights',
13960: 			      $depthcount+1);
13961: 		foreach my $rights (split(',',$rights_metadata)) {
13962: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
13963: 		    $metathesekeys{$rights}=1;
13964: 		}
13965: 	    }
13966: 	}
13967: 	# uniqifiy package listing
13968: 	my %seen;
13969: 	my @uniq_packages =
13970: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
13971: 	$metaentry{':packages'} = join(',',@uniq_packages);
13972: 
13973:         if (($importedresponses) || ($importedparts)) {
13974:             if ($importedparts) {
13975: # We had imported parts and need to rebuild partorder
13976:                 $metaentry{':partorder'}='';
13977:                 $metathesekeys{'partorder'}=1;
13978:             }
13979:             if ($importedresponses) {
13980: # We had imported responses and need to rebuil responseorder
13981:                 $metaentry{':responseorder'}='';
13982:                 $metathesekeys{'responseorder'}=1;
13983:             }
13984:             for (my $index=0;$index<$#origfiletagids;$index+=2) {
13985:                 my $origid = $origfiletagids[$index+1];
13986:                 if ($origfiletagids[$index] eq 'part') {
13987: # Original part, part of the problem
13988:                     if ($importedparts) {
13989:                         $metaentry{':partorder'}.=','.$origid;
13990:                     }
13991:                 } elsif ($origfiletagids[$index] eq 'import') {
13992:                     if ($importedparts) {
13993: # We have imported parts at this position
13994:                         if ($importedpartids{$origid} ne '') {
13995:                             $metaentry{':partorder'}.=','.$importedpartids{$origid};
13996:                         }
13997:                     }
13998:                     if ($importedresponses) {
13999: # We have imported responses at this position
14000:                         if ($importedrespids{$origid} ne '') {
14001:                             $metaentry{':responseorder'}.=','.$importedrespids{$origid};
14002:                         }
14003:                     }
14004:                 } else {
14005: # Original response item, part of the problem
14006:                     if ($importedresponses) {
14007:                         $metaentry{':responseorder'}.=','.$origid;
14008:                     }
14009:                 }
14010:             }
14011:             if ($importedparts) {
14012:                 $metaentry{':partorder'}=~s/^\,//;
14013:             }
14014:             if ($importedresponses) {
14015:                 $metaentry{':responseorder'}=~s/^\,//;
14016:             }
14017:         }
14018: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
14019: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
14020: 	$metaentry{':allpossiblekeys'}=join(',',keys(%metathesekeys));
14021:         unless ($liburi) {
14022: 	    &do_cache_new('meta',$uri,\%metaentry,$cachetime);
14023:         }
14024: # this is the end of "was not already recently cached
14025:     }
14026:     return $metaentry{':'.$what};
14027: }
14028: 
14029: sub metadata_create_package_def {
14030:     my ($uri,$key,$package,$metathesekeys)=@_;
14031:     my ($pack,$name,$subp)=split(/\&/,$key);
14032:     if ($subp eq 'default') { next; }
14033:     
14034:     if (defined($metaentry{':packages'})) {
14035: 	$metaentry{':packages'}.=','.$package;
14036:     } else {
14037: 	$metaentry{':packages'}=$package;
14038:     }
14039:     my $value=$packagetab{$key};
14040:     my $unikey;
14041:     $unikey='parameter_0_'.$name;
14042:     $metaentry{':'.$unikey.'.part'}=0;
14043:     $$metathesekeys{$unikey}=1;
14044:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
14045: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
14046:     }
14047:     if (defined($metaentry{':'.$unikey.'.default'})) {
14048: 	$metaentry{':'.$unikey}=
14049: 	    $metaentry{':'.$unikey.'.default'};
14050:     }
14051: }
14052: 
14053: sub metadata_generate_part0 {
14054:     my ($metadata,$metacache,$uri) = @_;
14055:     my %allnames;
14056:     foreach my $metakey (keys(%$metadata)) {
14057: 	if ($metakey=~/^parameter\_(.*)/) {
14058: 	  my $part=$$metacache{':'.$metakey.'.part'};
14059: 	  my $name=$$metacache{':'.$metakey.'.name'};
14060: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
14061: 	    $allnames{$name}=$part;
14062: 	  }
14063: 	}
14064:     }
14065:     foreach my $name (keys(%allnames)) {
14066:       $$metadata{"parameter_0_$name"}=1;
14067:       my $key=":parameter_0_$name";
14068:       $$metacache{"$key.part"}='0';
14069:       $$metacache{"$key.name"}=$name;
14070:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
14071: 					   $allnames{$name}.'_'.$name.
14072: 					   '.type'};
14073:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
14074: 			     '.display'};
14075:       my $expr='[Part: '.$allnames{$name}.']';
14076:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
14077:       $$metacache{"$key.display"}=$olddis;
14078:     }
14079: }
14080: 
14081: # ------------------------------------------------------ Devalidate title cache
14082: 
14083: sub devalidate_title_cache {
14084:     my ($url)=@_;
14085:     if (!$env{'request.course.id'}) { return; }
14086:     my $symb=&symbread($url);
14087:     if (!$symb) { return; }
14088:     my $key=$env{'request.course.id'}."\0".$symb;
14089:     &devalidate_cache_new('title',$key);
14090: }
14091: 
14092: # ------------------------------------------------- Get the title of a course
14093: 
14094: sub current_course_title {
14095:     return $env{ 'course.' . $env{'request.course.id'} . '.description' };
14096: }
14097: # ------------------------------------------------- Get the title of a resource
14098: 
14099: sub gettitle {
14100:     my $urlsymb=shift;
14101:     my $symb=&symbread($urlsymb);
14102:     if ($symb) {
14103: 	my $key=$env{'request.course.id'}."\0".$symb;
14104: 	my ($result,$cached)=&is_cached_new('title',$key);
14105: 	if (defined($cached)) { 
14106: 	    return $result;
14107: 	}
14108: 	my ($map,$resid,$url)=&decode_symb($symb);
14109: 	my $title='';
14110: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
14111: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
14112: 	} else {
14113: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
14114: 		    &GDBM_READER(),0640)) {
14115: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
14116: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
14117: 		untie(%bighash);
14118: 	    }
14119: 	}
14120: 	$title=~s/\&colon\;/\:/gs;
14121: 	if ($title) {
14122: # Remember both $symb and $title for dynamic metadata
14123:             $accesshash{$symb.'___crstitle'}=$title;
14124:             $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
14125: # Cache this title and then return it
14126: 	    return &do_cache_new('title',$key,$title,600);
14127: 	}
14128: 	$urlsymb=$url;
14129:     }
14130:     my $title=&metadata($urlsymb,'title');
14131:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
14132:     return $title;
14133: }
14134: 
14135: sub get_slot {
14136:     my ($which,$cnum,$cdom)=@_;
14137:     if (!$cnum || !$cdom) {
14138: 	(undef,my $courseid)=&whichuser();
14139: 	$cdom=$env{'course.'.$courseid.'.domain'};
14140: 	$cnum=$env{'course.'.$courseid.'.num'};
14141:     }
14142:     my $key=join("\0",'slots',$cdom,$cnum,$which);
14143:     my %slotinfo;
14144:     if (exists($remembered{$key})) {
14145: 	$slotinfo{$which} = $remembered{$key};
14146:     } else {
14147: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
14148: 	&Apache::lonhomework::showhash(%slotinfo);
14149: 	my ($tmp)=keys(%slotinfo);
14150: 	if ($tmp=~/^error:/) { return (); }
14151: 	$remembered{$key} = $slotinfo{$which};
14152:     }
14153:     if (ref($slotinfo{$which}) eq 'HASH') {
14154: 	return %{$slotinfo{$which}};
14155:     }
14156:     return $slotinfo{$which};
14157: }
14158: 
14159: sub get_reservable_slots {
14160:     my ($cnum,$cdom,$uname,$udom) = @_;
14161:     my $now = time;
14162:     my $reservable_info;
14163:     my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
14164:     if (exists($remembered{$key})) {
14165:         $reservable_info = $remembered{$key};
14166:     } else {
14167:         my %resv;
14168:         ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
14169:         &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
14170:         $reservable_info = \%resv;
14171:         $remembered{$key} = $reservable_info;
14172:     }
14173:     return $reservable_info;
14174: }
14175: 
14176: sub get_course_slots {
14177:     my ($cnum,$cdom) = @_;
14178:     my $hashid=$cnum.':'.$cdom;
14179:     my ($result,$cached) = &is_cached_new('allslots',$hashid);
14180:     if (defined($cached)) {
14181:         if (ref($result) eq 'HASH') {
14182:             return %{$result};
14183:         }
14184:     } else {
14185:         my %slots=&dump('slots',$cdom,$cnum);
14186:         my ($tmp) = keys(%slots);
14187:         if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
14188:             &do_cache_new('allslots',$hashid,\%slots,600);
14189:             return %slots;
14190:         }
14191:     }
14192:     return;
14193: }
14194: 
14195: sub devalidate_slots_cache {
14196:     my ($cnum,$cdom)=@_;
14197:     my $hashid=$cnum.':'.$cdom;
14198:     &devalidate_cache_new('allslots',$hashid);
14199: }
14200: 
14201: sub get_coursechange {
14202:     my ($cdom,$cnum) = @_;
14203:     if ($cdom eq '' || $cnum eq '') {
14204:         return unless ($env{'request.course.id'});
14205:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
14206:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
14207:     }
14208:     my $hashid=$cdom.'_'.$cnum;
14209:     my ($change,$cached)=&is_cached_new('crschange',$hashid);
14210:     if ((defined($cached)) && ($change ne '')) {
14211:         return $change;
14212:     } else {
14213:         my %crshash;
14214:         %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
14215:         if ($crshash{'internal.contentchange'} eq '') {
14216:             $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
14217:             if ($change eq '') {
14218:                 %crshash = &get('environment',['internal.created'],$cdom,$cnum);
14219:                 $change = $crshash{'internal.created'};
14220:             }
14221:         } else {
14222:             $change = $crshash{'internal.contentchange'};
14223:         }
14224:         my $cachetime = 600;
14225:         &do_cache_new('crschange',$hashid,$change,$cachetime);
14226:     }
14227:     return $change;
14228: }
14229: 
14230: sub devalidate_coursechange_cache {
14231:     my ($cdom,$cnum)=@_;
14232:     my $hashid=$cdom.'_'.$cnum;
14233:     &devalidate_cache_new('crschange',$hashid);
14234: }
14235: 
14236: sub get_suppchange {
14237:     my ($cdom,$cnum) = @_;
14238:     if ($cdom eq '' || $cnum eq '') {
14239:         return unless ($env{'request.course.id'});
14240:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
14241:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
14242:     }
14243:     my $hashid=$cdom.'_'.$cnum;
14244:     my ($change,$cached)=&is_cached_new('suppchange',$hashid);
14245:     if ((defined($cached)) && ($change ne '')) {
14246:         return $change;
14247:     } else {
14248:         my %crshash = &get('environment',['internal.supplementalchange'],$cdom,$cnum);
14249:         if ($crshash{'internal.supplementalchange'} eq '') {
14250:             $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
14251:             if ($change eq '') {
14252:                 %crshash = &get('environment',['internal.created'],$cdom,$cnum);
14253:                 $change = $crshash{'internal.created'};
14254:             }
14255:         } else {
14256:             $change = $crshash{'internal.supplementalchange'};
14257:         }
14258:         my $cachetime = 600;
14259:         &do_cache_new('suppchange',$hashid,$change,$cachetime);
14260:     }
14261:     return $change;
14262: }
14263: 
14264: sub devalidate_suppchange_cache {
14265:     my ($cdom,$cnum)=@_;
14266:     my $hashid=$cdom.'_'.$cnum;
14267:     &devalidate_cache_new('suppchange',$hashid);
14268: }
14269: 
14270: sub update_supp_caches {
14271:     my ($cdom,$cnum) = @_;
14272:     my %servers = &internet_dom_servers($cdom);
14273:     my @ids=&current_machine_ids();
14274:     foreach my $server (keys(%servers)) {
14275:         next if (grep(/^\Q$server\E$/,@ids));
14276:         my $hashid=$cnum.':'.$cdom;
14277:         my $cachekey = &escape('showsupp').':'.&escape($hashid);
14278:         &remote_devalidate_cache($server,[$cachekey]);
14279:     }
14280:     &has_unhidden_suppfiles($cnum,$cdom,1,1);
14281:     &count_supptools($cnum,$cdom,1);
14282:     my $now = time;
14283:     if ($env{'request.course.id'} eq $cdom.'_'.$cnum) {
14284:         &Apache::lonnet::appenv({'request.course.suppupdated' => $now});
14285:     }
14286:     &put('environment',{'internal.supplementalchange' => $now},
14287:          $cdom,$cnum);
14288:     &Apache::lonnet::appenv(
14289:         {'course.'.$cdom.'_'.$cnum.'.internal.supplementalchange' => $now});
14290:     &do_cache_new('suppchange',$cdom.'_'.$cnum,$now,600);
14291: }
14292: 
14293: # ------------------------------------------------- Update symbolic store links
14294: 
14295: sub symblist {
14296:     my ($mapname,%newhash)=@_;
14297:     $mapname=&deversion(&declutter($mapname));
14298:     my %hash;
14299:     if (($env{'request.course.fn'}) && (%newhash)) {
14300:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
14301:                       &GDBM_WRCREAT(),0640)) {
14302: 	    foreach my $url (keys(%newhash)) {
14303: 		next if ($url eq 'last_known'
14304: 			 && $env{'form.no_update_last_known'});
14305: 		$hash{declutter($url)}=&encode_symb($mapname,
14306: 						    $newhash{$url}->[1],
14307: 						    $newhash{$url}->[0]);
14308:             }
14309:             if (untie(%hash)) {
14310: 		return 'ok';
14311:             }
14312:         }
14313:     }
14314:     return 'error';
14315: }
14316: 
14317: # --------------------------------------------------------------- Verify a symb
14318: 
14319: sub symbverify {
14320:     my ($symb,$thisurl,$encstate)=@_;
14321:     my $thisfn=$thisurl;
14322:     $thisfn=&declutter($thisfn);
14323: # direct jump to resource in page or to a sequence - will construct own symbs
14324:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
14325: # check URL part
14326:     my ($map,$resid,$url)=&decode_symb($symb);
14327: 
14328:     unless ($url eq $thisfn) { return 0; }
14329: 
14330:     $symb=&symbclean($symb);
14331:     $thisurl=&deversion($thisurl);
14332:     $thisfn=&deversion($thisfn);
14333: 
14334:     my %bighash;
14335:     my $okay=0;
14336: 
14337:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
14338:                             &GDBM_READER(),0640)) {
14339:         if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
14340:             $thisurl =~ s/\?.+$//;
14341:             if ($map =~ m{^uploaded/.+\.page$}) {
14342:                 $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
14343:                 $thisurl =~ s{^\Qhttp://https://\E}{https://};
14344:             }
14345:         }
14346:         my $ids;
14347:         if ($map =~ m{^uploaded/.+\.page$}) {
14348:             $ids=$bighash{'ids_'.&clutter_with_no_wrapper($thisurl)};
14349:         } else {
14350:             $ids=$bighash{'ids_'.&clutter($thisurl)};
14351:         }
14352:         unless ($ids) {
14353:             my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;  
14354:             $ids=$bighash{$idkey};
14355:         }
14356:         if ($ids) {
14357: # ------------------------------------------------------------------- Has ID(s)
14358:             if ($thisfn =~ m{^/adm/wrapper/ext/}) {
14359:                 $symb =~ s/\?.+$//;
14360:             }
14361: 	    foreach my $id (split(/\,/,$ids)) {
14362: 	       my ($mapid,$resid)=split(/\./,$id);
14363:                if (
14364:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
14365:    eq $symb) {
14366:                    if (ref($encstate)) {
14367:                        $$encstate = $bighash{'encrypted_'.$id};
14368:                    }
14369: 		   if (($env{'request.role.adv'}) ||
14370: 		       ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
14371:                        ($thisurl eq '/adm/navmaps')) {
14372: 		       $okay=1;
14373:                        last;
14374: 		   }
14375: 	       }
14376: 	   }
14377:         }
14378: 	untie(%bighash);
14379:     }
14380:     return $okay;
14381: }
14382: 
14383: # --------------------------------------------------------------- Clean-up symb
14384: 
14385: sub symbclean {
14386:     my $symb=shift;
14387:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
14388: # remove version from map
14389:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
14390: 
14391: # remove version from URL
14392:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
14393: 
14394: # remove wrapper
14395: 
14396:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
14397:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
14398:     return $symb;
14399: }
14400: 
14401: # ---------------------------------------------- Split symb to find map and url
14402: 
14403: sub encode_symb {
14404:     my ($map,$resid,$url)=@_;
14405:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
14406: }
14407: 
14408: sub decode_symb {
14409:     my $symb=shift;
14410:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
14411:     my ($map,$resid,$url)=split(/___/,$symb);
14412:     return (&fixversion($map),$resid,&fixversion($url));
14413: }
14414: 
14415: sub fixversion {
14416:     my $fn=shift;
14417:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
14418:     my %bighash;
14419:     my $uri=&clutter($fn);
14420:     my $key=$env{'request.course.id'}.'_'.$uri;
14421: # is this cached?
14422:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
14423:     if (defined($cached)) { return $result; }
14424: # unfortunately not cached, or expired
14425:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
14426: 	    &GDBM_READER(),0640)) {
14427:  	if ($bighash{'version_'.$uri}) {
14428:  	    my $version=$bighash{'version_'.$uri};
14429:  	    unless (($version eq 'mostrecent') || 
14430: 		    ($version==&getversion($uri))) {
14431:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
14432:  	    }
14433:  	}
14434:  	untie %bighash;
14435:     }
14436:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
14437: }
14438: 
14439: sub deversion {
14440:     my $url=shift;
14441:     $url=~s/\.\d+\.(\w+)$/\.$1/;
14442:     return $url;
14443: }
14444: 
14445: # ------------------------------------------------------ Return symb list entry
14446: 
14447: sub symbread {
14448:     my ($thisfn,$donotrecurse,$ignorecachednull,$checkforblock,$possibles,
14449:         $ignoresymbdb,$noenccheck)=@_;
14450:     my $cache_str='request.symbread.cached.'.$thisfn;
14451:     if (defined($env{$cache_str})) {
14452:         unless (ref($possibles) eq 'HASH') {
14453:             if ($ignorecachednull) {
14454:                 return $env{$cache_str} unless ($env{$cache_str} eq '');
14455:             } else {
14456:                 return $env{$cache_str};
14457:             }
14458:         }
14459:     }
14460: # no filename provided? try from environment
14461:     unless ($thisfn) {
14462:         if ($env{'request.symb'}) {
14463:             return $env{$cache_str}=&symbclean($env{'request.symb'});
14464: 	}
14465: 	$thisfn=$env{'request.filename'};
14466:     }
14467:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
14468: # is that filename actually a symb? Verify, clean, and return
14469:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
14470: 	if (&symbverify($thisfn,$1)) {
14471: 	    return $env{$cache_str}=&symbclean($thisfn);
14472: 	}
14473:     }
14474:     $thisfn=declutter($thisfn);
14475:     my %hash;
14476:     my %bighash;
14477:     my $syval='';
14478:     if (($env{'request.course.fn'}) && ($thisfn)) {
14479:         unless ($ignoresymbdb) {
14480:             if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
14481:                           &GDBM_READER(),0640)) {
14482: 	        $syval=$hash{$thisfn};
14483:                 untie(%hash);
14484:             }
14485:             if ($syval && $checkforblock) {
14486:                 my @blockers = &has_comm_blocking('bre',$syval,$thisfn,$ignoresymbdb,$noenccheck);
14487:                 if (@blockers) {
14488:                     $syval='';
14489:                 }
14490:             }
14491:         }
14492: # ---------------------------------------------------------- There was an entry
14493:         if ($syval) {
14494: 	    #unless ($syval=~/\_\d+$/) {
14495: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
14496: 		    #&appenv({'request.ambiguous' => $thisfn});
14497: 		    #return $env{$cache_str}='';
14498: 		#}    
14499: 		#$syval.=$1;
14500: 	    #}
14501:         } else {
14502: # ------------------------------------------------------- Was not in symb table
14503:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
14504:                             &GDBM_READER(),0640)) {
14505: # ---------------------------------------------- Get ID(s) for current resource
14506:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
14507:               unless ($ids) { 
14508:                  $ids=$bighash{'ids_/'.$thisfn};
14509:               }
14510:               unless ($ids) {
14511: # alias?
14512: 		  $ids=$bighash{'mapalias_'.$thisfn};
14513:               }
14514:               if ($ids) {
14515: # ------------------------------------------------------------------- Has ID(s)
14516:                  my @possibilities=split(/\,/,$ids);
14517:                  if ($#possibilities==0) {
14518: # ----------------------------------------------- There is only one possibility
14519: 		     my ($mapid,$resid)=split(/\./,$ids);
14520: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
14521: 						    $resid,$thisfn);
14522:                      if (ref($possibles) eq 'HASH') {
14523:                          unless ($bighash{'randomout_'.$ids} || $env{'request.role.adv'}) {
14524:                              $possibles->{$syval} = 1;
14525:                          }
14526:                      }
14527:                      if ($checkforblock) {
14528:                          unless ($bighash{'randomout_'.$ids} || $env{'request.role.adv'}) {
14529:                              my @blockers = &has_comm_blocking('bre',$syval,$bighash{'src_'.$ids},'',$noenccheck);
14530:                              if (@blockers) {
14531:                                  $syval = '';
14532:                                  untie(%bighash);
14533:                                  return $env{$cache_str}='';
14534:                              }
14535:                          }
14536:                      }
14537:                  } elsif ((!$donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) { 
14538: # ------------------------------------------ There is more than one possibility
14539:                      my $realpossible=0;
14540:                      foreach my $id (@possibilities) {
14541: 			 my $file=$bighash{'src_'.$id};
14542:                          my $canaccess;
14543:                          if (($donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
14544:                              $canaccess = 1;
14545:                          } else { 
14546:                              $canaccess = &allowed('bre',$file);
14547:                          }
14548:                          if ($canaccess) {
14549:          		     my ($mapid,$resid)=split(/\./,$id);
14550:                              if ($bighash{'map_type_'.$mapid} ne 'page') {
14551:                                  my $poss_syval=&encode_symb($bighash{'map_id_'.$mapid},
14552: 						             $resid,$thisfn);
14553:                                  next if ($bighash{'randomout_'.$id} && !$env{'request.role.adv'});
14554:                                  next unless (($noenccheck) || ($bighash{'encrypted_'.$id} eq $env{'request.enc'}));
14555:                                  if ($checkforblock) {
14556:                                      my @blockers = &has_comm_blocking('bre',$poss_syval,$file,'',$noenccheck);
14557:                                      if (@blockers > 0) {
14558:                                          $syval = '';
14559:                                      } else {
14560:                                          $syval = $poss_syval;
14561:                                          $realpossible++;
14562:                                      }
14563:                                  } else {
14564:                                      $syval = $poss_syval;
14565:                                      $realpossible++;
14566:                                  }
14567:                                  if ($syval) {
14568:                                      if (ref($possibles) eq 'HASH') {
14569:                                          $possibles->{$syval} = 1;
14570:                                      }
14571:                                  }
14572:                              }
14573: 			 }
14574:                      }
14575: 		     if ($realpossible!=1) { $syval=''; }
14576:                  } else {
14577:                      $syval='';
14578:                  }
14579: 	      }
14580:               untie(%bighash);
14581:            }
14582:         }
14583:         if ($syval) {
14584: 	    return $env{$cache_str}=$syval;
14585:         }
14586:     }
14587:     &appenv({'request.ambiguous' => $thisfn});
14588:     return $env{$cache_str}='';
14589: }
14590: 
14591: # ---------------------------------------------------------- Return random seed
14592: 
14593: sub numval {
14594:     my $txt=shift;
14595:     $txt=~tr/A-J/0-9/;
14596:     $txt=~tr/a-j/0-9/;
14597:     $txt=~tr/K-T/0-9/;
14598:     $txt=~tr/k-t/0-9/;
14599:     $txt=~tr/U-Z/0-5/;
14600:     $txt=~tr/u-z/0-5/;
14601:     $txt=~s/\D//g;
14602:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
14603:     return int($txt);
14604: }
14605: 
14606: sub numval2 {
14607:     my $txt=shift;
14608:     $txt=~tr/A-J/0-9/;
14609:     $txt=~tr/a-j/0-9/;
14610:     $txt=~tr/K-T/0-9/;
14611:     $txt=~tr/k-t/0-9/;
14612:     $txt=~tr/U-Z/0-5/;
14613:     $txt=~tr/u-z/0-5/;
14614:     $txt=~s/\D//g;
14615:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
14616:     my $total;
14617:     foreach my $val (@txts) { $total+=$val; }
14618:     if ($_64bit) { if ($total > 2**32) { return -1; } }
14619:     return int($total);
14620: }
14621: 
14622: sub numval3 {
14623:     use integer;
14624:     my $txt=shift;
14625:     $txt=~tr/A-J/0-9/;
14626:     $txt=~tr/a-j/0-9/;
14627:     $txt=~tr/K-T/0-9/;
14628:     $txt=~tr/k-t/0-9/;
14629:     $txt=~tr/U-Z/0-5/;
14630:     $txt=~tr/u-z/0-5/;
14631:     $txt=~s/\D//g;
14632:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
14633:     my $total;
14634:     foreach my $val (@txts) { $total+=$val; }
14635:     if ($_64bit) { $total=(($total<<32)>>32); }
14636:     return $total;
14637: }
14638: 
14639: sub digest {
14640:     my ($data)=@_;
14641:     my $digest=&Digest::MD5::md5($data);
14642:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
14643:     my ($e,$f);
14644:     {
14645:         use integer;
14646:         $e=($a+$b);
14647:         $f=($c+$d);
14648:         if ($_64bit) {
14649:             $e=(($e<<32)>>32);
14650:             $f=(($f<<32)>>32);
14651:         }
14652:     }
14653:     if (wantarray) {
14654: 	return ($e,$f);
14655:     } else {
14656: 	my $g;
14657: 	{
14658: 	    use integer;
14659: 	    $g=($e+$f);
14660: 	    if ($_64bit) {
14661: 		$g=(($g<<32)>>32);
14662: 	    }
14663: 	}
14664: 	return $g;
14665:     }
14666: }
14667: 
14668: sub latest_rnd_algorithm_id {
14669:     return '64bit5';
14670: }
14671: 
14672: sub get_rand_alg {
14673:     my ($courseid)=@_;
14674:     if (!$courseid) { $courseid=(&whichuser())[1]; }
14675:     if ($courseid) {
14676: 	return $env{"course.$courseid.rndseed"};
14677:     }
14678:     return &latest_rnd_algorithm_id();
14679: }
14680: 
14681: sub validCODE {
14682:     my ($CODE)=@_;
14683:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
14684:     return 0;
14685: }
14686: 
14687: sub getCODE {
14688:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
14689:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
14690: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
14691: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
14692: 	return $Apache::lonhomework::history{'resource.CODE'};
14693:     }
14694:     return undef;
14695: }
14696: #
14697: #  Determines the random seed for a specific context:
14698: #
14699: # parameters:
14700: #   symb      - in course context the symb for the seed.
14701: #   course_id - The course id of the form domain_coursenum.
14702: #   domain    - Domain for the user.
14703: #   course    - Course for the user.
14704: #   cenv      - environment of the course.
14705: #
14706: # NOTE:
14707: #   All parameters are picked out of the environment if missing
14708: #   or not defined.
14709: #   If a symb cannot be determined the current time is used instead.
14710: #
14711: #  For a given well defined symb, courside, domain, username,
14712: #  and course environment, the seed is reproducible.
14713: #
14714: sub rndseed {
14715:     my ($symb,$courseid,$domain,$username, $cenv)=@_;
14716:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
14717:     if (!defined($symb)) {
14718: 	unless ($symb=$wsymb) { return time; }
14719:     }
14720:     if (!defined $courseid) { 
14721: 	$courseid=$wcourseid; 
14722:     }
14723:     if (!defined $domain) { $domain=$wdomain; }
14724:     if (!defined $username) { $username=$wusername }
14725: 
14726:     my $which;
14727:     if (defined($cenv->{'rndseed'})) {
14728: 	$which = $cenv->{'rndseed'};
14729:     } else {
14730: 	$which =&get_rand_alg($courseid);
14731:     }
14732:     if (defined(&getCODE())) {
14733: 
14734: 	if ($which eq '64bit5') {
14735: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
14736: 	} elsif ($which eq '64bit4') {
14737: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
14738: 	} else {
14739: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
14740: 	}
14741:     } elsif ($which eq '64bit5') {
14742: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
14743:     } elsif ($which eq '64bit4') {
14744: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
14745:     } elsif ($which eq '64bit3') {
14746: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
14747:     } elsif ($which eq '64bit2') {
14748: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
14749:     } elsif ($which eq '64bit') {
14750: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
14751:     }
14752:     return &rndseed_32bit($symb,$courseid,$domain,$username);
14753: }
14754: 
14755: sub rndseed_32bit {
14756:     my ($symb,$courseid,$domain,$username)=@_;
14757:     {
14758: 	use integer;
14759: 	my $symbchck=unpack("%32C*",$symb) << 27;
14760: 	my $symbseed=numval($symb) << 22;
14761: 	my $namechck=unpack("%32C*",$username) << 17;
14762: 	my $nameseed=numval($username) << 12;
14763: 	my $domainseed=unpack("%32C*",$domain) << 7;
14764: 	my $courseseed=unpack("%32C*",$courseid);
14765: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
14766: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
14767: 	#&logthis("rndseed :$num:$symb");
14768: 	if ($_64bit) { $num=(($num<<32)>>32); }
14769: 	return $num;
14770:     }
14771: }
14772: 
14773: sub rndseed_64bit {
14774:     my ($symb,$courseid,$domain,$username)=@_;
14775:     {
14776: 	use integer;
14777: 	my $symbchck=unpack("%32S*",$symb) << 21;
14778: 	my $symbseed=numval($symb) << 10;
14779: 	my $namechck=unpack("%32S*",$username);
14780: 	
14781: 	my $nameseed=numval($username) << 21;
14782: 	my $domainseed=unpack("%32S*",$domain) << 10;
14783: 	my $courseseed=unpack("%32S*",$courseid);
14784: 	
14785: 	my $num1=$symbchck+$symbseed+$namechck;
14786: 	my $num2=$nameseed+$domainseed+$courseseed;
14787: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
14788: 	#&logthis("rndseed :$num:$symb");
14789: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
14790: 	return "$num1,$num2";
14791:     }
14792: }
14793: 
14794: sub rndseed_64bit2 {
14795:     my ($symb,$courseid,$domain,$username)=@_;
14796:     {
14797: 	use integer;
14798: 	# strings need to be an even # of cahracters long, it it is odd the
14799:         # last characters gets thrown away
14800: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
14801: 	my $symbseed=numval($symb) << 10;
14802: 	my $namechck=unpack("%32S*",$username.' ');
14803: 	
14804: 	my $nameseed=numval($username) << 21;
14805: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
14806: 	my $courseseed=unpack("%32S*",$courseid.' ');
14807: 	
14808: 	my $num1=$symbchck+$symbseed+$namechck;
14809: 	my $num2=$nameseed+$domainseed+$courseseed;
14810: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
14811: 	#&logthis("rndseed :$num:$symb");
14812: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
14813: 	return "$num1,$num2";
14814:     }
14815: }
14816: 
14817: sub rndseed_64bit3 {
14818:     my ($symb,$courseid,$domain,$username)=@_;
14819:     {
14820: 	use integer;
14821: 	# strings need to be an even # of cahracters long, it it is odd the
14822:         # last characters gets thrown away
14823: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
14824: 	my $symbseed=numval2($symb) << 10;
14825: 	my $namechck=unpack("%32S*",$username.' ');
14826: 	
14827: 	my $nameseed=numval2($username) << 21;
14828: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
14829: 	my $courseseed=unpack("%32S*",$courseid.' ');
14830: 	
14831: 	my $num1=$symbchck+$symbseed+$namechck;
14832: 	my $num2=$nameseed+$domainseed+$courseseed;
14833: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
14834: 	#&logthis("rndseed :$num1:$num2:$_64bit");
14835: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
14836: 	
14837: 	return "$num1:$num2";
14838:     }
14839: }
14840: 
14841: sub rndseed_64bit4 {
14842:     my ($symb,$courseid,$domain,$username)=@_;
14843:     {
14844: 	use integer;
14845: 	# strings need to be an even # of cahracters long, it it is odd the
14846:         # last characters gets thrown away
14847: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
14848: 	my $symbseed=numval3($symb) << 10;
14849: 	my $namechck=unpack("%32S*",$username.' ');
14850: 	
14851: 	my $nameseed=numval3($username) << 21;
14852: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
14853: 	my $courseseed=unpack("%32S*",$courseid.' ');
14854: 	
14855: 	my $num1=$symbchck+$symbseed+$namechck;
14856: 	my $num2=$nameseed+$domainseed+$courseseed;
14857: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
14858: 	#&logthis("rndseed :$num1:$num2:$_64bit");
14859: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
14860: 	
14861: 	return "$num1:$num2";
14862:     }
14863: }
14864: 
14865: sub rndseed_64bit5 {
14866:     my ($symb,$courseid,$domain,$username)=@_;
14867:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
14868:     return "$num1:$num2";
14869: }
14870: 
14871: sub rndseed_CODE_64bit {
14872:     my ($symb,$courseid,$domain,$username)=@_;
14873:     {
14874: 	use integer;
14875: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
14876: 	my $symbseed=numval2($symb);
14877: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
14878: 	my $CODEseed=numval(&getCODE());
14879: 	my $courseseed=unpack("%32S*",$courseid.' ');
14880: 	my $num1=$symbseed+$CODEchck;
14881: 	my $num2=$CODEseed+$courseseed+$symbchck;
14882: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
14883: 	#&logthis("rndseed :$num1:$num2:$symb");
14884: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
14885: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
14886: 	return "$num1:$num2";
14887:     }
14888: }
14889: 
14890: sub rndseed_CODE_64bit4 {
14891:     my ($symb,$courseid,$domain,$username)=@_;
14892:     {
14893: 	use integer;
14894: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
14895: 	my $symbseed=numval3($symb);
14896: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
14897: 	my $CODEseed=numval3(&getCODE());
14898: 	my $courseseed=unpack("%32S*",$courseid.' ');
14899: 	my $num1=$symbseed+$CODEchck;
14900: 	my $num2=$CODEseed+$courseseed+$symbchck;
14901: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
14902: 	#&logthis("rndseed :$num1:$num2:$symb");
14903: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
14904: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
14905: 	return "$num1:$num2";
14906:     }
14907: }
14908: 
14909: sub rndseed_CODE_64bit5 {
14910:     my ($symb,$courseid,$domain,$username)=@_;
14911:     my $code = &getCODE();
14912:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
14913:     return "$num1:$num2";
14914: }
14915: 
14916: sub setup_random_from_rndseed {
14917:     my ($rndseed)=@_;
14918:     if ($rndseed =~/([,:])/) {
14919:         my ($num1,$num2) = map { abs($_); } (split(/[,:]/,$rndseed));
14920:         if ((!$num1) || (!$num2) || ($num1 > 2147483562) || ($num2 > 2147483398)) {
14921:             &Math::Random::random_set_seed_from_phrase($rndseed);
14922:         } else {
14923:             &Math::Random::random_set_seed($num1,$num2);
14924:         }
14925:     } else {
14926: 	&Math::Random::random_set_seed_from_phrase($rndseed);
14927:     }
14928: }
14929: 
14930: sub latest_receipt_algorithm_id {
14931:     return 'receipt3';
14932: }
14933: 
14934: sub recunique {
14935:     my $fucourseid=shift;
14936:     my $unique;
14937:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
14938: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
14939: 	$unique=$env{"course.$fucourseid.internal.encseed"};
14940:     } else {
14941: 	$unique=$perlvar{'lonReceipt'};
14942:     }
14943:     return unpack("%32C*",$unique);
14944: }
14945: 
14946: sub recprefix {
14947:     my $fucourseid=shift;
14948:     my $prefix;
14949:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
14950: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
14951: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
14952:     } else {
14953: 	$prefix=$perlvar{'lonHostID'};
14954:     }
14955:     return unpack("%32C*",$prefix);
14956: }
14957: 
14958: sub ireceipt {
14959:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
14960: 
14961:     my $return =&recprefix($fucourseid).'-';
14962: 
14963:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
14964: 	$env{'request.state'} eq 'construct') {
14965: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
14966: 	return $return;
14967:     }
14968: 
14969:     my $cuname=unpack("%32C*",$funame);
14970:     my $cudom=unpack("%32C*",$fudom);
14971:     my $cucourseid=unpack("%32C*",$fucourseid);
14972:     my $cusymb=unpack("%32C*",$fusymb);
14973:     my $cunique=&recunique($fucourseid);
14974:     my $cpart=unpack("%32S*",$part);
14975:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
14976: 
14977: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
14978: 			       
14979: 	$return.= ($cunique%$cuname+
14980: 		   $cunique%$cudom+
14981: 		   $cusymb%$cuname+
14982: 		   $cusymb%$cudom+
14983: 		   $cucourseid%$cuname+
14984: 		   $cucourseid%$cudom+
14985: 		   $cpart%$cuname+
14986: 		   $cpart%$cudom);
14987:     } else {
14988: 	$return.= ($cunique%$cuname+
14989: 		   $cunique%$cudom+
14990: 		   $cusymb%$cuname+
14991: 		   $cusymb%$cudom+
14992: 		   $cucourseid%$cuname+
14993: 		   $cucourseid%$cudom);
14994:     }
14995:     return $return;
14996: }
14997: 
14998: sub receipt {
14999:     my ($part)=@_;
15000:     my ($symb,$courseid,$domain,$name) = &whichuser();
15001:     return &ireceipt($name,$domain,$courseid,$symb,$part);
15002: }
15003: 
15004: sub whichuser {
15005:     my ($passedsymb)=@_;
15006:     my ($symb,$courseid,$domain,$name,$publicuser);
15007:     if (defined($env{'form.grade_symb'})) {
15008: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
15009: 	my $allowed=&allowed('vgr',$tmp_courseid);
15010: 	if (!$allowed &&
15011: 	    exists($env{'request.course.sec'}) &&
15012: 	    $env{'request.course.sec'} !~ /^\s*$/) {
15013: 	    $allowed=&allowed('vgr',$tmp_courseid.
15014: 			      '/'.$env{'request.course.sec'});
15015: 	}
15016: 	if ($allowed) {
15017: 	    ($symb)=&get_env_multiple('form.grade_symb');
15018: 	    $courseid=$tmp_courseid;
15019: 	    ($domain)=&get_env_multiple('form.grade_domain');
15020: 	    ($name)=&get_env_multiple('form.grade_username');
15021: 	    return ($symb,$courseid,$domain,$name,$publicuser);
15022: 	}
15023:     }
15024:     if (!$passedsymb) {
15025: 	$symb=&symbread();
15026:     } else {
15027: 	$symb=$passedsymb;
15028:     }
15029:     $courseid=$env{'request.course.id'};
15030:     $domain=$env{'user.domain'};
15031:     $name=$env{'user.name'};
15032:     if ($name eq 'public' && $domain eq 'public') {
15033: 	if (!defined($env{'form.username'})) {
15034: 	    $env{'form.username'}.=time.rand(10000000);
15035: 	}
15036: 	$name.=$env{'form.username'};
15037:     }
15038:     return ($symb,$courseid,$domain,$name,$publicuser);
15039: 
15040: }
15041: 
15042: # ------------------------------------------------------------ Serves up a file
15043: # returns either the contents of the file or 
15044: # -1 if the file doesn't exist
15045: #
15046: # if the target is a file that was uploaded via DOCS, 
15047: # a check will be made to see if a current copy exists on the local server,
15048: # if it does this will be served, otherwise a copy will be retrieved from
15049: # the home server for the course and stored in /home/httpd/html/userfiles on
15050: # the local server.   
15051: 
15052: sub getfile {
15053:     my ($file) = @_;
15054:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
15055:     &repcopy($file);
15056:     return &readfile($file);
15057: }
15058: 
15059: sub repcopy_userfile {
15060:     my ($file)=@_;
15061:     my $londocroot = $perlvar{'lonDocRoot'};
15062:     if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
15063:     if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
15064:     my ($cdom,$cnum,$filename) = 
15065: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
15066:     my $uri="/uploaded/$cdom/$cnum/$filename";
15067:     if (-e "$file") {
15068: # we already have a local copy, check it out
15069: 	my @fileinfo = stat($file);
15070: 	my $rtncode;
15071: 	my $info;
15072: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
15073: 	if ($lwpresp ne 'ok') {
15074: # there is no such file anymore, even though we had a local copy
15075: 	    if ($rtncode eq '404') {
15076: 		unlink($file);
15077: 	    }
15078: 	    return -1;
15079: 	}
15080: 	if ($info < $fileinfo[9]) {
15081: # nice, the file we have is up-to-date, just say okay
15082: 	    return 'ok';
15083: 	} else {
15084: # the file is outdated, get rid of it
15085: 	    unlink($file);
15086: 	}
15087:     }
15088: # one way or the other, at this point, we don't have the file
15089: # construct the correct path for the file
15090:     my @parts = ($cdom,$cnum); 
15091:     if ($filename =~ m|^(.+)/[^/]+$|) {
15092: 	push @parts, split(/\//,$1);
15093:     }
15094:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
15095:     foreach my $part (@parts) {
15096: 	$path .= '/'.$part;
15097: 	if (!-e $path) {
15098: 	    mkdir($path,0770);
15099: 	}
15100:     }
15101: # now the path exists for sure
15102: # get a user agent
15103:     my $transferfile=$file.'.in.transfer';
15104: # FIXME: this should flock
15105:     if (-e $transferfile) { return 'ok'; }
15106:     my $request;
15107:     $uri=~s/^\///;
15108:     my $homeserver = &homeserver($cnum,$cdom);
15109:     my $hostname = &hostname($homeserver);
15110:     my $protocol = $protocol{$homeserver};
15111:     $protocol = 'http' if ($protocol ne 'https');
15112:     $request=new HTTP::Request('GET',$protocol.'://'.$hostname.'/raw/'.$uri);
15113:     my $response = &LONCAPA::LWPReq::makerequest($homeserver,$request,$transferfile,\%perlvar,'',0,1);
15114: # did it work?
15115:     if ($response->is_error()) {
15116: 	unlink($transferfile);
15117: 	&logthis("Userfile repcopy failed for $uri");
15118: 	return -1;
15119:     }
15120: # worked, rename the transfer file
15121:     rename($transferfile,$file);
15122:     return 'ok';
15123: }
15124: 
15125: sub tokenwrapper {
15126:     my $uri=shift;
15127:     $uri=~s|^https?\://([^/]+)||;
15128:     $uri=~s|^/||;
15129:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
15130:     my $token=$1;
15131:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
15132:     if ($udom && $uname && $file) {
15133: 	$file=~s|(\?\.*)*$||;
15134:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
15135:         my $homeserver = &homeserver($uname,$udom);
15136:         my $hostname = &hostname($homeserver);
15137:         my $protocol = $protocol{$homeserver};
15138:         $protocol = 'http' if ($protocol ne 'https');
15139:         return $protocol.'://'.$hostname.'/'.$uri.
15140:                (($uri=~/\?/)?'&':'?').'token='.$token.
15141:                                '&tokenissued='.$perlvar{'lonHostID'};
15142:     } else {
15143:         return '/adm/notfound.html';
15144:     }
15145: }
15146: 
15147: # call with reqtype HEAD: get last modification time
15148: # call with reqtype GET: get the file contents
15149: # Do not call this with reqtype GET for large files! It loads everything into memory
15150: #
15151: sub getuploaded {
15152:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
15153:     $uri=~s/^\///;
15154:     my $homeserver = &homeserver($cnum,$cdom);
15155:     my $hostname = &hostname($homeserver);
15156:     my $protocol = $protocol{$homeserver};
15157:     $protocol = 'http' if ($protocol ne 'https');
15158:     $uri = $protocol.'://'.$hostname.'/raw/'.$uri;
15159:     my $request=new HTTP::Request($reqtype,$uri);
15160:     my $response=&LONCAPA::LWPReq::makerequest($homeserver,$request,'',\%perlvar,'',0,1);
15161:     $$rtncode = $response->code;
15162:     if (! $response->is_success()) {
15163: 	return 'failed';
15164:     }      
15165:     if ($reqtype eq 'HEAD') {
15166: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
15167:     } elsif ($reqtype eq 'GET') {
15168: 	$$info = $response->content;
15169:     }
15170:     return 'ok';
15171: }
15172: 
15173: sub readfile {
15174:     my $file = shift;
15175:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
15176:     my $fh;
15177:     open($fh,"<",$file);
15178:     my $a='';
15179:     while (my $line = <$fh>) { $a .= $line; }
15180:     return $a;
15181: }
15182: 
15183: sub filelocation {
15184:     my ($dir,$file) = @_;
15185:     my $location;
15186:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
15187: 
15188:     if ($file =~ m-^/adm/-) {
15189: 	$file=~s-^/adm/wrapper/-/-;
15190: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
15191:     }
15192: 
15193:     if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
15194:         $location = $file;
15195:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
15196:         my ($udom,$uname,$filename)=
15197:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
15198:         my $home=&homeserver($uname,$udom);
15199:         my $is_me=0;
15200:         my @ids=&current_machine_ids();
15201:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
15202:         if ($is_me) {
15203:   	    $location=propath($udom,$uname).'/userfiles/'.$filename;
15204:         } else {
15205:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
15206:   	      $udom.'/'.$uname.'/'.$filename;
15207:         }
15208:     } elsif ($file =~ m-^/adm/-) {
15209: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
15210:     } else {
15211:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
15212:         $file=~s:^/(res|priv)/:/:;
15213:         my $space=$1;
15214:         if ( !( $file =~ m:^/:) ) {
15215:             $location = $dir. '/'.$file;
15216:         } else {
15217:             $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
15218:         }
15219:     }
15220:     $location=~s://+:/:g; # remove duplicate /
15221:     while ($location=~m{/\.\./}) {
15222: 	if ($location =~ m{/[^/]+/\.\./}) {
15223: 	    $location=~ s{/[^/]+/\.\./}{/}g;
15224: 	} else {
15225: 	    $location=~ s{/\.\./}{/}g;
15226: 	}
15227:     } #remove dir/..
15228:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
15229:     return $location;
15230: }
15231: 
15232: sub hreflocation {
15233:     my ($dir,$file)=@_;
15234:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
15235: 	$file=filelocation($dir,$file);
15236:     } elsif ($file=~m-^/adm/-) {
15237: 	$file=~s-^/adm/wrapper/-/-;
15238: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
15239:     }
15240:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
15241: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
15242:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
15243: 	$file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
15244: 	        {/uploaded/$1/$2/}x;
15245:     }
15246:     if ($file=~ m{^/userfiles/}) {
15247: 	$file =~ s{^/userfiles/}{/uploaded/};
15248:     }
15249:     return $file;
15250: }
15251: 
15252: 
15253: 
15254: 
15255: 
15256: sub current_machine_domains {
15257:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
15258: }
15259: 
15260: sub machine_domains {
15261:     my ($hostname) = @_;
15262:     my @domains;
15263:     my %hostname = &all_hostnames();
15264:     while( my($id, $name) = each(%hostname)) {
15265: #	&logthis("-$id-$name-$hostname-");
15266: 	if ($hostname eq $name) {
15267: 	    push(@domains,&host_domain($id));
15268: 	}
15269:     }
15270:     return @domains;
15271: }
15272: 
15273: sub current_machine_ids {
15274:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
15275: }
15276: 
15277: sub machine_ids {
15278:     my ($hostname) = @_;
15279:     $hostname ||= &hostname($perlvar{'lonHostID'});
15280:     my @ids;
15281:     my %name_to_host = &all_names();
15282:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
15283: 	return @{ $name_to_host{$hostname} };
15284:     }
15285:     return;
15286: }
15287: 
15288: sub additional_machine_domains {
15289:     my @domains;
15290:     if (-e "$perlvar{'lonTabDir'}/expected_domains.tab") {
15291:         if (open(my $fh,"<","$perlvar{'lonTabDir'}/expected_domains.tab")) {
15292:             while (my $line = <$fh>) {
15293:                 chomp($line);           
15294:                 $line =~ s/\s//g;
15295:                 push(@domains,$line);
15296:             }
15297:             close($fh);
15298:         }
15299:     }
15300:     return @domains;
15301: }
15302: 
15303: sub default_login_domain {
15304:     my $domain = $perlvar{'lonDefDomain'};
15305:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
15306:     foreach my $posdom (&current_machine_domains(),
15307:                         &additional_machine_domains()) {
15308:         if (lc($posdom) eq lc($testdomain)) {
15309:             $domain=$posdom;
15310:             last;
15311:         }
15312:     }
15313:     return $domain;
15314: }
15315: 
15316: sub shared_institution {
15317:     my ($dom,$lonhost) = @_;
15318:     if ($lonhost eq '') {
15319:         $lonhost = $perlvar{'lonHostID'};
15320:     }
15321:     my $same_intdom;
15322:     my $hostintdom = &internet_dom($lonhost);
15323:     if ($hostintdom ne '') {
15324:         my %iphost = &get_iphost();
15325:         my $primary_id = &domain($dom,'primary');
15326:         my $primary_ip = &get_host_ip($primary_id);
15327:         if (ref($iphost{$primary_ip}) eq 'ARRAY') {
15328:             foreach my $id (@{$iphost{$primary_ip}}) {
15329:                 my $intdom = &internet_dom($id);
15330:                 if ($intdom eq $hostintdom) {
15331:                     $same_intdom = 1;
15332:                     last;
15333:                 }
15334:             }
15335:         }
15336:     }
15337:     return $same_intdom;
15338: }
15339: 
15340: sub uses_sts {
15341:     my ($ignore_cache) = @_;
15342:     my $lonhost = $perlvar{'lonHostID'};
15343:     my $hostname = &hostname($lonhost);
15344:     my $sts_on;
15345:     if ($protocol{$lonhost} eq 'https') {
15346:         my $cachetime = 12*3600;
15347:         if (!$ignore_cache) {
15348:             ($sts_on,my $cached)=&is_cached_new('stspolicy',$lonhost);
15349:             if (defined($cached)) {
15350:                 return $sts_on;
15351:             }
15352:         }
15353:         my $url = $protocol{$lonhost}.'://'.$hostname.'/index.html';
15354:         my $request=new HTTP::Request('HEAD',$url);
15355:         my $response=&LONCAPA::LWPReq::makerequest($lonhost,$request,'',\%perlvar,'','','',1);
15356:         if ($response->is_success) {
15357:             my $has_sts = $response->header('Strict-Transport-Security');
15358:             if ($has_sts eq '') {
15359:                 $sts_on = 0;
15360:             } else {
15361:                 if ($has_sts =~ /\Qmax-age=\E(\d+)/) {
15362:                     my $maxage = $1;
15363:                     if ($maxage) {
15364:                         $sts_on = 1;
15365:                     } else {
15366:                         $sts_on = 0;
15367:                     }
15368:                 } else {
15369:                     $sts_on = 0;
15370:                 }
15371:             }
15372:             return &do_cache_new('stspolicy',$lonhost,$sts_on,$cachetime);
15373:         }
15374:     }
15375:     return;
15376: }
15377: 
15378: sub waf_allssl {
15379:     my ($host_name) = @_;
15380:     my $alias = &get_proxy_alias();
15381:     if ($host_name eq '') {
15382:         $host_name = $ENV{'SERVER_NAME'};
15383:     }
15384:     if (($host_name ne '') && ($alias eq $host_name)) {
15385:         my $serverhomedom = &host_domain($perlvar{'lonHostID'});
15386:         my %defdomdefaults = &get_domain_defaults($serverhomedom);
15387:         if ($defdomdefaults{'waf_sslopt'}) {
15388:             return $defdomdefaults{'waf_sslopt'};
15389:         }
15390:     }
15391:     return;
15392: }
15393: 
15394: sub get_requestor_ip {
15395:     my ($r,$nolookup,$noproxy) = @_;
15396:     my $from_ip;
15397:     if (ref($r)) {
15398:         if ($r->can('useragent_ip')) {
15399:             if ($noproxy && $r->can('client_ip')) {
15400:                 $from_ip = $r->client_ip();
15401:             } else {
15402:                 $from_ip = $r->useragent_ip();
15403:             }
15404:         } elsif ($r->connection->can('remote_ip')) {
15405:             $from_ip = $r->connection->remote_ip();
15406:         } else {
15407:             $from_ip = $r->get_remote_host($nolookup);
15408:         }
15409:     } else {
15410:         $from_ip = $ENV{'REMOTE_ADDR'};
15411:     }
15412:     return $from_ip if ($noproxy); 
15413:     # Who controls proxy settings for server
15414:     my $dom_in_use = $Apache::lonnet::perlvar{'lonDefDomain'};
15415:     my $proxyinfo = &get_proxy_settings($dom_in_use);
15416:     if ((ref($proxyinfo) eq 'HASH') && ($from_ip)) {
15417:         if ($proxyinfo->{'vpnint'}) {
15418:             if (&ip_match($from_ip,$proxyinfo->{'vpnint'})) {
15419:                 return $from_ip;
15420:             }
15421:         }
15422:         if ($proxyinfo->{'trusted'}) {
15423:             if (&ip_match($from_ip,$proxyinfo->{'trusted'})) {
15424:                 my $ipheader = $proxyinfo->{'ipheader'};
15425:                 my ($ip,$xfor);
15426:                 if (ref($r)) {
15427:                     if ($ipheader) {
15428:                         $ip = $r->headers_in->{$ipheader};
15429:                     }
15430:                     $xfor = $r->headers_in->{'X-Forwarded-For'};
15431:                 } else {
15432:                     if ($ipheader) {
15433:                         $ip = $ENV{'HTTP_'.uc($ipheader)};
15434:                     }
15435:                     $xfor = $ENV{'HTTP_X_FORWARDED_FOR'};
15436:                 }
15437:                 if (($ip eq '') && ($xfor ne '')) {
15438:                     foreach my $poss_ip (reverse(split(/\s*,\s*/,$xfor))) {
15439:                         unless (&ip_match($poss_ip,$proxyinfo->{'trusted'})) {
15440:                             $ip = $poss_ip;
15441:                             last;
15442:                         }
15443:                     }
15444:                 }
15445:                 if ($ip ne '') {
15446:                     return $ip;
15447:                 }
15448:             }
15449:         }
15450:     }
15451:     return $from_ip;
15452: }
15453: 
15454: sub get_proxy_settings {
15455:     my ($dom_in_use) = @_;
15456:     my %domdefaults = &get_domain_defaults($dom_in_use);
15457:     my $proxyinfo = {
15458:                        ipheader => $domdefaults{'waf_ipheader'},
15459:                        trusted  => $domdefaults{'waf_trusted'},
15460:                        vpnint   => $domdefaults{'waf_vpnint'},
15461:                        vpnext   => $domdefaults{'waf_vpnext'},
15462:                        sslopt   => $domdefaults{'waf_sslopt'},
15463:                     };
15464:     return $proxyinfo;
15465: }
15466: 
15467: sub ip_match {
15468:     my ($ip,$pattern_str) = @_;
15469:     $ip=Net::CIDR::cidrvalidate($ip);
15470:     if ($ip) {
15471:         return Net::CIDR::cidrlookup($ip,split(/\s*,\s*/,$pattern_str));
15472:     }
15473:     return;
15474: }
15475: 
15476: sub get_proxy_alias {
15477:     my ($lonid) = @_;
15478:     if ($lonid eq '') {
15479:         $lonid = $perlvar{'lonHostID'};
15480:     }
15481:     if (!defined(&hostname($lonid))) {
15482:         return;
15483:     }
15484:     if ($lonid ne '') {
15485:         my ($alias,$cached) = &is_cached_new('proxyalias',$lonid);
15486:         if ($cached) {
15487:             return $alias;
15488:         }
15489:         my $dom = &host_domain($lonid);
15490:         if ($dom ne '') {
15491:             my $cachetime = 60*60*24;
15492:             my %domconfig =
15493:                 &get_dom('configuration',['wafproxy'],$dom);
15494:             if (ref($domconfig{'wafproxy'}) eq 'HASH') {
15495:                 if (ref($domconfig{'wafproxy'}{'alias'}) eq 'HASH') {
15496:                     $alias = $domconfig{'wafproxy'}{'alias'}{$lonid};
15497:                 }
15498:             }
15499:             return &do_cache_new('proxyalias',$lonid,$alias,$cachetime);
15500:         }
15501:     }
15502:     return;
15503: }
15504: 
15505: sub use_proxy_alias {
15506:     my ($r,$lonid) = @_;
15507:     my $alias = &get_proxy_alias($lonid);
15508:     if ($alias) {
15509:         my $dom = &host_domain($lonid);
15510:         if ($dom ne '') {
15511:             my $proxyinfo = &get_proxy_settings($dom);
15512:             my ($vpnint,$remote_ip);
15513:             if (ref($proxyinfo) eq 'HASH') {
15514:                 $vpnint = $proxyinfo->{'vpnint'};
15515:                 if ($vpnint) {
15516:                     $remote_ip = &get_requestor_ip($r,1,1);
15517:                 }
15518:             }
15519:             unless ($vpnint && &ip_match($remote_ip,$vpnint)) {
15520:                 return $alias;
15521:             }
15522:         }
15523:     }
15524:     return;
15525: }
15526: 
15527: sub alias_sso {
15528:     my ($lonid) = @_;
15529:     if ($lonid eq '') {
15530:         $lonid = $perlvar{'lonHostID'};
15531:     }
15532:     if (!defined(&hostname($lonid))) {
15533:         return;
15534:     }
15535:     if ($lonid ne '') {
15536:         my ($use_alias,$cached) = &is_cached_new('proxysaml',$lonid);
15537:         if ($cached) {
15538:             return $use_alias;
15539:         }
15540:         my $dom = &host_domain($lonid);
15541:         if ($dom ne '') {
15542:             my $cachetime = 60*60*24;
15543:             my %domconfig =
15544:                 &get_dom('configuration',['wafproxy'],$dom);
15545:             if (ref($domconfig{'wafproxy'}) eq 'HASH') {
15546:                 if (ref($domconfig{'wafproxy'}{'saml'}) eq 'HASH') {
15547:                     $use_alias = $domconfig{'wafproxy'}{'saml'}{$lonid};
15548:                 }
15549:             }
15550:             return &do_cache_new('proxysaml',$lonid,$use_alias,$cachetime);
15551:         }
15552:     }
15553:     return;
15554: }
15555: 
15556: sub get_saml_landing {
15557:     my ($lonid) = @_;
15558:     if ($lonid eq '') {
15559:         my $defdom = &default_login_domain();
15560:         my @hosts = &current_machine_ids();
15561:         if (@hosts > 1) {
15562:             foreach my $hostid (@hosts) {
15563:                 if (&host_domain($hostid) eq $defdom) {
15564:                     $lonid = $hostid;
15565:                     last;
15566:                 }
15567:             }
15568:         } else {
15569:             $lonid = $perlvar{'lonHostID'};
15570:         }
15571:         if ($lonid) {
15572:             unless (&host_domain($lonid) eq $defdom) {
15573:                 return;
15574:             }
15575:         } else {
15576:             return;
15577:         }
15578:     } elsif (!defined(&hostname($lonid))) {
15579:         return;
15580:     }
15581:     my ($landing,$cached) = &is_cached_new('samllanding',$lonid);
15582:     if ($cached) {
15583:         return $landing;
15584:     }
15585:     my $dom = &host_domain($lonid);
15586:     if ($dom ne '') {
15587:         my $cachetime = 60*60*24;
15588:         my %domconfig =
15589:             &get_dom('configuration',['login'],$dom);
15590:         if (ref($domconfig{'login'}) eq 'HASH') {
15591:             if (ref($domconfig{'login'}{'saml'}) eq 'HASH') {
15592:                 if (ref($domconfig{'login'}{'saml'}{$lonid}) eq 'HASH') {
15593:                     $landing = 1;
15594:                 }
15595:             }
15596:         }
15597:         return &do_cache_new('samllanding',$lonid,$landing,$cachetime);
15598:     }
15599:     return;
15600: }
15601: 
15602: # ------------------------------------------------------------- Declutters URLs
15603: 
15604: sub declutter {
15605:     my $thisfn=shift;
15606:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
15607:     unless ($thisfn=~m{^/home/httpd/html/priv/}) {
15608:         $thisfn=~s{^/home/httpd/html}{};
15609:     }
15610:     $thisfn=~s/^\///;
15611:     $thisfn=~s|^adm/wrapper/||;
15612:     $thisfn=~s|^adm/coursedocs/showdoc/||;
15613:     $thisfn=~s/^res\///;
15614:     $thisfn=~s/^priv\///;
15615:     unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
15616:         $thisfn=~s/\?.+$//;
15617:     }
15618:     return $thisfn;
15619: }
15620: 
15621: # ------------------------------------------------------------- Clutter up URLs
15622: 
15623: sub clutter {
15624:     my $thisfn='/'.&declutter(shift);
15625:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
15626: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
15627:        $thisfn='/res'.$thisfn; 
15628:     }
15629:     if ($thisfn !~m|^/adm|) {
15630: 	if ($thisfn =~ m|^/ext/|) {
15631: 	    $thisfn='/adm/wrapper'.$thisfn;
15632: 	} else {
15633: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
15634: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
15635: 	    if ($embstyle eq 'ssi'
15636: 		|| ($embstyle eq 'hdn')
15637: 		|| ($embstyle eq 'rat')
15638: 		|| ($embstyle eq 'prv')
15639: 		|| ($embstyle eq 'ign')) {
15640: 		#do nothing with these
15641: 	    } elsif (($embstyle eq 'img') 
15642: 		|| ($embstyle eq 'emb')
15643: 		|| ($embstyle eq 'wrp')) {
15644: 		$thisfn='/adm/wrapper'.$thisfn;
15645: 	    } elsif ($embstyle eq 'unk'
15646: 		     && $thisfn!~/\.(sequence|page)$/) {
15647: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
15648: 	    } else {
15649: #		&logthis("Got a blank emb style");
15650: 	    }
15651: 	}
15652:     } elsif ($thisfn =~ m{^/adm/$match_domain/$match_courseid/\d+/ext\.tool$}) {
15653:         $thisfn='/adm/wrapper'.$thisfn;
15654:     }
15655:     return $thisfn;
15656: }
15657: 
15658: sub clutter_with_no_wrapper {
15659:     my $uri = &clutter(shift);
15660:     if ($uri =~ m-^/adm/-) {
15661: 	$uri =~ s-^/adm/wrapper/-/-;
15662: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
15663:     }
15664:     return $uri;
15665: }
15666: 
15667: sub freeze_escape {
15668:     my ($value)=@_;
15669:     if (ref($value)) {
15670: 	$value=&nfreeze($value);
15671: 	return '__FROZEN__'.&escape($value);
15672:     }
15673:     return &escape($value);
15674: }
15675: 
15676: 
15677: sub thaw_unescape {
15678:     my ($value)=@_;
15679:     if ($value =~ /^__FROZEN__/) {
15680: 	substr($value,0,10,undef);
15681: 	$value=&unescape($value);
15682: 	return &thaw($value);
15683:     }
15684:     return &unescape($value);
15685: }
15686: 
15687: sub correct_line_ends {
15688:     my ($result)=@_;
15689:     $$result =~s/\r\n/\n/mg;
15690:     $$result =~s/\r/\n/mg;
15691: }
15692: # ================================================================ Main Program
15693: 
15694: sub goodbye {
15695:    &logthis("Starting Shut down");
15696: #not converted to using infrastruture and probably shouldn't be
15697:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
15698: #converted
15699: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
15700:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
15701: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
15702: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
15703: #1.1 only
15704: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
15705: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
15706: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
15707: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
15708:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
15709:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
15710:    &logthis(sprintf("%-20s is %s",'hits',$hits));
15711:    &flushcourselogs();
15712:    &logthis("Shutting down");
15713: }
15714: 
15715: sub get_dns {
15716:     my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
15717:     if (!$ignore_cache) {
15718: 	my ($content,$cached)=
15719: 	    &is_cached_new('dns',$url);
15720: 	if ($cached) {
15721: 	    &$func($content,$hashref);
15722: 	    return;
15723: 	}
15724:     }
15725: 
15726:     my %alldns;
15727:     if (open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab")) {
15728:         foreach my $dns (<$config>) {
15729: 	    next if ($dns !~ /^\^(\S*)/x);
15730:             my $line = $1;
15731:             my ($host,$protocol) = split(/:/,$line);
15732:             if ($protocol ne 'https') {
15733:                 $protocol = 'http';
15734:             }
15735: 	    $alldns{$host} = $protocol;
15736:         }
15737:         close($config);
15738:     }
15739:     while (%alldns) {
15740: 	my ($dns) = sort { $b cmp $a } keys(%alldns);
15741:         my ($contents,@content);
15742:         if ($dns eq Sys::Hostname::FQDN::fqdn()) {
15743:             my $command = (split('/',$url))[3];
15744:             my ($dir,$file) = &parse_getdns_url($command,$url);
15745:             delete($alldns{$dns});
15746:             next if (($dir eq '') || ($file eq ''));
15747:             if (open(my $config,'<',"$dir/$file")) {
15748:                 @content = <$config>;
15749:                 close($config);
15750:             }
15751:             if ($url eq '/adm/dns/loncapaCRL') {
15752:                 $contents = join('',@content);
15753:             }
15754:         } else {
15755: 	    my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
15756:             my $response = &LONCAPA::LWPReq::makerequest('',$request,'',\%perlvar,30,0);
15757:             delete($alldns{$dns});
15758: 	    next if ($response->is_error());
15759:             if ($url eq '/adm/dns/loncapaCRL') {
15760:                 $contents = $response->content;
15761:             } else {
15762:                 @content = split("\n",$response->content);
15763:             }
15764:         }
15765:         if ($url eq '/adm/dns/loncapaCRL') {
15766:             return &$func($contents);
15767:         } else {
15768: 	    unless ($nocache) {
15769: 	        &do_cache_new('dns',$url,\@content,30*24*60*60);
15770: 	    }
15771: 	    &$func(\@content,$hashref);
15772:             return;
15773:         }
15774:     }
15775:     my $which = (split('/',$url,4))[3];
15776:     if ($which eq 'loncapaCRL') {
15777:         my $diskfile = "$perlvar{'lonCertificateDirectory'}/$perlvar{'lonnetCertRevocationList'}";
15778:         if (-e $diskfile) {
15779:             &logthis("unable to contact DNS, on disk file $diskfile not updated");
15780:         } else {
15781:             &logthis("unable to contact DNS, no on disk file $diskfile available");
15782:         }
15783:     } else {
15784:         &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
15785:         if (open(my $config,"<","$perlvar{'lonTabDir'}/dns_$which.tab")) {
15786:             my @content = <$config>;
15787:             close($config);
15788:             &$func(\@content,$hashref);
15789:         }
15790:     }
15791:     return;
15792: }
15793: 
15794: # ------------------------------------------------------Get DNS checksums file
15795: sub parse_dns_checksums_tab {
15796:     my ($lines,$hashref) = @_;
15797:     my $lonhost = $perlvar{'lonHostID'};
15798:     my $machine_dom = &host_domain($lonhost);
15799:     my $loncaparev = &get_server_loncaparev($machine_dom);
15800:     my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
15801:     my $webconfdir = '/etc/httpd/conf';
15802:     if ($distro =~ /^(ubuntu|debian)(\d+)$/) {
15803:         $webconfdir = '/etc/apache2';
15804:     } elsif ($distro =~ /^sles(\d+)$/) {
15805:         if ($1 >= 10) {
15806:             $webconfdir = '/etc/apache2';
15807:         }
15808:     } elsif ($distro =~ /^suse(\d+\.\d+)$/) {
15809:         if ($1 >= 10.0) {
15810:             $webconfdir = '/etc/apache2';
15811:         }
15812:     }
15813:     my ($release,$timestamp) = split(/\-/,$loncaparev);
15814:     my (%chksum,%revnum);
15815:     if (ref($lines) eq 'ARRAY') {
15816:         chomp(@{$lines});
15817:         my $version = shift(@{$lines});
15818:         if ($version eq $release) {  
15819:             foreach my $line (@{$lines}) {
15820:                 my ($file,$version,$shasum) = split(/,/,$line);
15821:                 if ($file =~ m{^/etc/httpd/conf}) {
15822:                     if ($webconfdir eq '/etc/apache2') {
15823:                         $file =~ s{^\Q/etc/httpd/conf/\E}{$webconfdir/};
15824:                     }
15825:                 }
15826:                 $chksum{$file} = $shasum;
15827:                 $revnum{$file} = $version;
15828:             }
15829:             if (ref($hashref) eq 'HASH') {
15830:                 %{$hashref} = (
15831:                                 sums     => \%chksum,
15832:                                 versions => \%revnum,
15833:                               );
15834:             }
15835:         }
15836:     }
15837:     return;
15838: }
15839: 
15840: sub fetch_dns_checksums {
15841:     my %checksums;
15842:     my $machine_dom = &host_domain($perlvar{'lonHostID'});
15843:     my $loncaparev = &get_server_loncaparev($machine_dom,$perlvar{'lonHostID'});
15844:     my ($release,$timestamp) = split(/\-/,$loncaparev);
15845:     &get_dns("/adm/dns/checksums/$release",\&parse_dns_checksums_tab,1,1,
15846:              \%checksums);
15847:     return \%checksums;
15848: }
15849: 
15850: sub fetch_crl_pemfile {
15851:     return &get_dns("/adm/dns/loncapaCRL",\&save_crl_pem,1,1);
15852: }
15853: 
15854: sub save_crl_pem {
15855:     my ($content) = @_;
15856:     my ($msg,$hadchanges);
15857:     if ($content ne '') {
15858:         my $now = time;
15859:         my $lonca = $perlvar{'lonCertificateDirectory'}.'/'.$perlvar{'lonnetCertificateAuthority'};
15860:         my $tmpcrl = $tmpdir.'/'.$perlvar{'lonnetCertRevocationList'}.'_'.$now.'.'.$$.'.tmp';
15861:         if (open(my $fh,'>',"$tmpcrl")) {
15862:             print $fh $content;
15863:             close($fh);
15864:             if (-e $lonca) {
15865:                 if (open(PIPE,"openssl crl -in $tmpcrl -inform pem -CAfile $lonca -noout 2>&1 |")) {
15866:                     my $check = <PIPE>;
15867:                     close(PIPE);
15868:                     chomp($check);
15869:                     if ($check eq 'verify OK') {
15870:                         my $dest = "$perlvar{'lonCertificateDirectory'}/$perlvar{'lonnetCertRevocationList'}";
15871:                         my $backup;
15872:                         if (-e $dest) {
15873:                             if (&File::Copy::move($dest,"$dest.bak")) {
15874:                                 $backup = 'ok';
15875:                             }
15876:                         }
15877:                         if (&File::Copy::move($tmpcrl,$dest)) {
15878:                             $msg = 'ok';
15879:                             if ($backup) {
15880:                                 my (%oldnums,%newnums);
15881:                                 if (open(PIPE, "openssl crl -inform PEM -text -noout -in $dest.bak |grep 'Serial Number' |")) {
15882:                                     while (<PIPE>) {
15883:                                         $oldnums{(split(/:/))[1]} = 1;
15884:                                     }
15885:                                     close(PIPE);
15886:                                 }
15887:                                 if (open(PIPE, "openssl crl -inform PEM -text -noout -in $dest |grep 'Serial Number' |")) {
15888:                                     while(<PIPE>) {
15889:                                         $newnums{(split(/:/))[1]} = 1;
15890:                                     }
15891:                                     close(PIPE);
15892:                                 }
15893:                                 foreach my $key (sort {$b <=> $a } (keys(%newnums))) {
15894:                                     unless (exists($oldnums{$key})) {
15895:                                         $hadchanges = 1;
15896:                                         last;
15897:                                     }
15898:                                 }
15899:                                 unless ($hadchanges) {
15900:                                     foreach my $key (sort {$b <=> $a } (keys(%oldnums))) {
15901:                                         unless (exists($newnums{$key})) {
15902:                                             $hadchanges = 1;
15903:                                             last;
15904:                                         }
15905:                                     }
15906:                                 }
15907:                             }
15908:                         }
15909:                     } else {
15910:                         unlink($tmpcrl);
15911:                     }
15912:                 } else {
15913:                     unlink($tmpcrl);
15914:                 }
15915:             } else {
15916:                 unlink($tmpcrl);
15917:             }
15918:         }
15919:     }
15920:     return ($msg,$hadchanges);
15921: }
15922: 
15923: sub parse_getdns_url {
15924:     my ($command,$url) = @_;
15925:     my $dir = $perlvar{'lonTabDir'};
15926:     my $file;
15927:     if ($command eq 'hosts') {
15928:         $file = 'dns_hosts.tab';
15929:     } elsif ($command eq 'domain') {
15930:         $file = 'dns_domain.tab';
15931:     } elsif ($command eq 'checksums') {
15932:         my $version = (split('/',$url))[4];
15933:         $file = "dns_checksums/$version.tab",
15934:     } elsif ($command eq 'loncapaCRL') {
15935:         $dir = $perlvar{'lonCertificateDirectory'};
15936:         $file = $perlvar{'lonnetCertRevocationList'};
15937:     }
15938:     return ($dir,$file);
15939: }
15940: 
15941: # ------------------------------------------------------------ Read domain file
15942: {
15943:     my $loaded;
15944:     my %domain;
15945: 
15946:     sub parse_domain_tab {
15947: 	my ($lines) = @_;
15948: 	foreach my $line (@$lines) {
15949: 	    next if ($line =~ /^(\#|\s*$ )/x);
15950: 
15951: 	    chomp($line);
15952: 	    my ($name,@elements) = split(/:/,$line,9);
15953: 	    my %this_domain;
15954: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
15955: 			       'lang_def', 'city', 'longi', 'lati',
15956: 			       'primary') {
15957: 		$this_domain{$field} = shift(@elements);
15958: 	    }
15959: 	    $domain{$name} = \%this_domain;
15960: 	}
15961:     }
15962: 
15963:     sub reset_domain_info {
15964: 	undef($loaded);
15965: 	undef(%domain);
15966:     }
15967: 
15968:     sub load_domain_tab {
15969: 	my ($ignore_cache,$nocache) = @_;
15970: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache,$nocache);
15971: 	my $fh;
15972: 	if (open($fh,"<",$perlvar{'lonTabDir'}.'/domain.tab')) {
15973: 	    my @lines = <$fh>;
15974: 	    &parse_domain_tab(\@lines);
15975: 	}
15976: 	close($fh);
15977: 	$loaded = 1;
15978:     }
15979: 
15980:     sub domain {
15981: 	&load_domain_tab() if (!$loaded);
15982: 
15983: 	my ($name,$what) = @_;
15984: 	return if ( !exists($domain{$name}) );
15985: 
15986: 	if (!$what) {
15987: 	    return $domain{$name}{'description'};
15988: 	}
15989: 	return $domain{$name}{$what};
15990:     }
15991: 
15992:     sub domain_info {
15993:         &load_domain_tab() if (!$loaded);
15994:         return %domain;
15995:     }
15996: 
15997: }
15998: 
15999: 
16000: # ------------------------------------------------------------- Read hosts file
16001: {
16002:     my %hostname;
16003:     my %hostdom;
16004:     my %libserv;
16005:     my $loaded;
16006:     my %name_to_host;
16007:     my %internetdom;
16008:     my %LC_dns_serv;
16009: 
16010:     sub parse_hosts_tab {
16011: 	my ($file) = @_;
16012: 	foreach my $configline (@$file) {
16013: 	    next if ($configline =~ /^(\#|\s*$ )/x);
16014:             chomp($configline);
16015: 	    if ($configline =~ /^\^/) {
16016:                 if ($configline =~ /^\^([\w.\-]+)/) {
16017:                     $LC_dns_serv{$1} = 1;
16018:                 }
16019:                 next;
16020:             }
16021: 	    my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
16022: 	    $name=~s/\s//g;
16023: 	    if ($id && $domain && $role && $name) {
16024:                 if ((exists($hostname{$id})) && ($hostname{$id} ne '')) {
16025:                     my $curr = $hostname{$id};
16026:                     my $skip;
16027:                     if (ref($name_to_host{$curr}) eq 'ARRAY') {
16028:                         if (($curr eq $name) && (@{$name_to_host{$curr}} == 1)) {
16029:                             $skip = 1;
16030:                         } else {
16031:                             @{$name_to_host{$curr}} = grep { $_ ne $id } @{$name_to_host{$curr}};
16032:                         }
16033:                     }
16034:                     unless ($skip) {
16035:                         push(@{$name_to_host{$name}},$id);
16036:                     }
16037:                 } else {
16038:                     push(@{$name_to_host{$name}},$id);
16039:                 }
16040: 		$hostname{$id}=$name;
16041: 		$hostdom{$id}=$domain;
16042: 		if ($role eq 'library') { $libserv{$id}=$name; }
16043:                 if (defined($protocol)) {
16044:                     if ($protocol eq 'https') {
16045:                         $protocol{$id} = $protocol;
16046:                     } else {
16047:                         $protocol{$id} = 'http'; 
16048:                     }
16049:                 } else {
16050:                     $protocol{$id} = 'http';
16051:                 }
16052:                 if (defined($intdom)) {
16053:                     $internetdom{$id} = $intdom;
16054:                 }
16055: 	    }
16056: 	}
16057:     }
16058:     
16059:     sub reset_hosts_info {
16060: 	&purge_remembered();
16061: 	&reset_domain_info();
16062: 	&reset_hosts_ip_info();
16063:         undef(%internetdom);
16064: 	undef(%name_to_host);
16065: 	undef(%hostname);
16066: 	undef(%hostdom);
16067: 	undef(%libserv);
16068: 	undef($loaded);
16069:     }
16070: 
16071:     sub load_hosts_tab {
16072: 	my ($ignore_cache,$nocache) = @_;
16073: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache,$nocache);
16074: 	open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab");
16075: 	my @config = <$config>;
16076: 	&parse_hosts_tab(\@config);
16077: 	close($config);
16078: 	$loaded=1;
16079:     }
16080: 
16081:     sub hostname {
16082: 	&load_hosts_tab() if (!$loaded);
16083: 
16084: 	my ($lonid) = @_;
16085: 	return $hostname{$lonid};
16086:     }
16087: 
16088:     sub all_hostnames {
16089: 	&load_hosts_tab() if (!$loaded);
16090: 
16091: 	return %hostname;
16092:     }
16093: 
16094:     sub all_names {
16095:         my ($ignore_cache,$nocache) = @_;
16096: 	&load_hosts_tab($ignore_cache,$nocache) if (!$loaded);
16097: 
16098: 	return %name_to_host;
16099:     }
16100: 
16101:     sub all_host_domain {
16102:         &load_hosts_tab() if (!$loaded);
16103:         return %hostdom;
16104:     }
16105: 
16106:     sub all_host_intdom {
16107:         &load_hosts_tab() if (!$loaded);
16108:         return %internetdom;
16109:     }
16110: 
16111:     sub is_library {
16112: 	&load_hosts_tab() if (!$loaded);
16113: 
16114: 	return exists($libserv{$_[0]});
16115:     }
16116: 
16117:     sub all_library {
16118: 	&load_hosts_tab() if (!$loaded);
16119: 
16120: 	return %libserv;
16121:     }
16122: 
16123:     sub unique_library {
16124: 	#2x reverse removes all hostnames that appear more than once
16125:         my %unique = reverse &all_library();
16126:         return reverse %unique;
16127:     }
16128: 
16129:     sub get_servers {
16130: 	&load_hosts_tab() if (!$loaded);
16131: 
16132: 	my ($domain,$type) = @_;
16133: 	my %possible_hosts = ($type eq 'library') ? %libserv
16134: 	                                          : %hostname;
16135: 	my %result;
16136: 	if (ref($domain) eq 'ARRAY') {
16137: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
16138: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
16139: 		    $result{$host} = $hostname;
16140: 		}
16141: 	    }
16142: 	} else {
16143: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
16144: 		if ($hostdom{$host} eq $domain) {
16145: 		    $result{$host} = $hostname;
16146: 		}
16147: 	    }
16148: 	}
16149: 	return %result;
16150:     }
16151: 
16152:     sub get_unique_servers {
16153:         my %unique = reverse &get_servers(@_);
16154: 	return reverse %unique;
16155:     }
16156: 
16157:     sub host_domain {
16158: 	&load_hosts_tab() if (!$loaded);
16159: 
16160: 	my ($lonid) = @_;
16161: 	return $hostdom{$lonid};
16162:     }
16163: 
16164:     sub all_domains {
16165: 	&load_hosts_tab() if (!$loaded);
16166: 
16167: 	my %seen;
16168: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
16169: 	return @uniq;
16170:     }
16171: 
16172:     sub internet_dom {
16173:         &load_hosts_tab() if (!$loaded);
16174: 
16175:         my ($lonid) = @_;
16176:         return $internetdom{$lonid};
16177:     }
16178: 
16179:     sub is_LC_dns {
16180:         &load_hosts_tab() if (!$loaded);
16181: 
16182:         my ($hostname) = @_;
16183:         return exists($LC_dns_serv{$hostname});
16184:     }
16185: 
16186: }
16187: 
16188: { 
16189:     my %iphost;
16190:     my %name_to_ip;
16191:     my %lonid_to_ip;
16192: 
16193:     sub get_hosts_from_ip {
16194: 	my ($ip) = @_;
16195: 	my %iphosts = &get_iphost();
16196: 	if (ref($iphosts{$ip})) {
16197: 	    return @{$iphosts{$ip}};
16198: 	}
16199: 	return;
16200:     }
16201:     
16202:     sub reset_hosts_ip_info {
16203: 	undef(%iphost);
16204: 	undef(%name_to_ip);
16205: 	undef(%lonid_to_ip);
16206:     }
16207: 
16208:     sub get_host_ip {
16209: 	my ($lonid) = @_;
16210: 	if (exists($lonid_to_ip{$lonid})) {
16211: 	    return $lonid_to_ip{$lonid};
16212: 	}
16213: 	my $name=&hostname($lonid);
16214:    	my $ip = gethostbyname($name);
16215: 	return if (!$ip || length($ip) ne 4);
16216: 	$ip=inet_ntoa($ip);
16217: 	$name_to_ip{$name}   = $ip;
16218: 	$lonid_to_ip{$lonid} = $ip;
16219: 	return $ip;
16220:     }
16221:     
16222:     sub get_iphost {
16223: 	my ($ignore_cache,$nocache) = @_;
16224: 
16225: 	if (!$ignore_cache) {
16226: 	    if (%iphost) {
16227: 		return %iphost;
16228: 	    }
16229: 	    my ($ip_info,$cached)=
16230: 		&is_cached_new('iphost','iphost');
16231: 	    if ($cached) {
16232: 		%iphost      = %{$ip_info->[0]};
16233: 		%name_to_ip  = %{$ip_info->[1]};
16234: 		%lonid_to_ip = %{$ip_info->[2]};
16235: 		return %iphost;
16236: 	    }
16237: 	}
16238: 
16239: 	# get yesterday's info for fallback
16240: 	my %old_name_to_ip;
16241: 	my ($ip_info,$cached)=
16242: 	    &is_cached_new('iphost','iphost');
16243: 	if ($cached) {
16244: 	    %old_name_to_ip = %{$ip_info->[1]};
16245: 	}
16246: 
16247: 	my %name_to_host = &all_names($ignore_cache,$nocache);
16248: 	foreach my $name (keys(%name_to_host)) {
16249: 	    my $ip;
16250: 	    if (!exists($name_to_ip{$name})) {
16251: 		$ip = gethostbyname($name);
16252: 		if (!$ip || length($ip) ne 4) {
16253: 		    if (defined($old_name_to_ip{$name})) {
16254: 			$ip = $old_name_to_ip{$name};
16255: 			&logthis("Can't find $name defaulting to old $ip");
16256: 		    } else {
16257: 			&logthis("Name $name no IP found");
16258: 			next;
16259: 		    }
16260: 		} else {
16261: 		    $ip=inet_ntoa($ip);
16262: 		}
16263: 		$name_to_ip{$name} = $ip;
16264: 	    } else {
16265: 		$ip = $name_to_ip{$name};
16266: 	    }
16267: 	    foreach my $id (@{ $name_to_host{$name} }) {
16268: 		$lonid_to_ip{$id} = $ip;
16269: 	    }
16270: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
16271: 	}
16272:         unless ($nocache) {
16273: 	    &do_cache_new('iphost','iphost',
16274: 		          [\%iphost,\%name_to_ip,\%lonid_to_ip],
16275: 		          48*60*60);
16276:         }
16277: 
16278: 	return %iphost;
16279:     }
16280: 
16281:     #
16282:     #  Given a DNS returns the loncapa host name for that DNS 
16283:     # 
16284:     sub host_from_dns {
16285:         my ($dns) = @_;
16286:         my @hosts;
16287:         my $ip;
16288: 
16289:         if (exists($name_to_ip{$dns})) {
16290:             $ip = $name_to_ip{$dns};
16291:         }
16292:         if (!$ip) {
16293:             $ip = gethostbyname($dns); # Initial translation to IP is in net order.
16294:             if (length($ip) == 4) { 
16295: 	        $ip   = &IO::Socket::inet_ntoa($ip);
16296:             }
16297:         }
16298:         if ($ip) {
16299: 	    @hosts = get_hosts_from_ip($ip);
16300: 	    return $hosts[0];
16301:         }
16302:         return undef;
16303:     }
16304: 
16305:     sub get_internet_names {
16306:         my ($lonid) = @_;
16307:         return if ($lonid eq '');
16308:         my ($idnref,$cached)=
16309:             &is_cached_new('internetnames',$lonid);
16310:         if ($cached) {
16311:             return $idnref;
16312:         }
16313:         my $ip = &get_host_ip($lonid);
16314:         my @hosts = &get_hosts_from_ip($ip);
16315:         my %iphost = &get_iphost();
16316:         my (@idns,%seen);
16317:         foreach my $id (@hosts) {
16318:             my $dom = &host_domain($id);
16319:             my $prim_id = &domain($dom,'primary');
16320:             my $prim_ip = &get_host_ip($prim_id);
16321:             next if ($seen{$prim_ip});
16322:             if (ref($iphost{$prim_ip}) eq 'ARRAY') {
16323:                 foreach my $id (@{$iphost{$prim_ip}}) {
16324:                     my $intdom = &internet_dom($id);
16325:                     unless (grep(/^\Q$intdom\E$/,@idns)) {
16326:                         push(@idns,$intdom);
16327:                     }
16328:                 }
16329:             }
16330:             $seen{$prim_ip} = 1;
16331:         }
16332:         return &do_cache_new('internetnames',$lonid,\@idns,12*60*60);
16333:     }
16334: 
16335: }
16336: 
16337: sub all_loncaparevs {
16338:     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);
16339: }
16340: 
16341: # ---------------------------------------------------------- Read loncaparev table
16342: {
16343:     sub load_loncaparevs { 
16344:         if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
16345:             if (open(my $config,"<","$perlvar{'lonTabDir'}/loncaparevs.tab")) {
16346:                 while (my $configline=<$config>) {
16347:                     chomp($configline);
16348:                     my ($hostid,$loncaparev)=split(/:/,$configline);
16349:                     $loncaparevs{$hostid}=$loncaparev;
16350:                 }
16351:                 close($config);
16352:             }
16353:         }
16354:     }
16355: }
16356: 
16357: # ---------------------------------------------------------- Read serverhostID table
16358: {
16359:     sub load_serverhomeIDs {
16360:         if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
16361:             if (open(my $config,"<","$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
16362:                 while (my $configline=<$config>) {
16363:                     chomp($configline);
16364:                     my ($name,$id)=split(/:/,$configline);
16365:                     $serverhomeIDs{$name}=$id;
16366:                 }
16367:                 close($config);
16368:             }
16369:         }
16370:     }
16371: }
16372: 
16373: 
16374: BEGIN {
16375: 
16376: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
16377:     unless ($readit) {
16378: {
16379:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
16380:     %perlvar = (%perlvar,%{$configvars});
16381: }
16382: 
16383: 
16384: # ------------------------------------------------------ Read spare server file
16385: {
16386:     open(my $config,"<","$perlvar{'lonTabDir'}/spare.tab");
16387: 
16388:     while (my $configline=<$config>) {
16389:        chomp($configline);
16390:        if ($configline) {
16391: 	   my ($host,$type) = split(':',$configline,2);
16392: 	   if (!defined($type) || $type eq '') { $type = 'default' };
16393: 	   push(@{ $spareid{$type} }, $host);
16394:        }
16395:     }
16396:     close($config);
16397: }
16398: # ------------------------------------------------------------ Read permissions
16399: {
16400:     open(my $config,"<","$perlvar{'lonTabDir'}/roles.tab");
16401: 
16402:     while (my $configline=<$config>) {
16403: 	chomp($configline);
16404: 	if ($configline) {
16405: 	    my ($role,$perm)=split(/ /,$configline);
16406: 	    if ($perm ne '') { $pr{$role}=$perm; }
16407: 	}
16408:     }
16409:     close($config);
16410: }
16411: 
16412: # -------------------------------------------- Read plain texts for permissions
16413: {
16414:     open(my $config,"<","$perlvar{'lonTabDir'}/rolesplain.tab");
16415: 
16416:     while (my $configline=<$config>) {
16417: 	chomp($configline);
16418: 	if ($configline) {
16419: 	    my ($short,@plain)=split(/:/,$configline);
16420:             %{$prp{$short}} = ();
16421: 	    if (@plain > 0) {
16422:                 $prp{$short}{'std'} = $plain[0];
16423:                 for (my $i=1; $i<@plain; $i++) {
16424:                     $prp{$short}{'alt'.$i} = $plain[$i];  
16425:                 }
16426:             }
16427: 	}
16428:     }
16429:     close($config);
16430: }
16431: 
16432: # ---------------------------------------------------------- Read package table
16433: {
16434:     open(my $config,"<","$perlvar{'lonTabDir'}/packages.tab");
16435: 
16436:     while (my $configline=<$config>) {
16437: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
16438: 	chomp($configline);
16439: 	my ($short,$plain)=split(/:/,$configline);
16440: 	my ($pack,$name)=split(/\&/,$short);
16441: 	if ($plain ne '') {
16442: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
16443: 	    $packagetab{$short}=$plain; 
16444: 	}
16445:     }
16446:     close($config);
16447: }
16448: 
16449: # ---------------------------------------------------------- Read loncaparev table
16450: 
16451: &load_loncaparevs();
16452: 
16453: # ---------------------------------------------------------- Read serverhostID table
16454: 
16455: &load_serverhomeIDs();
16456: 
16457: # ---------------------------------------------------------- Read releaseslist XML
16458: {
16459:     my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
16460:     if (-e $file) {
16461:         my $parser = HTML::LCParser->new($file);
16462:         while (my $token = $parser->get_token()) {
16463:             if ($token->[0] eq 'S') {
16464:                 my $item = $token->[1];
16465:                 my $name = $token->[2]{'name'};
16466:                 my $value = $token->[2]{'value'};
16467:                 my $valuematch = $token->[2]{'valuematch'};
16468:                 my $namematch = $token->[2]{'namematch'};
16469:                 if ($item eq 'parameter') {
16470:                     if (($namematch ne '') || (($name ne '') && ($value ne '' || $valuematch ne ''))) {
16471:                         my $release = $parser->get_text();
16472:                         $release =~ s/(^\s*|\s*$ )//gx;
16473:                         $needsrelease{$item.':'.$name.':'.$value.':'.$valuematch.':'.$namematch} = $release;
16474:                     }
16475:                 } elsif ($item ne '' && $name ne '') {
16476:                     my $release = $parser->get_text();
16477:                     $release =~ s/(^\s*|\s*$ )//gx;
16478:                     $needsrelease{$item.':'.$name.':'.$value} = $release;
16479:                 }
16480:             }
16481:         }
16482:     }
16483: }
16484: 
16485: # ---------------------------------------------------------- Read managers table
16486: {
16487:     if (-e "$perlvar{'lonTabDir'}/managers.tab") {
16488:         if (open(my $config,"<","$perlvar{'lonTabDir'}/managers.tab")) {
16489:             while (my $configline=<$config>) {
16490:                 chomp($configline);
16491:                 next if ($configline =~ /^\#/);
16492:                 if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
16493:                     $managerstab{$configline} = 1;
16494:                 }
16495:             }
16496:             close($config);
16497:         }
16498:     }
16499: }
16500: 
16501: # ------------- set up temporary directory
16502: {
16503:     $tmpdir = LONCAPA::tempdir();
16504: 
16505: }
16506: 
16507: # ------------- set default texengine (domain default overrides this)
16508: {
16509:     $deftex = LONCAPA::texengine();
16510: }
16511: 
16512: # ------------- set default minimum length for passwords for internal auth users
16513: {
16514:     $passwdmin = LONCAPA::passwd_min();
16515: }
16516: 
16517: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
16518: 				'compress_threshold'=> 20_000,
16519:  			        });
16520: 
16521: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
16522: $dumpcount=0;
16523: $locknum=0;
16524: 
16525: &logtouch();
16526: &logthis('<font color="yellow">INFO: Read configuration</font>');
16527: $readit=1;
16528:     {
16529: 	use integer;
16530: 	my $test=(2**32)+1;
16531: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
16532: 	&logthis(" Detected 64bit platform ($_64bit)");
16533:     }
16534: }
16535: }
16536: 
16537: 1;
16538: __END__
16539: 
16540: =pod
16541: 
16542: =head1 NAME
16543: 
16544: Apache::lonnet - Subroutines to ask questions about things in the network.
16545: 
16546: =head1 SYNOPSIS
16547: 
16548: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
16549: 
16550:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
16551: 
16552: Common parameters:
16553: 
16554: =over 4
16555: 
16556: =item *
16557: 
16558: $uname : an internal username (if $cname expecting a course Id specifically)
16559: 
16560: =item *
16561: 
16562: $udom : a domain (if $cdom expecting a course's domain specifically)
16563: 
16564: =item *
16565: 
16566: $symb : a resource instance identifier
16567: 
16568: =item *
16569: 
16570: $namespace : the name of a .db file that contains the data needed or
16571: being set.
16572: 
16573: =back
16574: 
16575: =head1 OVERVIEW
16576: 
16577: lonnet provides subroutines which interact with the
16578: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
16579: about classes, users, and resources.
16580: 
16581: For many of these objects you can also use this to store data about
16582: them or modify them in various ways.
16583: 
16584: =head2 Symbs
16585: 
16586: To identify a specific instance of a resource, LON-CAPA uses symbols
16587: or "symbs"X<symb>. These identifiers are built from the URL of the
16588: map, the resource number of the resource in the map, and the URL of
16589: the resource itself. The latter is somewhat redundant, but might help
16590: if maps change.
16591: 
16592: An example is
16593: 
16594:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
16595: 
16596: The respective map entry is
16597: 
16598:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
16599:   title="Problem 2">
16600:  </resource>
16601: 
16602: Symbs are used by the random number generator, as well as to store and
16603: restore data specific to a certain instance of for example a problem.
16604: 
16605: =head2 Storing And Retrieving Data
16606: 
16607: X<store()>X<cstore()>X<restore()>Three of the most important functions
16608: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
16609: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
16610: is is the non-critical message twin of cstore. These functions are for
16611: handlers to store a perl hash to a user's permanent data space in an
16612: easy manner, and to retrieve it again on another call. It is expected
16613: that a handler would use this once at the beginning to retrieve data,
16614: and then again once at the end to send only the new data back.
16615: 
16616: The data is stored in the user's data directory on the user's
16617: homeserver under the ID of the course.
16618: 
16619: The hash that is returned by restore will have all of the previous
16620: value for all of the elements of the hash.
16621: 
16622: Example:
16623: 
16624:  #creating a hash
16625:  my %hash;
16626:  $hash{'foo'}='bar';
16627: 
16628:  #storing it
16629:  &Apache::lonnet::cstore(\%hash);
16630: 
16631:  #changing a value
16632:  $hash{'foo'}='notbar';
16633: 
16634:  #adding a new value
16635:  $hash{'bar'}='foo';
16636:  &Apache::lonnet::cstore(\%hash);
16637: 
16638:  #retrieving the hash
16639:  my %history=&Apache::lonnet::restore();
16640: 
16641:  #print the hash
16642:  foreach my $key (sort(keys(%history))) {
16643:    print("\%history{$key} = $history{$key}");
16644:  }
16645: 
16646: Will print out:
16647: 
16648:  %history{1:foo} = bar
16649:  %history{1:keys} = foo:timestamp
16650:  %history{1:timestamp} = 990455579
16651:  %history{2:bar} = foo
16652:  %history{2:foo} = notbar
16653:  %history{2:keys} = foo:bar:timestamp
16654:  %history{2:timestamp} = 990455580
16655:  %history{bar} = foo
16656:  %history{foo} = notbar
16657:  %history{timestamp} = 990455580
16658:  %history{version} = 2
16659: 
16660: Note that the special hash entries C<keys>, C<version> and
16661: C<timestamp> were added to the hash. C<version> will be equal to the
16662: total number of versions of the data that have been stored. The
16663: C<timestamp> attribute will be the UNIX time the hash was
16664: stored. C<keys> is available in every historical section to list which
16665: keys were added or changed at a specific historical revision of a
16666: hash.
16667: 
16668: B<Warning>: do not store the hash that restore returns directly. This
16669: will cause a mess since it will restore the historical keys as if the
16670: were new keys. I.E. 1:foo will become 1:1:foo etc.
16671: 
16672: Calling convention:
16673: 
16674:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname);
16675:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$laststore);
16676: 
16677: For more detailed information, see lonnet specific documentation.
16678: 
16679: =head1 RETURN MESSAGES
16680: 
16681: =over 4
16682: 
16683: =item * B<con_lost>: unable to contact remote host
16684: 
16685: =item * B<con_delayed>: unable to contact remote host, message will be delivered
16686: when the connection is brought back up
16687: 
16688: =item * B<con_failed>: unable to contact remote host and unable to save message
16689: for later delivery
16690: 
16691: =item * B<error:>: an error a occurred, a description of the error follows the :
16692: 
16693: =item * B<no_such_host>: unable to fund a host associated with the user/domain
16694: that was requested
16695: 
16696: =back
16697: 
16698: =head1 PUBLIC SUBROUTINES
16699: 
16700: =head2 Session Environment Functions
16701: 
16702: =over 4
16703: 
16704: =item * 
16705: X<appenv()>
16706: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
16707: the user envirnoment file, and will be restored for each access this
16708: user makes during this session, also modifies the %env for the current
16709: process. Optional rolesarrayref - if defined contains a reference to an array
16710: of roles which are exempt from the restriction on modifying user.role entries 
16711: in the user's environment.db and in %env.    
16712: 
16713: =item *
16714: X<delenv()>
16715: B<delenv($delthis,$regexp)>: removes all items from the session
16716: environment file that begin with $delthis. If the 
16717: optional second arg - $regexp - is true, $delthis is treated as a 
16718: regular expression, otherwise \Q$delthis\E is used. 
16719: The values are also deleted from the current processes %env.
16720: 
16721: =item * get_env_multiple($name) 
16722: 
16723: gets $name from the %env hash, it seemlessly handles the cases where multiple
16724: values may be defined and end up as an array ref.
16725: 
16726: returns an array of values
16727: 
16728: =back
16729: 
16730: =head2 User Information
16731: 
16732: =over 4
16733: 
16734: =item *
16735: X<queryauthenticate()>
16736: B<queryauthenticate($uname,$udom)>: try to determine user's current 
16737: authentication scheme
16738: 
16739: =item *
16740: X<authenticate()>
16741: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
16742: authenticate user from domain's lib servers (first use the current
16743: one). C<$upass> should be the users password.
16744: $checkdefauth is optional (value is 1 if a check should be made to
16745:    authenticate user using default authentication method, and allow
16746:    account creation if username does not have account in the domain).
16747: $clientcancheckhost is optional (value is 1 if checking whether the
16748:    server can host will occur on the client side in lonauth.pm).   
16749: 
16750: =item *
16751: X<homeserver()>
16752: B<homeserver($uname,$udom)>: find the server which has
16753: the user's directory and files (there must be only one), this caches
16754: the answer, and also caches if there is a borken connection.
16755: 
16756: =item *
16757: X<idget()>
16758: B<idget($udom,$idsref,$namespace)>: find the usernames behind either 
16759: a list of student/employee IDs or clicker IDs
16760: (student/employee IDs are a unique resource in a domain, there must be 
16761: only 1 ID per username, and only 1 username per ID in a specific domain).
16762: clickerIDs are not necessarily unique, as students might share clickers.
16763: (returns hash: id=>name,id=>name)
16764: 
16765: =item *
16766: X<idrget()>
16767: B<idrget($udom,@unames)>: find the IDs behind a list of
16768: usernames (returns hash: name=>id,name=>id)
16769: 
16770: =item *
16771: X<idput()>
16772: B<idput($udom,$idsref,$uhome,$namespace)>: store away a list of 
16773: names and associated student/employee IDs or clicker IDs.
16774: 
16775: =item *
16776: X<iddel()>
16777: B<iddel($udom,$idshashref,$uhome,$namespace)>: delete unwanted 
16778: student/employee ID or clicker ID username look-ups from domain.
16779: The homeserver ($uhome) and namespace ($namespace) are optional.
16780: If no $uhome is provided, it will be determined usig &homeserver()
16781: for each user.  If no $namespace is provided, the default is ids.
16782: 
16783: =item *
16784: X<updateclickers()>
16785: B<updateclickers($udom,$action,$idshashref,$uhome,$critical)>: update 
16786: clicker ID-to-username look-ups in clickers.db on library server.
16787: Permitted actions are add or del (i.e., add or delete). The 
16788: clickers.db contains clickerID as keys (escaped), and each corresponding
16789: value is an escaped comma-separated list of usernames (for whom the
16790: library server is the homeserver), who registered that particular ID.
16791: If $critical is true, the update will be sent via &critical, otherwise
16792: &reply() will be used.
16793: 
16794: =item *
16795: X<rolesinit()>
16796: B<rolesinit($udom,$username)>: get user privileges.
16797: returns user role, first access and timer interval hashes
16798: 
16799: =item *
16800: X<privileged()>
16801: B<privileged($username,$domain)>: returns a true if user has a
16802: privileged and active role (i.e. su or dc), false otherwise.
16803: 
16804: =item *
16805: X<getsection()>
16806: B<getsection($udom,$uname,$cname)>: finds the section of student in the
16807: course $cname, return section name/number or '' for "not in course"
16808: and '-1' for "no section"
16809: 
16810: =item *
16811: X<userenvironment()>
16812: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
16813: passed in @what from the requested user's environment, returns a hash
16814: 
16815: =item * 
16816: X<userlog_query()>
16817: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
16818: activity.log file. %filters defines filters applied when parsing the
16819: log file. These can be start or end timestamps, or the type of action
16820: - log to look for Login or Logout events, check for Checkin or
16821: Checkout, role for role selection. The response is in the form
16822: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
16823: escaped strings of the action recorded in the activity.log file.
16824: 
16825: =back
16826: 
16827: =head2 User Roles
16828: 
16829: =over 4
16830: 
16831: =item *
16832: 
16833: allowed($priv,$uri,$symb,$role,$clientip,$noblockcheck) : check for a user privilege; 
16834: returns codes for allowed actions.
16835: 
16836: The first argument is required, all others are optional.
16837: 
16838: $priv is the privilege being checked.
16839: $uri contains additional information about what is being checked for access (e.g.,
16840: URL, course ID etc.). 
16841: $symb is the unique resource instance identifier in a course; if needed,
16842: but not provided, it will be retrieved via a call to &symbread(). 
16843: $role is the role for which a priv is being checked (only used if priv is evb). 
16844: $clientip is the user's IP address (only used when checking for access to portfolio 
16845: files).
16846: $noblockcheck, if true, skips calls to &has_comm_blocking() for the bre priv. This 
16847: prevents recursive calls to &allowed.
16848: 
16849:  F: full access
16850:  U,I,K: authentication modes (cxx only)
16851:  '': forbidden
16852:  1: user needs to choose course
16853:  2: browse allowed
16854:  A: passphrase authentication needed
16855:  B: access temporarily blocked because of a blocking event in a course.
16856:  D: access blocked because access is required via session initiated via deep-link 
16857: 
16858: =item *
16859: 
16860: constructaccess($url,$setpriv) : check for access to construction space URL
16861: 
16862: See if the owner domain and name in the URL match those in the
16863: expected environment.  If so, return three element list
16864: ($ownername,$ownerdomain,$ownerhome).
16865: 
16866: Otherwise return the null string.
16867: 
16868: If second argument 'setpriv' is true, it assigns the privileges,
16869: and returns the same three element list, unless the owner has
16870: blocked "ad hoc" Domain Coordinator access to the Author Space,
16871: in which case the null string is returned.
16872: 
16873: =item *
16874: 
16875: definerole($rolename,$sysrole,$domrole,$courole,$uname,$udom) : define role;
16876: define a custom role rolename set privileges in format of lonTabs/roles.tab
16877: for system, domain, and course level. $uname and $udom are optional (current
16878: user's username and domain will be used when either of $uname or $udom are absent.
16879: 
16880: =item *
16881: 
16882: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
16883: (rolesplain.tab); plain text explanation of a user role term.
16884: $type is Course (default) or Community.
16885: If $forcedefault evaluates to true, text returned will be default 
16886: text for $type. Otherwise, if this is a course, the text returned 
16887: will be a custom name for the role (if defined in the course's 
16888: environment).  If no custom name is defined the default is returned.
16889:    
16890: =item *
16891: 
16892: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv) :
16893: All arguments are optional. Returns a hash of a roles, either for
16894: co-author/assistant author roles for a user's Construction Space
16895: (default), or if $context is 'userroles', roles for the user himself,
16896: In the hash, keys are set to colon-separated $uname,$udom,$role, and
16897: (optionally) if $withsec is true, a fourth colon-separated item - $section.
16898: For each key, value is set to colon-separated start and end times for
16899: the role.  If no username and domain are specified, will default to
16900: current user/domain. Types, roles, and roledoms are references to arrays
16901: of role statuses (active, future or previous), roles 
16902: (e.g., cc,in, st etc.) and domains of the roles which can be used
16903: to restrict the list of roles reported. If no array ref is 
16904: provided for types, will default to return only active roles.
16905: 
16906: =item *
16907: 
16908: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
16909: user: $uname:$udom has a role in the course: $cdom_$cnum. 
16910: 
16911: Additional optional arguments are: $type (if role checking is to be restricted 
16912: to certain user status types -- previous (expired roles), active (currently
16913: available roles) or future (roles available in the future), and
16914: $hideprivileged -- if true will not report course roles for users who
16915: have active Domain Coordinator role in course's domain or in additional
16916: domains (specified in 'Domains to check for privileged users' in course
16917: environment -- set via:  Course Settings -> Classlists and staff listing).
16918: 
16919: =item *
16920: 
16921: privileged($username,$domain,$possdomains,$possroles) : returns 1 if user
16922: $username:$domain is a privileged user (e.g., Domain Coordinator or Super User)
16923: $possdomains and $possroles are optional array refs -- to domains to check and
16924: roles to check.  If $possdomains is not specified, a dump will be done of the
16925: users' roles.db to check for a dc or su role in any domain. This can be
16926: time consuming if &privileged is called repeatedly (e.g., when displaying a
16927: classlist), so in such cases, supplying a $possdomains array is preferred, as
16928: this then allows &privileged_by_domain() to be used, which caches the identity
16929: of privileged users, eliminating the need for repeated calls to &dump().
16930: 
16931: =item *
16932: 
16933: privileged_by_domain($possdomains,$roles) : returns a hash of a hash of a hash,
16934: where the outer hash keys are domains specified in the $possdomains array ref,
16935: next inner hash keys are privileged roles specified in the $roles array ref,
16936: and the innermost hash contains key = value pairs for username:domain = end:start
16937: for active or future "privileged" users with that role in that domain. To avoid
16938: repeated dumps of domain roles -- via &get_domain_roles() -- contents of the
16939: innerhash are cached using priv_$role and $dom as the identifiers.
16940: 
16941: =back
16942: 
16943: =head2 User Modification
16944: 
16945: =over 4
16946: 
16947: =item *
16948: 
16949: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
16950: user for the level given by URL.  Optional start and end dates (leave empty
16951: string or zero for "no date")
16952: 
16953: =item *
16954: 
16955: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
16956: change a users, password, possible return values are: ok,
16957: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
16958: refused
16959: 
16960: =item *
16961: 
16962: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
16963: 
16964: =item *
16965: 
16966: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
16967:            $forceid,$desiredhome,$email,$inststatus,$candelete) :
16968: 
16969: will update user information (firstname,middlename,lastname,generation,
16970: permanentemail), and if forceid is true, student/employee ID also.
16971: A user's institutional affiliation(s) can also be updated.
16972: User information fields will not be overwritten with empty entries 
16973: unless the field is included in the $candelete array reference.
16974: This array is included when a single user is modified via "Manage Users",
16975: or when Autoupdate.pl is run by cron in a domain.
16976: 
16977: =item *
16978: 
16979: modifystudent
16980: 
16981: modify a student's enrollment and identification information.
16982: The course id is resolved based on the current user's environment.  
16983: This means the invoking user must be a course coordinator or otherwise
16984: associated with a course.
16985: 
16986: This call is essentially a wrapper for lonnet::modifyuser and
16987: lonnet::modify_student_enrollment
16988: 
16989: Inputs: 
16990: 
16991: =over 4
16992: 
16993: =item B<$udom> Student's loncapa domain
16994: 
16995: =item B<$uname> Student's loncapa login name
16996: 
16997: =item B<$uid> Student/Employee ID
16998: 
16999: =item B<$umode> Student's authentication mode
17000: 
17001: =item B<$upass> Student's password
17002: 
17003: =item B<$first> Student's first name
17004: 
17005: =item B<$middle> Student's middle name
17006: 
17007: =item B<$last> Student's last name
17008: 
17009: =item B<$gene> Student's generation
17010: 
17011: =item B<$usec> Student's section in course
17012: 
17013: =item B<$end> Unix time of the roles expiration
17014: 
17015: =item B<$start> Unix time of the roles start date
17016: 
17017: =item B<$forceid> If defined, allow $uid to be changed
17018: 
17019: =item B<$desiredhome> server to use as home server for student
17020: 
17021: =item B<$email> Student's permanent e-mail address
17022: 
17023: =item B<$type> Type of enrollment (auto or manual)
17024: 
17025: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
17026: 
17027: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
17028: 
17029: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
17030: 
17031: =item B<$context> role change context (shown in User Management Logs display in a course)
17032: 
17033: =item B<$inststatus> institutional status of user - : separated string of escaped status types
17034: 
17035: =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.
17036: 
17037: =back
17038: 
17039: =item *
17040: 
17041: modify_student_enrollment
17042: 
17043: Change a student's enrollment status in a class.  The environment variable
17044: 'role.request.course' must be defined for this function to proceed.
17045: 
17046: Inputs:
17047: 
17048: =over 4
17049: 
17050: =item $udom, student's domain
17051: 
17052: =item $uname, student's name
17053: 
17054: =item $uid, student's user id
17055: 
17056: =item $first, student's first name
17057: 
17058: =item $middle
17059: 
17060: =item $last
17061: 
17062: =item $gene
17063: 
17064: =item $usec
17065: 
17066: =item $end
17067: 
17068: =item $start
17069: 
17070: =item $type
17071: 
17072: =item $locktype
17073: 
17074: =item $cid
17075: 
17076: =item $selfenroll
17077: 
17078: =item $context
17079: 
17080: =item $credits, number of credits student will earn from this class
17081: 
17082: =item $instsec, institutional course section code for student
17083: 
17084: =back
17085: 
17086: 
17087: =item *
17088: 
17089: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
17090: custom role; give a custom role to a user for the level given by URL.  Specify
17091: name and domain of role author, and role name
17092: 
17093: =item *
17094: 
17095: revokerole($udom,$uname,$url,$role) : revoke a role for url
17096: 
17097: =item *
17098: 
17099: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
17100: 
17101: =back
17102: 
17103: =head2 Course Infomation
17104: 
17105: =over 4
17106: 
17107: =item *
17108: 
17109: coursedescription($courseid,$options) : returns a hash of information about the
17110: specified course id, including all environment settings for the
17111: course, the description of the course will be in the hash under the
17112: key 'description'
17113: 
17114: $options is an optional parameter that if supplied is a hash reference that controls
17115: what how this function works.  It has the following key/values:
17116: 
17117: =over 4
17118: 
17119: =item freshen_cache
17120: 
17121: If defined, and the environment cache for the course is valid, it is 
17122: returned in the returned hash.
17123: 
17124: =item one_time
17125: 
17126: If defined, the last cache time is set to _now_
17127: 
17128: =item user
17129: 
17130: If defined, the supplied username is used instead of the current user.
17131: 
17132: 
17133: =back
17134: 
17135: =item *
17136: 
17137: resdata($name,$domain,$type,@which) : request for current parameter
17138: setting for a specific $type, where $type is either 'course' or 'user',
17139: @what should be a list of parameters to ask about. This routine caches
17140: answers for 10 minutes.
17141: 
17142: =item *
17143: 
17144: get_courseresdata($courseid, $domain) : dump the entire course resource
17145: data base, returning a hash that is keyed by the resource name and has
17146: values that are the resource value.  I believe that the timestamps and
17147: versions are also returned.
17148: 
17149: =back
17150: 
17151: =head2 Course Modification
17152: 
17153: =over 4
17154: 
17155: =item *
17156: 
17157: writecoursepref($courseid,%prefs) : write preferences (environment
17158: database) for a course
17159: 
17160: =item *
17161: 
17162: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
17163: 
17164: =item *
17165: 
17166: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
17167: 
17168: =item *
17169: 
17170: is_course($courseid), is_course($cdom, $cnum)
17171: 
17172: Accepts either a combined $courseid (in the form of domain_courseid) or the
17173: two component version $cdom, $cnum. It checks if the specified course exists.
17174: 
17175: Returns:
17176:     undef if the course doesn't exist, otherwise
17177:     in scalar context the combined courseid.
17178:     in list context the two components of the course identifier, domain and 
17179:     courseid.    
17180: 
17181: =back
17182: 
17183: =head2 Bubblesheet Configuration
17184: 
17185: =over 4
17186: 
17187: =item *
17188: 
17189: get_scantron_config($which)
17190: 
17191: $which - the name of the configuration to parse from the file.
17192: 
17193: Parses and returns the bubblesheet configuration line selected as a
17194: hash of configuration file fields.
17195: 
17196: 
17197: Returns:
17198:     If the named configuration is not in the file, an empty
17199:     hash is returned.
17200: 
17201:     a hash with the fields
17202:       name         - internal name for the this configuration setup
17203:       description  - text to display to operator that describes this config
17204:       CODElocation - if 0 or the string 'none'
17205:                           - no CODE exists for this config
17206:                      if -1 || the string 'letter'
17207:                           - a CODE exists for this config and is
17208:                             a string of letters
17209:                      Unsupported value (but planned for future support)
17210:                           if a positive integer
17211:                                - The CODE exists as the first n items from
17212:                                  the question section of the form
17213:                           if the string 'number'
17214:                                - The CODE exists for this config and is
17215:                                  a string of numbers
17216:       CODEstart   - (only matter if a CODE exists) column in the line where
17217:                      the CODE starts
17218:       CODElength  - length of the CODE
17219:       IDstart     - column where the student/employee ID starts
17220:       IDlength    - length of the student/employee ID info
17221:       Qstart      - column where the information from the bubbled
17222:                     'questions' start
17223:       Qlength     - number of columns comprising a single bubble line from
17224:                     the sheet. (usually either 1 or 10)
17225:       Qon         - either a single character representing the character used
17226:                     to signal a bubble was chosen in the positional setup, or
17227:                     the string 'letter' if the letter of the chosen bubble is
17228:                     in the final, or 'number' if a number representing the
17229:                     chosen bubble is in the file (1->A 0->J)
17230:       Qoff        - the character used to represent that a bubble was
17231:                     left blank
17232:       PaperID     - if the scanning process generates a unique number for each
17233:                     sheet scanned the column that this ID number starts in
17234:       PaperIDlength - number of columns that comprise the unique ID number
17235:                       for the sheet of paper
17236:       FirstName   - column that the first name starts in
17237:       FirstNameLength - number of columns that the first name spans
17238:       LastName    - column that the last name starts in
17239:       LastNameLength - number of columns that the last name spans
17240:       BubblesPerRow - number of bubbles available in each row used to
17241:                       bubble an answer. (If not specified, 10 assumed).
17242: 
17243: 
17244: =item *
17245: 
17246: get_scantronformat_file($cdom)
17247: 
17248: $cdom - the course's domain (optional); if not supplied, uses
17249: domain for current $env{'request.course.id'}.
17250: 
17251: Returns an array containing lines from the scantron format file for
17252: the domain of the course.
17253: 
17254: If a url for a custom.tab file is listed in domain's configuration.db,
17255: lines are from this file.
17256: 
17257: Otherwise, if a default.tab has been published in RES space by the
17258: domainconfig user, lines are from this file.
17259: 
17260: Otherwise, fall back to getting lines from the legacy file on the
17261: local server:  /home/httpd/lonTabs/default_scantronformat.tab
17262: 
17263: =back
17264: 
17265: =head2 Resource Subroutines
17266: 
17267: =over 4
17268: 
17269: =item *
17270: 
17271: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
17272: 
17273: =item *
17274: 
17275: repcopy($filename) : subscribes to the requested file, and attempts to
17276: replicate from the owning library server, Might return
17277: 'unavailable', 'not_found', 'forbidden', 'ok', or
17278: 'bad_request', also attempts to grab the metadata for the
17279: resource. Expects the local filesystem pathname
17280: (/home/httpd/html/res/....)
17281: 
17282: =back
17283: 
17284: =head2 Resource Information
17285: 
17286: =over 4
17287: 
17288: =item *
17289: 
17290: EXT($varname,$symb,$udom,$uname,$usection,$recurse,$cid) : evaluates 
17291: and returns the value of a variety of different possible values,
17292: $varname should be a request string, and the other parameters can be
17293: used to specify who and what one is asking about. Ordinarily, $cid 
17294: does not need to be specified, as it is retrived from 
17295: $env{'request.course.id'}, but &Apache::lonnet::EXT() is called
17296: within lonuserstate::loadmap() when initializing a course, before
17297: $env{'request.course.id'} has been set, so it needs to be provided
17298: in that one case.
17299: 
17300: Possible values for $varname are environment.lastname (or other item
17301: from the envirnment hash), user.name (or someother aspect about the
17302: user), resource.0.maxtries (or some other part and parameter of a
17303: resource)
17304: 
17305: =item *
17306: 
17307: directcondval($number) : get current value of a condition; reads from a state
17308: string
17309: 
17310: =item *
17311: 
17312: condval($condidx) : value of condition index based on state
17313: 
17314: =item *
17315: 
17316: metadata($uri,$what,$toolsymb,$liburi,$prefix,$depthcount) : request a
17317: resource's metadata, $what should be either a specific key, or either
17318: 'keys' (to get a list of possible keys) or 'packages' to get a list of
17319: packages that this resource currently uses, the last 3 arguments are 
17320: only used internally for recursive metadata.
17321: 
17322: the toolsymb is only used where the uri is for an external tool (for which
17323: the uri as well as the symb are guaranteed to be unique).
17324: 
17325: this function automatically caches all requests except any made recursively
17326: to retrieve a list of metadata keys for an imported library file ($liburi is 
17327: defined).
17328: 
17329: =item *
17330: 
17331: metadata_query($query,$custom,$customshow) : make a metadata query against the
17332: network of library servers; returns file handle of where SQL and regex results
17333: will be stored for query
17334: 
17335: =item *
17336: 
17337: symbread($filename,$donotrecurse,$ignorecachednull,$checkforblock,$possibles) : 
17338: return symbolic list entry (all arguments optional). 
17339: 
17340: Args: filename is the filename (including path) for the file for which a symb 
17341: is required; donotrecurse, if true will prevent calls to allowed() being made 
17342: to check access status if more than one resource was found in the bighash 
17343: (see rev. 1.249) to avoid an infinite loop if an ambiguous resource is part of 
17344: a randompick); ignorecachednull, if true will prevent a symb of '' being 
17345: returned if $env{$cache_str} is defined as ''; checkforblock if true will
17346: cause possible symbs to be checked to determine if they are subject to content
17347: blocking, if so they will not be included as possible symbs; possibles is a
17348: ref to a hash, which, as a side effect, will be populated with all possible 
17349: symbs (content blocking not tested).
17350:  
17351: returns the data handle
17352: 
17353: =item *
17354: 
17355: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
17356: and is a possible symb for the URL in $thisfn, and if is an encrypted
17357: resource that the user accessed using /enc/ returns a 1 on success, 0
17358: on failure, user must be in a course, as it assumes the existence of
17359: the course initial hash, and uses $env('request.course.id'}.  The third
17360: arg is an optional reference to a scalar.  If this arg is passed in the 
17361: call to symbverify, it will be set to 1 if the symb has been set to be 
17362: encrypted; otherwise it will be null.  
17363: 
17364: =item *
17365: 
17366: symbclean($symb) : removes versions numbers from a symb, returns the
17367: cleaned symb
17368: 
17369: =item *
17370: 
17371: is_on_map($uri) : checks if the $uri is somewhere on the current
17372: course map, user must be in a course for it to work.
17373: 
17374: =item *
17375: 
17376: numval($salt) : return random seed value (addend for rndseed)
17377: 
17378: =item *
17379: 
17380: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
17381: a random seed, all arguments are optional, if they aren't sent it uses the
17382: environment to derive them. Note: if symb isn't sent and it can't get one
17383: from &symbread it will use the current time as its return value
17384: 
17385: =item *
17386: 
17387: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
17388: unfakeable, receipt
17389: 
17390: =item *
17391: 
17392: receipt() : API to ireceipt working off of env values; given out to users
17393: 
17394: =item *
17395: 
17396: countacc($url) : count the number of accesses to a given URL
17397: 
17398: =item *
17399: 
17400: 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
17401: 
17402: =item *
17403: 
17404: 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)
17405: 
17406: =item *
17407: 
17408: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
17409: 
17410: =item *
17411: 
17412: devalidate($symb) : devalidate temporary spreadsheet calculations,
17413: forcing spreadsheet to reevaluate the resource scores next time.
17414: 
17415: =item * 
17416: 
17417: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
17418: when viewing in course context.
17419: 
17420:  input: six args -- filename (decluttered), course number, course domain,
17421:                     url, symb (if registered) and group (if this is a 
17422:                     group item -- e.g., bulletin board, group page etc.).
17423: 
17424:  output: array of five scalars --
17425:          $cfile -- url for file editing if editable on current server
17426:          $home -- homeserver of resource (i.e., for author if published,
17427:                                           or course if uploaded.).
17428:          $switchserver --  1 if server switch will be needed.
17429:          $forceedit -- 1 if icon/link should be to go to edit mode 
17430:          $forceview -- 1 if icon/link should be to go to view mode
17431: 
17432: =item *
17433: 
17434: is_course_upload($file,$cnum,$cdom)
17435: 
17436: Used in course context to determine if current file was uploaded to 
17437: the course (i.e., would be found in /userfiles/docs on the course's 
17438: homeserver.
17439: 
17440:   input: 3 args -- filename (decluttered), course number and course domain.
17441:   output: boolean -- 1 if file was uploaded.
17442: 
17443: =back
17444: 
17445: =head2 Storing/Retreiving Data
17446: 
17447: =over 4
17448: 
17449: =item *
17450: 
17451: store($storehash,$symb,$namespace,$udom,$uname,$laststore) : stores hash
17452: permanently for this url; hashref needs to be given and should be a \%hashname;
17453: the remaining args aren't required and if they aren't passed or are '' they will
17454: be derived from the env (with the exception of $laststore, which is an 
17455: optional arg used when a user's submission is stored in grading).
17456: $laststore is $version=$timestamp, where $version is the most recent version
17457: number retrieved for the corresponding $symb in the $namespace db file, and
17458: $timestamp is the timestamp for that transaction (UNIX time).
17459: $laststore is currently only passed when cstore() is called by 
17460: structuretags::finalize_storage().
17461: 
17462: =item *
17463: 
17464: cstore($storehash,$symb,$namespace,$udom,$uname,$laststore) : same as store
17465: but uses critical subroutine
17466: 
17467: =item *
17468: 
17469: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
17470: all args are optional
17471: 
17472: =item *
17473: 
17474: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
17475: dumps the complete (or key matching regexp) namespace into a hash
17476: ($udom, $uname, $regexp, $range are optional) for a namespace that is
17477: normally &store()ed into
17478: 
17479: $range should be either an integer '100' (give me the first 100
17480:                                            matching records)
17481:               or be  two integers sperated by a - with no spaces
17482:                  '30-50' (give me the 30th through the 50th matching
17483:                           records)
17484: 
17485: 
17486: =item *
17487: 
17488: putstore($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog) :
17489: replaces a &store() version of data with a replacement set of data
17490: for a particular resource in a namespace passed in the $storehash hash 
17491: reference. If $tolog is true, the transaction is logged in the courselog
17492: with an action=PUTSTORE.
17493: 
17494: =item *
17495: 
17496: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
17497: works very similar to store/cstore, but all data is stored in a
17498: temporary location and can be reset using tmpreset, $storehash should
17499: be a hash reference, returns nothing on success
17500: 
17501: =item *
17502: 
17503: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
17504: similar to restore, but all data is stored in a temporary location and
17505: can be reset using tmpreset. Returns a hash of values on success,
17506: error string otherwise.
17507: 
17508: =item *
17509: 
17510: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
17511: deltes all keys for $symb form the temporary storage hash.
17512: 
17513: =item *
17514: 
17515: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
17516: reference filled in from namesp ($udom and $uname are optional)
17517: 
17518: =item *
17519: 
17520: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
17521: namesp ($udom and $uname are optional)
17522: 
17523: =item *
17524: 
17525: dump($namespace,$udom,$uname,$regexp,$range) : 
17526: dumps the complete (or key matching regexp) namespace into a hash
17527: ($udom, $uname, $regexp, $range are optional)
17528: 
17529: $range should be either an integer '100' (give me the first 100
17530:                                            matching records)
17531:               or be  two integers sperated by a - with no spaces
17532:                  '30-50' (give me the 30th through the 50th matching
17533:                           records)
17534: =item *
17535: 
17536: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
17537: $store can be a scalar, an array reference, or if the amount to be 
17538: incremented is > 1, a hash reference.
17539: 
17540: ($udom and $uname are optional)
17541: 
17542: =item *
17543: 
17544: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
17545: ($udom and $uname are optional)
17546: 
17547: =item *
17548: 
17549: cput($namespace,$storehash,$udom,$uname) : critical put
17550: ($udom and $uname are optional)
17551: 
17552: =item *
17553: 
17554: newput($namespace,$storehash,$udom,$uname) :
17555: 
17556: Attempts to store the items in the $storehash, but only if they don't
17557: currently exist, if this succeeds you can be certain that you have 
17558: successfully created a new key value pair in the $namespace db.
17559: 
17560: 
17561: Args:
17562:  $namespace: name of database to store values to
17563:  $storehash: hashref to store to the db
17564:  $udom: (optional) domain of user containing the db
17565:  $uname: (optional) name of user caontaining the db
17566: 
17567: Returns:
17568:  'ok' -> succeeded in storing all keys of $storehash
17569:  'key_exists: <key>' -> failed to anything out of $storehash, as at
17570:                         least <key> already existed in the db (other
17571:                         requested keys may also already exist)
17572:  'error: <msg>' -> unable to tie the DB or other error occurred
17573:  'con_lost' -> unable to contact request server
17574:  'refused' -> action was not allowed by remote machine
17575: 
17576: 
17577: =item *
17578: 
17579: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
17580: reference filled in from namesp (encrypts the return communication)
17581: ($udom and $uname are optional)
17582: 
17583: =item *
17584: 
17585: log($udom,$name,$home,$message) : write to permanent log for user; use
17586: critical subroutine
17587: 
17588: =item *
17589: 
17590: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
17591: array reference filled in from namespace found in domain level on either
17592: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
17593: 
17594: =item *
17595: 
17596: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
17597: domain level either on specified domain server ($uhome) or primary domain 
17598: server ($udom and $uhome are optional)
17599: 
17600: =item * 
17601: 
17602: get_domain_defaults($target_domain,$ignore_cache) : returns hash with defaults 
17603: for: authentication, language, quotas, timezone, date locale, and portal URL in
17604: the target domain.
17605: 
17606: May also include additional key => value pairs for the following groups:
17607: 
17608: =over
17609: 
17610: =item
17611: disk quotas (MB allocated by default to portfolios and authoring spaces).
17612: 
17613: =over
17614: 
17615: =item defaultquota, authorquota
17616: 
17617: =back
17618: 
17619: =item
17620: tools (availability of aboutme page, blog, webDAV access for authoring spaces,
17621: portfolio for users).
17622: 
17623: =over
17624: 
17625: =item
17626: aboutme, blog, webdav, portfolio
17627: 
17628: =back
17629: 
17630: =item
17631: requestcourses: ability to request courses, and how requests are processed.
17632: 
17633: =over
17634: 
17635: =item
17636: official, unofficial, community, textbook, placement
17637: 
17638: =back
17639: 
17640: =item
17641: inststatus: types of institutional affiliation, and order in which they are displayed.
17642: 
17643: =over
17644: 
17645: =item
17646: inststatustypes, inststatusorder, inststatusguest
17647: 
17648: =back
17649: 
17650: =item
17651: coursedefaults: can PDF forms can be created, default credits for courses, default quotas (MB)
17652: for course's uploaded content.
17653: 
17654: =over
17655: 
17656: =item
17657: canuse_pdfforms, officialcredits, unofficialcredits, textbookcredits, officialquota, unofficialquota, 
17658: communityquota, textbookquota, placementquota
17659: 
17660: =back
17661: 
17662: =item
17663: usersessions: set options for hosting of your users in other domains, and hosting of users from other domains
17664: on your servers.
17665: 
17666: =over
17667: 
17668: =item 
17669: remotesessions, hostedsessions
17670: 
17671: =back
17672: 
17673: =back
17674: 
17675: In cases where a domain coordinator has never used the "Set Domain Configuration"
17676: utility to create a configuration.db file on a domain's primary library server 
17677: only the following domain defaults: auth_def, auth_arg_def, lang_def
17678: -- corresponding values are authentication type (internal, krb4, krb5,
17679: or localauth), initial password or a kerberos realm, language (e.g., en-us) -- 
17680: will be available. Values are retrieved from cache (if current), unless the
17681: optional $ignore_cache arg is true, or from domain's configuration.db (if available),
17682: or lastly from values in lonTabs/dns_domain,tab, or lonTabs/domain.tab.
17683: 
17684: Typical usage:
17685: 
17686: %domdefaults = &get_domain_defaults($target_domain);
17687: 
17688: =back
17689: 
17690: =head2 Network Status Functions
17691: 
17692: =over 4
17693: 
17694: =item *
17695: 
17696: dirlist() : return directory list based on URI (first arg).
17697: 
17698: Inputs: 1 required, 5 optional.
17699: 
17700: =over
17701: 
17702: =item 
17703: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
17704: 
17705: =item
17706: $userdomain - domain of user/course to be listed. Extracted from $uri if absent. 
17707: 
17708: =item
17709: $username -  username of user/course to be listed. Extracted from $uri if absent. 
17710: 
17711: =item
17712: $getpropath - boolean: 1 if prepend path using &propath(). 
17713: 
17714: =item
17715: $getuserdir - boolean: 1 if prepend path for "userfiles".
17716: 
17717: =item 
17718: $alternateRoot - path to prepend in place of path from $uri.
17719: 
17720: =back
17721: 
17722: Returns: Array of up to two items.
17723: 
17724: =over
17725: 
17726: a reference to an array of files/subdirectories
17727: 
17728: =over
17729: 
17730: Each element in the array of files/subdirectories is a & separated list of
17731: item name and the result of running stat on the item.  If dirlist was requested
17732: for a file instead of a directory, the item name will be ''. For a directory 
17733: listing, if the item is a metadata file, the element will end &N&M 
17734: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
17735: default copyright set (1).  
17736: 
17737: =back
17738: 
17739: a scalar containing error condition (if encountered).
17740: 
17741: =over
17742: 
17743: =item 
17744: no_host (no homeserver identified for $username:$domain).
17745: 
17746: =item 
17747: no_such_host (server contacted for listing not identified as valid host).
17748: 
17749: =item 
17750: con_lost (connection to remote server failed).
17751: 
17752: =item 
17753: refused (invalid $username:$domain received on lond side).
17754: 
17755: =item 
17756: no_such_dir (directory at specified path on lond side does not exist). 
17757: 
17758: =item 
17759: empty (directory at specified path on lond side is empty).
17760: 
17761: =over
17762: 
17763: This is currently not encountered because the &ls3, &ls2, 
17764: &ls (_handler) routines on the lond side do not filter out
17765: . and .. from a directory listing. 
17766: 
17767: =back
17768: 
17769: =back
17770: 
17771: =back
17772: 
17773: =item *
17774: 
17775: spareserver() : find server with least workload from spare.tab
17776: 
17777: 
17778: =item *
17779: 
17780: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
17781: if there is no corresponding loncapa host.
17782: 
17783: =back
17784: 
17785: 
17786: =head2 Apache Request
17787: 
17788: =over 4
17789: 
17790: =item *
17791: 
17792: ssi($url,%hash) : server side include, does a complete request cycle on url to
17793: localhost, posts hash
17794: 
17795: =back
17796: 
17797: =head2 Data to String to Data
17798: 
17799: =over 4
17800: 
17801: =item *
17802: 
17803: hash2str(%hash) : convert a hash into a string complete with escaping and '='
17804: and '&' separators, supports elements that are arrayrefs and hashrefs
17805: 
17806: =item *
17807: 
17808: hashref2str($hashref) : convert a hashref into a string complete with
17809: escaping and '=' and '&' separators, supports elements that are
17810: arrayrefs and hashrefs
17811: 
17812: =item *
17813: 
17814: arrayref2str($arrayref) : convert an arrayref into a string complete
17815: with escaping and '&' separators, supports elements that are arrayrefs
17816: and hashrefs
17817: 
17818: =item *
17819: 
17820: str2hash($string) : convert string to hash using unescaping and
17821: splitting on '=' and '&', supports elements that are arrayrefs and
17822: hashrefs
17823: 
17824: =item *
17825: 
17826: str2array($string) : convert string to hash using unescaping and
17827: splitting on '&', supports elements that are arrayrefs and hashrefs
17828: 
17829: =back
17830: 
17831: =head2 Logging Routines
17832: 
17833: 
17834: These routines allow one to make log messages in the lonnet.log and
17835: lonnet.perm logfiles.
17836: 
17837: =over 4
17838: 
17839: =item *
17840: 
17841: logtouch() : make sure the logfile, lonnet.log, exists
17842: 
17843: =item *
17844: 
17845: logthis() : append message to the normal lonnet.log file, it gets
17846: preiodically rolled over and deleted.
17847: 
17848: =item *
17849: 
17850: logperm() : append a permanent message to lonnet.perm.log, this log
17851: file never gets deleted by any automated portion of the system, only
17852: messages of critical importance should go in here.
17853: 
17854: 
17855: =back
17856: 
17857: =head2 General File Helper Routines
17858: 
17859: =over 4
17860: 
17861: =item *
17862: 
17863: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
17864: (a) files in /uploaded
17865:   (i) If a local copy of the file exists - 
17866:       compares modification date of local copy with last-modified date for 
17867:       definitive version stored on home server for course. If local copy is 
17868:       stale, requests a new version from the home server and stores it. 
17869:       If the original has been removed from the home server, then local copy 
17870:       is unlinked.
17871:   (ii) If local copy does not exist -
17872:       requests the file from the home server and stores it. 
17873:   
17874:   If $caller is 'uploadrep':  
17875:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
17876:     for request for files originally uploaded via DOCS. 
17877:      - returns 'ok' if fresh local copy now available, -1 otherwise.
17878:   
17879:   Otherwise:
17880:      This indicates a call from the content generation phase of the request.
17881:      -  returns the entire contents of the file or -1.
17882:      
17883: (b) files in /res
17884:    - returns the entire contents of a file or -1; 
17885:    it properly subscribes to and replicates the file if neccessary.
17886: 
17887: 
17888: =item *
17889: 
17890: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
17891:                   reference
17892: 
17893: returns either a stat() list of data about the file or an empty list
17894: if the file doesn't exist or couldn't find out about it (connection
17895: problems or user unknown)
17896: 
17897: =item *
17898: 
17899: filelocation($dir,$file) : returns file system location of a file
17900: based on URI; meant to be "fairly clean" absolute reference, $dir is a
17901: directory that relative $file lookups are to looked in ($dir of /a/dir
17902: and a file of ../bob will become /a/bob)
17903: 
17904: =item *
17905: 
17906: hreflocation($dir,$file) : returns file system location or a URL; same as
17907: filelocation except for hrefs
17908: 
17909: =item *
17910: 
17911: declutter() : declutters URLs -- remove beginning slashes, 'res' etc.
17912: also removes beginning /home/httpd/html unless /priv/ follows it.
17913: 
17914: =back
17915: 
17916: =head2 Usererfile file routines (/uploaded*)
17917: 
17918: =over 4
17919: 
17920: =item *
17921: 
17922: userfileupload(): main rotine for putting a file in a user or course's
17923:                   filespace, arguments are,
17924: 
17925:  formname - required - this is the name of the element in $env where the
17926:            filename, and the contents of the file to create/modifed exist
17927:            the filename is in $env{'form.'.$formname.'.filename'} and the
17928:            contents of the file is located in $env{'form.'.$formname}
17929:  context - if coursedoc, store the file in the course of the active role
17930:              of the current user; 
17931:            if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
17932:            if 'canceloverwrite': delete file in tmp/overwrites directory
17933:  subdir - required - subdirectory to put the file in under ../userfiles/
17934:          if undefined, it will be placed in "unknown"
17935: 
17936:  (This routine calls clean_filename() to remove any dangerous
17937:  characters from the filename, and then calls finuserfileupload() to
17938:  complete the transaction)
17939: 
17940:  returns either the url of the uploaded file (/uploaded/....) if successful
17941:  and /adm/notfound.html if unsuccessful
17942: 
17943: =item *
17944: 
17945: clean_filename(): routine for cleaing a filename up for storage in
17946:                  userfile space, argument is:
17947: 
17948:  filename - proposed filename
17949: 
17950: returns: the new clean filename
17951: 
17952: =item *
17953: 
17954: finishuserfileupload(): routine that creates and sends the file to
17955: userspace, probably shouldn't be called directly
17956: 
17957:   docuname: username or courseid of destination for the file
17958:   docudom: domain of user/course of destination for the file
17959:   formname: same as for userfileupload()
17960:   fname: filename (including subdirectories) for the file
17961:   parser: if 'parse', will parse (html) file to extract references to objects, links etc.
17962:           if hashref, and context is scantron, will convert csv format to standard format
17963:   allfiles: reference to hash used to store objects found by parser
17964:   codebase: reference to hash used for codebases of java objects found by parser
17965:   thumbwidth: width (pixels) of thumbnail to be created for uploaded image
17966:   thumbheight: height (pixels) of thumbnail to be created for uploaded image
17967:   resizewidth: width to be used to resize image using resizeImage from ImageMagick
17968:   resizeheight: height to be used to resize image using resizeImage from ImageMagick
17969:   context: if 'overwrite', will move the uploaded file from its temporary location to
17970:             userfiles to facilitate overwriting a previously uploaded file with same name.
17971:   mimetype: reference to scalar to accommodate mime type determined
17972:             from File::MMagic if $parser = parse.
17973: 
17974:  returns either the url of the uploaded file (/uploaded/....) if successful
17975:  and /adm/notfound.html if unsuccessful (or an error message if context 
17976:  was 'overwrite').
17977:  
17978: 
17979: =item *
17980: 
17981: renameuserfile(): renames an existing userfile to a new name
17982: 
17983:   Args:
17984:    docuname: username or courseid of destination for the file
17985:    docudom: domain of user/course of destination for the file
17986:    old: current file name (including any subdirs under userfiles)
17987:    new: desired file name (including any subdirs under userfiles)
17988: 
17989: =item *
17990: 
17991: mkdiruserfile(): creates a directory is a userfiles dir
17992: 
17993:   Args:
17994:    docuname: username or courseid of destination for the file
17995:    docudom: domain of user/course of destination for the file
17996:    dir: dir to create (including any subdirs under userfiles)
17997: 
17998: =item *
17999: 
18000: removeuserfile(): removes a file that exists in userfiles
18001: 
18002:   Args:
18003:    docuname: username or courseid of destination for the file
18004:    docudom: domain of user/course of destination for the file
18005:    fname: filname to delete (including any subdirs under userfiles)
18006: 
18007: =item *
18008: 
18009: removeuploadedurl(): convience function for removeuserfile()
18010: 
18011:   Args:
18012:    url:  a full /uploaded/... url to delete
18013: 
18014: =item * 
18015: 
18016: get_portfile_permissions():
18017:   Args:
18018:     domain: domain of user or course contain the portfolio files
18019:     user: name of user or num of course contain the portfolio files
18020:   Returns:
18021:     hashref of a dump of the proper file_permissions.db
18022:    
18023: 
18024: =item * 
18025: 
18026: get_access_controls():
18027: 
18028: Args:
18029:   current_permissions: the hash ref returned from get_portfile_permissions()
18030:   group: (optional) the group you want the files associated with
18031:   file: (optional) the file you want access info on
18032: 
18033: Returns:
18034:     a hash (keys are file names) of hashes containing
18035:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
18036:         values are XML containing access control settings (see below) 
18037: 
18038: Internal notes:
18039: 
18040:  access controls are stored in file_permissions.db as key=value pairs.
18041:     key -> path to file/file_name\0uniqueID:scope_end_start
18042:         where scope -> public,guest,course,group,domains or users.
18043:               end -> UNIX time for end of access (0 -> no end date)
18044:               start -> UNIX time for start of access
18045: 
18046:     value -> XML description of access control
18047:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
18048:             <start></start>
18049:             <end></end>
18050: 
18051:             <password></password>  for scope type = guest
18052: 
18053:             <domain></domain>     for scope type = course or group
18054:             <number></number>
18055:             <roles id="">
18056:              <role></role>
18057:              <access></access>
18058:              <section></section>
18059:              <group></group>
18060:             </roles>
18061: 
18062:             <dom></dom>         for scope type = domains
18063: 
18064:             <users>             for scope type = users
18065:              <user>
18066:               <uname></uname>
18067:               <udom></udom>
18068:              </user>
18069:             </users>
18070:            </scope> 
18071:               
18072:  Access data is also aggregated for each file in an additional key=value pair:
18073:  key -> path to file/file_name\0accesscontrol 
18074:  value -> reference to hash
18075:           hash contains key = value pairs
18076:           where key = uniqueID:scope_end_start
18077:                 value = UNIX time record was last updated
18078: 
18079:           Used to improve speed of look-ups of access controls for each file.  
18080:  
18081:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
18082: 
18083: =item *
18084: 
18085: modify_access_controls():
18086: 
18087: Modifies access controls for a portfolio file
18088: Args
18089: 1. file name
18090: 2. reference to hash of required changes,
18091: 3. domain
18092: 4. username
18093:   where domain,username are the domain of the portfolio owner 
18094:   (either a user or a course) 
18095: 
18096: Returns:
18097: 1. result of additions or updates ('ok' or 'error', with error message). 
18098: 2. result of deletions ('ok' or 'error', with error message).
18099: 3. reference to hash of any new or updated access controls.
18100: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
18101:    key = integer (inbound ID)
18102:    value = uniqueID
18103: 
18104: =item *
18105: 
18106: get_timebased_id():
18107: 
18108: Attempts to get a unique timestamp-based suffix for use with items added to a 
18109: course via the Course Editor (e.g., folders, composite pages, 
18110: group bulletin boards).
18111: 
18112: Args: (first three required; six others optional)
18113: 
18114: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
18115:    docssequence, or name of group
18116: 
18117: 2. keyid (alphanumeric): name of temporary locking key in hash,
18118:    e.g., num, boardids
18119: 
18120: 3. namespace: name of gdbm file used to store suffixes already assigned;  
18121:    file will be named nohist_namespace.db
18122: 
18123: 4. cdom: domain of course; default is current course domain from %env
18124: 
18125: 5. cnum: course number; default is current course number from %env
18126: 
18127: 6. idtype: set to concat if an additional digit is to be appended to the 
18128:    unix timestamp to form the suffix, if the plain timestamp is already
18129:    in use.  Default is to not do this, but simply increment the unix 
18130:    timestamp by 1 until a unique key is obtained.
18131: 
18132: 7. who: holder of locking key; defaults to user:domain for user.
18133: 
18134: 8. locktries: number of attempts to obtain a lock (sleep of 1s before 
18135:    retrying); default is 3.
18136: 
18137: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.  
18138: 
18139: Returns:
18140: 
18141: 1. suffix obtained (numeric)
18142: 
18143: 2. result of deleting locking key (ok if deleted, or lock never obtained)
18144: 
18145: 3. error: contains (localized) error message if an error occurred.
18146: 
18147: 
18148: =back
18149: 
18150: =head2 HTTP Helper Routines
18151: 
18152: =over 4
18153: 
18154: =item *
18155: 
18156: escape() : unpack non-word characters into CGI-compatible hex codes
18157: 
18158: =item *
18159: 
18160: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
18161: 
18162: =back
18163: 
18164: =head1 PRIVATE SUBROUTINES
18165: 
18166: =head2 Underlying communication routines (Shouldn't call)
18167: 
18168: =over 4
18169: 
18170: =item *
18171: 
18172: subreply() : tries to pass a message to lonc, returns con_lost if incapable
18173: 
18174: =item *
18175: 
18176: reply() : uses subreply to send a message to remote machine, logs all failures
18177: 
18178: =item *
18179: 
18180: critical() : passes a critical message to another server; if cannot
18181: get through then place message in connection buffer directory and
18182: returns con_delayed, if incapable of saving message, returns
18183: con_failed
18184: 
18185: =item *
18186: 
18187: reconlonc() : tries to reconnect lonc client processes.
18188: 
18189: =back
18190: 
18191: =head2 Resource Access Logging
18192: 
18193: =over 4
18194: 
18195: =item *
18196: 
18197: flushcourselogs() : flush (save) buffer logs and access logs
18198: 
18199: =item *
18200: 
18201: courselog($what) : save message for course in hash
18202: 
18203: =item *
18204: 
18205: courseacclog($what) : save message for course using &courselog().  Perform
18206: special processing for specific resource types (problems, exams, quizzes, etc).
18207: 
18208: =item *
18209: 
18210: goodbye() : flush course logs and log shutting down; it is called in srm.conf
18211: as a PerlChildExitHandler
18212: 
18213: =back
18214: 
18215: =head2 Other
18216: 
18217: =over 4
18218: 
18219: =item *
18220: 
18221: symblist($mapname,%newhash) : update symbolic storage links
18222: 
18223: =back
18224: 
18225: =cut
18226: 

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