File:  [LON-CAPA] / loncom / lonnet / perl / lonnet.pm
Revision 1.1528: download - view: text, annotated - select for diffs
Fri Jun 14 18:49:42 2024 UTC (7 weeks, 6 days ago) by raeburn
Branches: MAIN
CVS tags: version_2_12_X, HEAD
- Changes from loncnew rev. 1.108 when creating a new connection between
  LON-CAPA nodes to (a) support verification of common name when creating
  SSL tunnel between 2.12 nodes, while (b) supporting continued queuing of
  any delayed transactions when reconnecting (both 2.12 and pre-2.12).

    1: # The LearningOnline Network
    2: # TCP networking package
    3: #
    4: # $Id: lonnet.pm,v 1.1528 2024/06/14 18:49:42 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:     if ($loncaparevs{$lonid} =~ /^(\d+\.\d+\.[\w.]+)-\d+$/) {
  192:         print $client (join(':',$hostname,$lonid,$1,&machine_ids($hostname))."\n");
  193:     } else {
  194:         print $client (join(':',$hostname,$lonid,&machine_ids($hostname))."\n");
  195:     }
  196:     my $result = <$client>;
  197:     chomp($result);
  198:     return 1 if ($result eq 'done');
  199:     return 0;
  200: }
  201: 
  202: sub get_server_timezone {
  203:     my ($cnum,$cdom) = @_;
  204:     my $home=&homeserver($cnum,$cdom);
  205:     if ($home ne 'no_host') {
  206:         my $cachetime = 24*3600;
  207:         my ($timezone,$cached)=&is_cached_new('servertimezone',$home);
  208:         if (defined($cached)) {
  209:             return $timezone;
  210:         } else {
  211:             my $timezone = &reply('servertimezone',$home);
  212:             return &do_cache_new('servertimezone',$home,$timezone,$cachetime);
  213:         }
  214:     }
  215: }
  216: 
  217: sub get_server_distarch {
  218:     my ($lonhost,$ignore_cache) = @_;
  219:     if (defined($lonhost)) {
  220:         if (!defined(&hostname($lonhost))) {
  221:             return;
  222:         }
  223:         my $cachetime = 12*3600;
  224:         if (!$ignore_cache) {
  225:             my ($distarch,$cached)=&is_cached_new('serverdistarch',$lonhost);
  226:             if (defined($cached)) {
  227:                 return $distarch;
  228:             }
  229:         }
  230:         my $rep = &reply('serverdistarch',$lonhost);
  231:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
  232:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
  233:                 $rep eq '') {
  234:             return &do_cache_new('serverdistarch',$lonhost,$rep,$cachetime);
  235:         }
  236:     }
  237:     return;
  238: }
  239: 
  240: sub get_servercerts_info {
  241:     my ($lonhost,$hostname,$context) = @_;
  242:     return if ($lonhost eq '');
  243:     if ($hostname eq '') {
  244:         $hostname = &hostname($lonhost);
  245:     }
  246:     return if ($hostname eq '');
  247:     my ($rep,$uselocal);
  248:     if ($context eq 'install') {
  249:         $uselocal = 1;
  250:     } elsif (grep { $_ eq $lonhost } &current_machine_ids()) {
  251:         $uselocal = 1;
  252:     }
  253:     if (($context ne 'cgi') && ($context ne 'install') && ($uselocal)) {
  254:         my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
  255:         if ($distro eq '') {
  256:             $uselocal = 0;
  257:         } elsif ($distro =~ /^(?:centos|redhat|scientific)(\d+)$/) {
  258:             if ($1 < 6) {
  259:                 $uselocal = 0;
  260:             }
  261:         }  elsif ($distro =~ /^(?:sles)(\d+)$/) {
  262:             if ($1 < 12) {
  263:                 $uselocal = 0;
  264:             }
  265:         }
  266:     }
  267:     if ($uselocal) {
  268:         $rep = LONCAPA::Lond::server_certs(\%perlvar,$lonhost,$hostname);
  269:     } else {
  270:         $rep=&reply('servercerts',$lonhost);
  271:     }
  272:     my ($result,%returnhash);
  273:     if (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
  274:         ($rep eq 'unknown_cmd')) {
  275:         $result = $rep;
  276:     } else {
  277:         $result = 'ok';
  278:         my @pairs=split(/\&/,$rep);
  279:         foreach my $item (@pairs) {
  280:             my ($key,$value)=split(/=/,$item,2);
  281:             my $what = &unescape($key);
  282:             $returnhash{$what}=&thaw_unescape($value);
  283:         }
  284:     }
  285:     return ($result,\%returnhash);
  286: }
  287: 
  288: sub get_server_loncaparev {
  289:     my ($dom,$lonhost,$ignore_cache,$caller) = @_;
  290:     if (defined($lonhost)) {
  291:         if (!defined(&hostname($lonhost))) {
  292:             undef($lonhost);
  293:         }
  294:     }
  295:     if (!defined($lonhost)) {
  296:         if (defined(&domain($dom,'primary'))) {
  297:             $lonhost=&domain($dom,'primary');
  298:             if ($lonhost eq 'no_host') {
  299:                 undef($lonhost);
  300:             }
  301:         }
  302:     }
  303:     if (defined($lonhost)) {
  304:         my $cachetime = 12*3600;
  305:         if (!$ignore_cache) {
  306:             my ($loncaparev,$cached)=&is_cached_new('serverloncaparev',$lonhost);
  307:             if (defined($cached)) {
  308:                 return $loncaparev;
  309:             }
  310:         }
  311:         my ($answer,$loncaparev);
  312:         my @ids=&current_machine_ids();
  313:         if (grep(/^\Q$lonhost\E$/,@ids)) {
  314:             $answer = $perlvar{'lonVersion'};
  315:             if ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
  316:                 $loncaparev = $1;
  317:             }
  318:         } else {
  319:             $answer = &reply('serverloncaparev',$lonhost);
  320:             if (($answer eq 'unknown_cmd') || ($answer eq 'con_lost')) {
  321:                 if ($caller eq 'loncron') {
  322:                     my $hostname = &hostname($lonhost);
  323:                     my $protocol = $protocol{$lonhost};
  324:                     $protocol = 'http' if ($protocol ne 'https');
  325:                     my $url = $protocol.'://'.$hostname.'/adm/about.html';
  326:                     my $request=new HTTP::Request('GET',$url);
  327:                     my $response=&LONCAPA::LWPReq::makerequest($lonhost,$request,'',\%perlvar,4,1);
  328:                     unless ($response->is_error()) {
  329:                         my $content = $response->content;
  330:                         if ($content =~ /<p>VERSION\:\s*([\w.\-]+)<\/p>/) {
  331:                             $loncaparev = $1;
  332:                         }
  333:                     }
  334:                 } else {
  335:                     $loncaparev = $loncaparevs{$lonhost};
  336:                 }
  337:             } elsif ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
  338:                 $loncaparev = $1;
  339:             }
  340:         }
  341:         return &do_cache_new('serverloncaparev',$lonhost,$loncaparev,$cachetime);
  342:     }
  343: }
  344: 
  345: sub get_server_homeID {
  346:     my ($hostname,$ignore_cache,$caller) = @_;
  347:     unless ($ignore_cache) {
  348:         my ($serverhomeID,$cached)=&is_cached_new('serverhomeID',$hostname);
  349:         if (defined($cached)) {
  350:             return $serverhomeID;
  351:         }
  352:     }
  353:     my $cachetime = 12*3600;
  354:     my $serverhomeID;
  355:     if ($caller eq 'loncron') { 
  356:         my @machine_ids = &machine_ids($hostname);
  357:         foreach my $id (@machine_ids) {
  358:             my $response = &reply('serverhomeID',$id);
  359:             unless (($response eq 'unknown_cmd') || ($response eq 'con_lost')) {
  360:                 $serverhomeID = $response;
  361:                 last;
  362:             }
  363:         }
  364:         if ($serverhomeID eq '') {
  365:             $serverhomeID = $machine_ids[-1];
  366:         }
  367:     } else {
  368:         $serverhomeID = $serverhomeIDs{$hostname};
  369:     }
  370:     return &do_cache_new('serverhomeID',$hostname,$serverhomeID,$cachetime);
  371: }
  372: 
  373: sub get_remote_globals {
  374:     my ($lonhost,$whathash,$ignore_cache) = @_;
  375:     my ($result,%returnhash,%whatneeded);
  376:     if (ref($whathash) eq 'HASH') {
  377:         foreach my $what (sort(keys(%{$whathash}))) {
  378:             my $hashid = $lonhost.'-'.$what;
  379:             my ($response,$cached);
  380:             unless ($ignore_cache) {
  381:                 ($response,$cached)=&is_cached_new('lonnetglobal',$hashid);
  382:             }
  383:             if (defined($cached)) {
  384:                 $returnhash{$what} = $response;
  385:             } else {
  386:                 $whatneeded{$what} = 1;
  387:             }
  388:         }
  389:         if (keys(%whatneeded) == 0) {
  390:             $result = 'ok';
  391:         } else {
  392:             my $requested = &freeze_escape(\%whatneeded);
  393:             my $rep=&reply('readlonnetglobal:'.$requested,$lonhost);
  394:             if (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
  395:                 ($rep eq 'unknown_cmd')) {
  396:                 $result = $rep;
  397:             } else {
  398:                 $result = 'ok';
  399:                 my @pairs=split(/\&/,$rep);
  400:                 foreach my $item (@pairs) {
  401:                     my ($key,$value)=split(/=/,$item,2);
  402:                     my $what = &unescape($key);
  403:                     my $hashid = $lonhost.'-'.$what;
  404:                     $returnhash{$what}=&thaw_unescape($value);
  405:                     &do_cache_new('lonnetglobal',$hashid,$returnhash{$what},600);
  406:                 }
  407:             }
  408:         }
  409:     }
  410:     return ($result,\%returnhash);
  411: }
  412: 
  413: sub remote_devalidate_cache {
  414:     my ($lonhost,$cachekeys) = @_;
  415:     my $items;
  416:     return unless (ref($cachekeys) eq 'ARRAY');
  417:     my $cachestr = join('&',@{$cachekeys});
  418:     my $response = &reply('devalidatecache:'.&escape($cachestr),$lonhost);
  419:     return $response;
  420: }
  421: 
  422: sub sign_lti {
  423:     my ($cdom,$cnum,$crsdef,$type,$context,$url,$ltinum,$keynum,$paramsref,$inforef) = @_;
  424:     my $chome;
  425:     if (&domain($cdom) ne '') {
  426:         if ($crsdef) {
  427:             $chome = &homeserver($cnum,$cdom);
  428:         } else {
  429:             $chome = &domain($cdom,'primary');
  430:         }
  431:     }
  432:     if ($cdom && $chome && ($chome ne 'no_host')) {
  433:         if ((ref($paramsref) eq 'HASH') &&
  434:             (ref($inforef) eq 'HASH')) {
  435:             my $rep;
  436:             if (grep { $_ eq $chome } &current_machine_ids()) {
  437:                 # domain information is hosted on this machine
  438:                 $rep =
  439:                     &LONCAPA::Lond::sign_lti_payload($cdom,$cnum,$crsdef,$type,
  440:                                                      $context,$url,$ltinum,$keynum,
  441:                                                      $perlvar{'lonVersion'},
  442:                                                      $paramsref,$inforef);
  443:                 if (ref($rep) eq 'HASH') {
  444:                     return ('ok',$rep);
  445:                 }
  446:             } else {
  447:                 my ($escurl,$params,$info);
  448:                 $escurl = &escape($url);
  449:                 if (ref($paramsref) eq 'HASH') {
  450:                     $params = &freeze_escape($paramsref);
  451:                 }
  452:                 if (ref($inforef) eq 'HASH') {
  453:                     $info = &freeze_escape($inforef);
  454:                 }
  455:                 $rep=&reply("encrypt:signlti:$cdom:$cnum:$crsdef:$type:$context:$escurl:$ltinum:$keynum:$params:$info",$chome);
  456:             }
  457:             if (($rep eq '') || ($rep =~ /^con_lost|error|no_such_host|unknown_cmd/i)) {
  458:                 return ();
  459:             } elsif (($inforef->{'respfmt'} eq 'to_post_body') ||
  460:                      ($inforef->{'respfmt'} eq 'to_authorization_header')) {
  461:                 return ('ok',$rep);
  462:             } else {
  463:                 my %returnhash;
  464:                 foreach my $item (split(/\&/,$rep)) {
  465:                     my ($name,$value)=split(/\=/,$item);
  466:                     $returnhash{&unescape($name)}=&thaw_unescape($value);
  467:                 }
  468:                 return('ok',\%returnhash);
  469:             }
  470:         } else {
  471:             return ();
  472:         }
  473:     } else {
  474:         return ();
  475:         &logthis("sign_lti failed - no homeserver and/or domain ($cdom) ($chome)");
  476:     }
  477: }
  478: 
  479: # -------------------------------------------------- Non-critical communication
  480: sub subreply {
  481:     my ($cmd,$server)=@_;
  482:     my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
  483:     #
  484:     #  With loncnew process trimming, there's a timing hole between lonc server
  485:     #  process exit and the master server picking up the listen on the AF_UNIX
  486:     #  socket.  In that time interval, a lock file will exist:
  487: 
  488:     my $lockfile=$peerfile.".lock";
  489:     while (-e $lockfile) {	# Need to wait for the lockfile to disappear.
  490: 	sleep(0.1);
  491:     }
  492:     # At this point, either a loncnew parent is listening or an old lonc
  493:     # or loncnew child is listening so we can connect or everything's dead.
  494:     #
  495:     #   We'll give the connection a few tries before abandoning it.  If
  496:     #   connection is not possible, we'll con_lost back to the client.
  497:     #   
  498:     my $client;
  499:     for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
  500: 	$client=IO::Socket::UNIX->new(Peer    =>"$peerfile",
  501: 				      Type    => SOCK_STREAM,
  502: 				      Timeout => 10);
  503: 	if ($client) {
  504: 	    last;		# Connected!
  505: 	} else {
  506: 	    &create_connection(&hostname($server),$server);
  507: 	}
  508:         sleep(0.1);	# Try again later if failed connection.
  509:     }
  510:     my $answer;
  511:     if ($client) {
  512: 	print $client "sethost:$server:$cmd\n";
  513: 	$answer=<$client>;
  514: 	if (!$answer) { $answer="con_lost"; }
  515: 	chomp($answer);
  516:     } else {
  517: 	$answer = 'con_lost';	# Failed connection.
  518:     }
  519:     return $answer;
  520: }
  521: 
  522: sub reply {
  523:     my ($cmd,$server)=@_;
  524:     unless (defined(&hostname($server))) { return 'no_such_host'; }
  525:     my $answer=subreply($cmd,$server);
  526:     if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
  527:         my $logged = $cmd;
  528:         if ($cmd =~ /^encrypt:([^:]+):/) {
  529:             my $subcmd = $1;
  530:             if (($subcmd eq 'auth') || ($subcmd eq 'passwd') ||
  531:                 ($subcmd eq 'changeuserauth') || ($subcmd eq 'makeuser') ||
  532:                 ($subcmd eq 'putdom') || ($subcmd eq 'autoexportgrades') ||
  533:                 ($subcmd eq 'put')) {
  534:                 (undef,undef,my @rest) = split(/:/,$cmd);
  535:                 if (($subcmd eq 'auth') || ($subcmd eq 'putdom')) {
  536:                     splice(@rest,2,1,'Hidden');
  537:                 } elsif ($subcmd eq 'passwd') {
  538:                     splice(@rest,2,2,('Hidden','Hidden'));
  539:                 } elsif (($subcmd eq 'changeuserauth') || ($subcmd eq 'makeuser') ||
  540:                          ($subcmd eq 'autoexportgrades') || ($subcmd eq 'put')) {
  541:                     splice(@rest,3,1,'Hidden');
  542:                 }
  543:                 $logged = join(':',('encrypt:'.$subcmd,@rest));
  544:             }
  545:         }
  546:         &logthis("<font color=\"blue\">WARNING:".
  547:                  " $logged to $server returned $answer</font>");
  548:     }
  549:     return $answer;
  550: }
  551: 
  552: # ----------------------------------------------------------- Send USR1 to lonc
  553: 
  554: sub reconlonc {
  555:     my ($lonid) = @_;
  556:     if ($lonid) {
  557:         my $hostname = &hostname($lonid);
  558: 	my $peerfile="$perlvar{'lonSockDir'}/$hostname";
  559: 	if ($hostname && -e $peerfile) {
  560: 	    &logthis("Trying to reconnect lonc for $lonid ($hostname)");
  561: 	    my $client=IO::Socket::UNIX->new(Peer    => $peerfile,
  562: 					     Type    => SOCK_STREAM,
  563: 					     Timeout => 10);
  564: 	    if ($client) {
  565: 		print $client ("reset_retries\n");
  566: 		my $answer=<$client>;
  567: 		#reset just this one.
  568: 	    }
  569: 	}
  570: 	return;
  571:     }
  572: 
  573:     &logthis("Trying to reconnect lonc");
  574:     my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
  575:     if (open(my $fh,"<",$loncfile)) {
  576: 	my $loncpid=<$fh>;
  577:         chomp($loncpid);
  578:         if (kill 0 => $loncpid) {
  579: 	    &logthis("lonc at pid $loncpid responding, sending USR1");
  580:             kill USR1 => $loncpid;
  581:             sleep 1;
  582:         } else {
  583: 	    &logthis(
  584:                "<font color=\"blue\">WARNING:".
  585:                " lonc at pid $loncpid not responding, giving up</font>");
  586:         }
  587:     } else {
  588: 	&logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
  589:     }
  590: }
  591: 
  592: # ------------------------------------------------------ Critical communication
  593: 
  594: sub critical {
  595:     my ($cmd,$server)=@_;
  596:     unless (&hostname($server)) {
  597:         &logthis("<font color=\"blue\">WARNING:".
  598:                " Critical message to unknown server ($server)</font>");
  599:         return 'no_such_host';
  600:     }
  601:     my $answer=reply($cmd,$server);
  602:     if ($answer eq 'con_lost') {
  603: 	&reconlonc($server);
  604: 	my $answer=reply($cmd,$server);
  605:         if ($answer eq 'con_lost') {
  606:             my $now=time;
  607:             my $middlename=$cmd;
  608:             $middlename=substr($middlename,0,16);
  609:             $middlename=~s/\W//g;
  610:             my $dfilename=
  611:       "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
  612:             $dumpcount++;
  613:             {
  614: 		my $dfh;
  615: 		if (open($dfh,">",$dfilename)) {
  616: 		    print $dfh "$cmd\n"; 
  617: 		    close($dfh);
  618: 		}
  619:             }
  620:             sleep 1;
  621:             my $wcmd='';
  622:             {
  623: 		my $dfh;
  624: 		if (open($dfh,"<",$dfilename)) {
  625: 		    $wcmd=<$dfh>; 
  626: 		    close($dfh);
  627: 		}
  628:             }
  629:             chomp($wcmd);
  630:             if ($wcmd eq $cmd) {
  631: 		&logthis("<font color=\"blue\">WARNING: ".
  632:                          "Connection buffer $dfilename: $cmd</font>");
  633:                 &logperm("D:$server:$cmd");
  634: 	        return 'con_delayed';
  635:             } else {
  636:                 &logthis("<font color=\"red\">CRITICAL:"
  637:                         ." Critical connection failed: $server $cmd</font>");
  638:                 &logperm("F:$server:$cmd");
  639:                 return 'con_failed';
  640:             }
  641:         }
  642:     }
  643:     return $answer;
  644: }
  645: 
  646: # ------------------------------------------- check if return value is an error
  647: 
  648: sub error {
  649:     my ($result) = @_;
  650:     if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
  651: 	if ($2 == 2) { return undef; }
  652: 	return $1;
  653:     }
  654:     return undef;
  655: }
  656: 
  657: sub convert_and_load_session_env {
  658:     my ($lonidsdir,$handle)=@_;
  659:     my @profile;
  660:     {
  661: 	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
  662: 	if (!$opened) {
  663: 	    return 0;
  664: 	}
  665: 	flock($idf,LOCK_SH);
  666: 	@profile=<$idf>;
  667: 	close($idf);
  668:     }
  669:     my %temp_env;
  670:     foreach my $line (@profile) {
  671: 	if ($line !~ m/=/) {
  672: 	    return 0;
  673: 	}
  674: 	chomp($line);
  675: 	my ($envname,$envvalue)=split(/=/,$line,2);
  676: 	$temp_env{&unescape($envname)} = &unescape($envvalue);
  677:     }
  678:     unlink("$lonidsdir/$handle.id");
  679:     if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
  680: 	    0640)) {
  681: 	%disk_env = %temp_env;
  682: 	@env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
  683: 	untie(%disk_env);
  684:     }
  685:     return 1;
  686: }
  687: 
  688: # ------------------------------------------- Transfer profile into environment
  689: my $env_loaded;
  690: sub transfer_profile_to_env {
  691:     my ($lonidsdir,$handle,$force_transfer) = @_;
  692:     if (!$force_transfer && $env_loaded) { return; } 
  693: 
  694:     if (!defined($lonidsdir)) {
  695: 	$lonidsdir = $perlvar{'lonIDsDir'};
  696:     }
  697:     if (!defined($handle)) {
  698:         ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
  699:     }
  700: 
  701:     my $convert;
  702:     {
  703:     	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
  704: 	if (!$opened) {
  705: 	    return;
  706: 	}
  707: 	flock($idf,LOCK_SH);
  708: 	if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
  709: 		&GDBM_READER(),0640)) {
  710: 	    @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
  711: 	    untie(%disk_env);
  712: 	} else {
  713: 	    $convert = 1;
  714: 	}
  715:     }
  716:     if ($convert) {
  717: 	if (!&convert_and_load_session_env($lonidsdir,$handle)) {
  718: 	    &logthis("Failed to load session, or convert session.");
  719: 	}
  720:     }
  721: 
  722:     my %remove;
  723:     while ( my $envname = each(%env) ) {
  724:         if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
  725:             if ($time < time-300) {
  726:                 $remove{$key}++;
  727:             }
  728:         }
  729:     }
  730: 
  731:     $env{'user.environment'} = "$lonidsdir/$handle.id";
  732:     $env_loaded=1;
  733:     foreach my $expired_key (keys(%remove)) {
  734:         &delenv($expired_key);
  735:     }
  736: }
  737: 
  738: # ---------------------------------------------------- Check for valid session 
  739: sub check_for_valid_session {
  740:     my ($r,$name,$userhashref,$domref) = @_;
  741:     my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
  742:     my ($lonidsdir,$linkname,$pubname,$secure,$lonid);
  743:     if ($name eq 'lonDAV') {
  744:         $lonidsdir=$r->dir_config('lonDAVsessDir');
  745:     } else {
  746:         $lonidsdir=$r->dir_config('lonIDsDir');
  747:         if ($name eq '') {
  748:             $name = 'lonID';
  749:         }
  750:     }
  751:     if ($name eq 'lonID') {
  752:         $secure = 'lonSID';
  753:         $linkname = 'lonLinkID';
  754:         $pubname = 'lonPubID';
  755:         if (exists($cookies{$secure})) {
  756:             $lonid=$cookies{$secure};
  757:         } elsif (exists($cookies{$name})) {
  758:             $lonid=$cookies{$name};
  759:         } elsif ((exists($cookies{$linkname})) && ($ENV{'SERVER_PORT'} != 443)) {
  760:             $lonid=$cookies{$linkname};
  761:         } elsif (exists($cookies{$pubname})) {
  762:             $lonid=$cookies{$pubname};
  763:         }
  764:     } else {
  765:         $lonid=$cookies{$name};
  766:     }
  767:     return undef if (!$lonid);
  768: 
  769:     my $handle=&LONCAPA::clean_handle($lonid->value);
  770:     if (-l "$lonidsdir/$handle.id") {
  771:         my $link = readlink("$lonidsdir/$handle.id");
  772:         if ((-e $link) && ($link =~ m{^\Q$lonidsdir\E/(.+)\.id$})) {
  773:             $handle = $1;
  774:         }
  775:     }
  776:     if (!-e "$lonidsdir/$handle.id") {
  777:         if ((ref($domref)) && ($name eq 'lonID') && 
  778:             ($handle =~ /^($match_username)\_\d+\_($match_domain)\_(.+)$/)) {
  779:             my ($possuname,$possudom,$possuhome) = ($1,$2,$3);
  780:             if ((&domain($possudom) ne '') && (&homeserver($possuname,$possudom) eq $possuhome)) {
  781:                 $$domref = $possudom;
  782:             }
  783:         }
  784:         return undef;
  785:     }
  786: 
  787:     my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
  788:     return undef if (!$opened);
  789: 
  790:     flock($idf,LOCK_SH);
  791:     my %disk_env;
  792:     if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
  793: 	    &GDBM_READER(),0640)) {
  794: 	return undef;	
  795:     }
  796: 
  797:     if (!defined($disk_env{'user.name'})
  798: 	|| !defined($disk_env{'user.domain'})) {
  799:         untie(%disk_env);
  800: 	return undef;
  801:     }
  802: 
  803:     if (ref($userhashref) eq 'HASH') {
  804:         $userhashref->{'name'} = $disk_env{'user.name'};
  805:         $userhashref->{'domain'} = $disk_env{'user.domain'};
  806:         if ($disk_env{'request.role'}) {
  807:             $userhashref->{'role'} = $disk_env{'request.role'};
  808:         }
  809:         $userhashref->{'lti'} = $disk_env{'request.lti.login'};
  810:         if ($userhashref->{'lti'}) {
  811:             $userhashref->{'ltitarget'} = $disk_env{'request.lti.target'};
  812:             $userhashref->{'ltiuri'} = $disk_env{'request.lti.uri'};
  813:         }
  814:     }
  815:     untie(%disk_env);
  816: 
  817:     return $handle;
  818: }
  819: 
  820: sub timed_flock {
  821:     my ($file,$lock_type) = @_;
  822:     my $failed=0;
  823:     eval {
  824: 	local $SIG{__DIE__}='DEFAULT';
  825: 	local $SIG{ALRM}=sub {
  826: 	    $failed=1;
  827: 	    die("failed lock");
  828: 	};
  829: 	alarm(13);
  830: 	flock($file,$lock_type);
  831: 	alarm(0);
  832:     };
  833:     if ($failed) {
  834: 	return undef;
  835:     } else {
  836: 	return 1;
  837:     }
  838: }
  839: 
  840: sub get_sessionfile_vars {
  841:     my ($handle,$lonidsdir,$storearr) = @_;
  842:     my %returnhash;
  843:     unless (ref($storearr) eq 'ARRAY') {
  844:         return %returnhash;
  845:     }
  846:     if (-l "$lonidsdir/$handle.id") {
  847:         my $link = readlink("$lonidsdir/$handle.id");
  848:         if ((-e $link) && ($link =~ m{^\Q$lonidsdir\E/(.+)\.id$})) {
  849:             $handle = $1;
  850:         }
  851:     }
  852:     if ((-e "$lonidsdir/$handle.id") &&
  853:         ($handle =~ /^($match_username)\_\d+\_($match_domain)\_(.+)$/)) {
  854:         my ($possuname,$possudom,$possuhome) = ($1,$2,$3);
  855:         if ((&domain($possudom) ne '') && (&homeserver($possuname,$possudom) eq $possuhome)) {
  856:             if (open(my $idf,'+<',"$lonidsdir/$handle.id")) {
  857:                 flock($idf,LOCK_SH);
  858:                 if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
  859:                         &GDBM_READER(),0640)) {
  860:                     foreach my $item (@{$storearr}) {
  861:                         $returnhash{$item} = $disk_env{$item};
  862:                     }
  863:                     untie(%disk_env);
  864:                 }
  865:             }
  866:         }
  867:     }
  868:     return %returnhash;
  869: }
  870: 
  871: # ---------------------------------------------------------- Append Environment
  872: 
  873: sub appenv {
  874:     my ($newenv,$roles) = @_;
  875:     if (ref($newenv) eq 'HASH') {
  876:         foreach my $key (keys(%{$newenv})) {
  877:             my $refused = 0;
  878: 	    if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
  879:                 $refused = 1;
  880:                 if (ref($roles) eq 'ARRAY') {
  881:                     my ($type,$role) = ($key =~ m{^user\.(role|priv)\.(.+?)\./});
  882:                     if (grep(/^\Q$role\E$/,@{$roles})) {
  883:                         $refused = 0;
  884:                     }
  885:                 }
  886:             }
  887:             if ($refused) {
  888:                 &logthis("<font color=\"blue\">WARNING: ".
  889:                          "Attempt to modify environment ".$key." to ".$newenv->{$key}
  890:                          .'</font>');
  891: 	        delete($newenv->{$key});
  892:             } else {
  893:                 $env{$key}=$newenv->{$key};
  894:             }
  895:         }
  896:         my $lonids = $perlvar{'lonIDsDir'};
  897:         if ($env{'user.environment'} =~ m{^\Q$lonids/\E$match_username\_\d+\_$match_domain\_[\w\-.]+\.id$}) {
  898:             my $opened = open(my $env_file,'+<',$env{'user.environment'});
  899:             if ($opened
  900: 	        && &timed_flock($env_file,LOCK_EX)
  901: 	        &&
  902: 	        tie(my %disk_env,'GDBM_File',$env{'user.environment'},
  903: 	            (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
  904: 	        while (my ($key,$value) = each(%{$newenv})) {
  905: 	            $disk_env{$key} = $value;
  906: 	        }
  907: 	        untie(%disk_env);
  908:             }
  909:         }
  910:     }
  911:     return 'ok';
  912: }
  913: # ----------------------------------------------------- Delete from Environment
  914: 
  915: sub delenv {
  916:     my ($delthis,$regexp,$roles) = @_;
  917:     if (($delthis=~/^user\.role/) || ($delthis=~/^user\.priv/)) {
  918:         my $refused = 1;
  919:         if (ref($roles) eq 'ARRAY') {
  920:             my ($type,$role) = ($delthis =~ /^user\.(role|priv)\.([^.]+)\./);
  921:             if (grep(/^\Q$role\E$/,@{$roles})) {
  922:                 $refused = 0;
  923:             }
  924:         }
  925:         if ($refused) {
  926:             &logthis("<font color=\"blue\">WARNING: ".
  927:                      "Attempt to delete from environment ".$delthis);
  928:             return 'error';
  929:         }
  930:     }
  931:     my $opened = open(my $env_file,'+<',$env{'user.environment'});
  932:     if ($opened
  933: 	&& &timed_flock($env_file,LOCK_EX)
  934: 	&&
  935: 	tie(my %disk_env,'GDBM_File',$env{'user.environment'},
  936: 	    (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
  937: 	foreach my $key (keys(%disk_env)) {
  938: 	    if ($regexp) {
  939:                 if ($key=~/^$delthis/) {
  940:                     delete($env{$key});
  941:                     delete($disk_env{$key});
  942:                 } 
  943:             } else {
  944:                 if ($key=~/^\Q$delthis\E/) {
  945: 		    delete($env{$key});
  946: 		    delete($disk_env{$key});
  947: 	        }
  948:             }
  949: 	}
  950: 	untie(%disk_env);
  951:     }
  952:     return 'ok';
  953: }
  954: 
  955: sub get_env_multiple {
  956:     my ($name) = @_;
  957:     my @values;
  958:     if (defined($env{$name})) {
  959:         # exists is it an array
  960:         if (ref($env{$name})) {
  961:             @values=@{ $env{$name} };
  962:         } else {
  963:             $values[0]=$env{$name};
  964:         }
  965:     }
  966:     return(@values);
  967: }
  968: 
  969: # ------------------------------------------------------------------- Locking
  970: 
  971: sub set_lock {
  972:     my ($text)=@_;
  973:     $locknum++;
  974:     my $id=$$.'-'.$locknum;
  975:     &appenv({'session.locks' => $env{'session.locks'}.','.$id,
  976:              'session.lock.'.$id => $text});
  977:     return $id;
  978: }
  979: 
  980: sub get_locks {
  981:     my $num=0;
  982:     my %texts=();
  983:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
  984:        if ($lock=~/\w/) {
  985:           $num++;
  986:           $texts{$lock}=$env{'session.lock.'.$lock};
  987:        }
  988:    }
  989:    return ($num,%texts);
  990: }
  991: 
  992: sub remove_lock {
  993:     my ($id)=@_;
  994:     my $newlocks='';
  995:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
  996:        if (($lock=~/\w/) && ($lock ne $id)) {
  997:           $newlocks.=','.$lock;
  998:        }
  999:     }
 1000:     &appenv({'session.locks' => $newlocks});
 1001:     &delenv('session.lock.'.$id);
 1002: }
 1003: 
 1004: sub remove_all_locks {
 1005:     my $activelocks=$env{'session.locks'};
 1006:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
 1007:        if ($lock=~/\w/) {
 1008:           &remove_lock($lock);
 1009:        }
 1010:     }
 1011: }
 1012: 
 1013: 
 1014: # ------------------------------------------ Find out current server userload
 1015: sub userload {
 1016:     my $numusers=0;
 1017:     {
 1018: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
 1019: 	my $filename;
 1020: 	my $curtime=time;
 1021: 	while ($filename=readdir(LONIDS)) {
 1022: 	    next if ($filename eq '.' || $filename eq '..');
 1023: 	    next if ($filename =~ /publicuser_\d+\.id/);
 1024:             next if ($filename =~ /^[a-f0-9]+_linked\.id$/);
 1025: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
 1026: 	    if ($curtime-$mtime < 1800) { $numusers++; }
 1027: 	}
 1028: 	closedir(LONIDS);
 1029:     }
 1030:     my $userloadpercent=0;
 1031:     my $maxuserload=$perlvar{'lonUserLoadLim'};
 1032:     if ($maxuserload) {
 1033: 	$userloadpercent=100*$numusers/$maxuserload;
 1034:     }
 1035:     $userloadpercent=sprintf("%.2f",$userloadpercent);
 1036:     return $userloadpercent;
 1037: }
 1038: 
 1039: # ------------------------------ Find server with least workload from spare.tab
 1040: 
 1041: sub spareserver {
 1042:     my ($r,$loadpercent,$userloadpercent,$want_server_name,$udom) = @_;
 1043:     my $spare_server;
 1044:     if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
 1045:     my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent 
 1046:                                                      :  $userloadpercent;
 1047:     my ($uint_dom,$remotesessions);
 1048:     if (($udom ne '') && (&domain($udom) ne '')) {
 1049:         my $uprimary_id = &domain($udom,'primary');
 1050:         $uint_dom = &internet_dom($uprimary_id);
 1051:         my %udomdefaults = &get_domain_defaults($udom);
 1052:         $remotesessions = $udomdefaults{'remotesessions'};
 1053:     }
 1054:     my $spareshash = &this_host_spares($udom);
 1055:     if (ref($spareshash) eq 'HASH') {
 1056:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
 1057:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
 1058:                 next unless (&spare_can_host($udom,$uint_dom,$remotesessions,
 1059:                                              $try_server));
 1060: 	        ($spare_server, $lowest_load) =
 1061: 	            &compare_server_load($try_server, $spare_server, $lowest_load);
 1062:             }
 1063:         }
 1064: 
 1065:         my $found_server = ($spare_server ne '' && $lowest_load < 100);
 1066: 
 1067:         if (!$found_server) {
 1068:             if (ref($spareshash->{'default'}) eq 'ARRAY') { 
 1069: 	        foreach my $try_server (@{ $spareshash->{'default'} }) {
 1070:                     next unless (&spare_can_host($udom,$uint_dom,
 1071:                                                  $remotesessions,$try_server));
 1072: 	            ($spare_server, $lowest_load) =
 1073: 		        &compare_server_load($try_server, $spare_server, $lowest_load);
 1074:                 }
 1075: 	    }
 1076:         }
 1077:     }
 1078: 
 1079:     if (!$want_server_name) {
 1080:         if (defined($spare_server)) {
 1081:             my $hostname = &hostname($spare_server);
 1082:             if (defined($hostname)) {
 1083:                 my $protocol = 'http';
 1084:                 if ($protocol{$spare_server} eq 'https') {
 1085:                     $protocol = $protocol{$spare_server};
 1086:                 }
 1087:                 my $alias = &use_proxy_alias($r,$spare_server);
 1088:                 $hostname = $alias if ($alias ne '');
 1089: 	        $spare_server = $protocol.'://'.$hostname;
 1090:             }
 1091:         }
 1092:     }
 1093:     return $spare_server;
 1094: }
 1095: 
 1096: sub compare_server_load {
 1097:     my ($try_server, $spare_server, $lowest_load, $required) = @_;
 1098: 
 1099:     if ($required) {
 1100:         my ($reqdmajor,$reqdminor) = ($required =~ /^(\d+)\.(\d+)$/);
 1101:         my $remoterev = &get_server_loncaparev(undef,$try_server);
 1102:         my ($major,$minor) = ($remoterev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
 1103:         if (($major eq '' && $minor eq '') ||
 1104:             (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)))) {
 1105:             return ($spare_server,$lowest_load);
 1106:         }
 1107:     }
 1108: 
 1109:     my $loadans     = &reply('load',    $try_server);
 1110:     my $userloadans = &reply('userload',$try_server);
 1111: 
 1112:     if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
 1113: 	return ($spare_server, $lowest_load); #didn't get a number from the server
 1114:     }
 1115: 
 1116:     my $load;
 1117:     if ($loadans =~ /\d/) {
 1118: 	if ($userloadans =~ /\d/) {
 1119: 	    #both are numbers, pick the bigger one
 1120: 	    $load = ($loadans > $userloadans) ? $loadans 
 1121: 		                              : $userloadans;
 1122: 	} else {
 1123: 	    $load = $loadans;
 1124: 	}
 1125:     } else {
 1126: 	$load = $userloadans;
 1127:     }
 1128: 
 1129:     if (($load =~ /\d/) && ($load < $lowest_load)) {
 1130: 	$spare_server = $try_server;
 1131: 	$lowest_load  = $load;
 1132:     }
 1133:     return ($spare_server,$lowest_load);
 1134: }
 1135: 
 1136: # --------------------------- ask offload servers if user already has a session
 1137: sub find_existing_session {
 1138:     my ($udom,$uname) = @_;
 1139:     my $spareshash = &this_host_spares($udom);
 1140:     if (ref($spareshash) eq 'HASH') {
 1141:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
 1142:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
 1143:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
 1144:             }
 1145:         }
 1146:         if (ref($spareshash->{'default'}) eq 'ARRAY') {
 1147:             foreach my $try_server (@{ $spareshash->{'default'} }) {
 1148:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
 1149:             }
 1150:         }
 1151:     }
 1152:     return;
 1153: }
 1154: 
 1155: sub delusersession {
 1156:     my ($lonid,$udom,$uname) = @_;
 1157:     my $uprimary_id = &domain($udom,'primary');
 1158:     my $uintdom = &internet_dom($uprimary_id);
 1159:     my $intdom = &internet_dom($lonid);
 1160:     my $serverhomedom = &host_domain($lonid);
 1161:     if (($uintdom ne '') && ($uintdom eq $intdom)) {
 1162:         return &reply(join(':','delusersession',
 1163:                             map {&escape($_)} ($udom,$uname)),$lonid);
 1164:     }
 1165:     return;
 1166: }
 1167: 
 1168: # check if user's browser sent load balancer cookie and server still has session
 1169: # and is not overloaded.
 1170: sub check_for_balancer_cookie {
 1171:     my ($r,$update_mtime) = @_;
 1172:     my ($otherserver,$cookie);
 1173:     my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
 1174:     if (exists($cookies{'balanceID'})) {
 1175:         my $balid = $cookies{'balanceID'};
 1176:         $cookie=&LONCAPA::clean_handle($balid->value);
 1177:         my $balancedir=$r->dir_config('lonBalanceDir');
 1178:         if ((-d $balancedir) && (-e "$balancedir/$cookie.id")) {
 1179:             if ($cookie =~ /^($match_domain)_($match_username)_[a-f0-9]+$/) {
 1180:                 my ($possudom,$possuname) = ($1,$2);
 1181:                 my $has_session = 0;
 1182:                 if ((&domain($possudom) ne '') &&
 1183:                     (&homeserver($possuname,$possudom) ne 'no_host')) {
 1184:                     my $try_server;
 1185:                     my $opened = open(my $idf,'+<',"$balancedir/$cookie.id");
 1186:                     if ($opened) {
 1187:                         flock($idf,LOCK_SH);
 1188:                         while (my $line = <$idf>) {
 1189:                             chomp($line);
 1190:                             if (&hostname($line) ne '') {
 1191:                                 $try_server = $line;
 1192:                                 last;
 1193:                             }
 1194:                         }
 1195:                         close($idf);
 1196:                         if (($try_server) &&
 1197:                             (&has_user_session($try_server,$possudom,$possuname))) {
 1198:                             my $lowest_load = 30000;
 1199:                             ($otherserver,$lowest_load) =
 1200:                                 &compare_server_load($try_server,undef,$lowest_load);
 1201:                             if ($otherserver ne '' && $lowest_load < 100) {
 1202:                                 $has_session = 1;
 1203:                             } else {
 1204:                                 undef($otherserver);
 1205:                             }
 1206:                         }
 1207:                     }
 1208:                 }
 1209:                 if ($has_session) {
 1210:                     if ($update_mtime) {
 1211:                         my $atime = my $mtime = time;
 1212:                         utime($atime,$mtime,"$balancedir/$cookie.id");
 1213:                     }
 1214:                 } else {
 1215:                     unlink("$balancedir/$cookie.id");
 1216:                 }
 1217:             }
 1218:         }
 1219:     }
 1220:     return ($otherserver,$cookie);
 1221: }
 1222: 
 1223: sub updatebalcookie {
 1224:     my ($cookie,$balancer,$lastentry)=@_;
 1225:     if ($cookie =~ /^($match_domain)\_($match_username)\_[a-f0-9]{32}$/) {
 1226:         my ($udom,$uname) = ($1,$2);
 1227:         my $uprimary_id = &domain($udom,'primary');
 1228:         my $uintdom = &internet_dom($uprimary_id);
 1229:         my $intdom = &internet_dom($balancer);
 1230:         my $serverhomedom = &host_domain($balancer);
 1231:         if (($uintdom ne '') && ($uintdom eq $intdom)) {
 1232:             return &reply('updatebalcookie:'.&escape($cookie).':'.&escape($lastentry),$balancer);
 1233:         }
 1234:     }
 1235:     return;
 1236: }
 1237: 
 1238: sub delbalcookie {
 1239:     my ($cookie,$balancer) =@_;
 1240:     if ($cookie =~ /^($match_domain)\_($match_username)\_[a-f0-9]{32}$/) {
 1241:         my ($udom,$uname) = ($1,$2);
 1242:         my $uprimary_id = &domain($udom,'primary');
 1243:         my $uintdom = &internet_dom($uprimary_id);
 1244:         my $intdom = &internet_dom($balancer);
 1245:         my $serverhomedom = &host_domain($balancer);
 1246:         if (($uintdom ne '') && ($uintdom eq $intdom)) {
 1247:             return &reply('delbalcookie:'.&escape($cookie),$balancer);
 1248:         }
 1249:     }
 1250: }
 1251: 
 1252: # -------------------------------- ask if server already has a session for user
 1253: sub has_user_session {
 1254:     my ($lonid,$udom,$uname) = @_;
 1255:     my $result = &reply(join(':','userhassession',
 1256: 			     map {&escape($_)} ($udom,$uname)),$lonid);
 1257:     return 1 if ($result eq 'ok');
 1258: 
 1259:     return 0;
 1260: }
 1261: 
 1262: # --------- determine least loaded server in a user's domain which allows login
 1263: 
 1264: sub choose_server {
 1265:     my ($udom,$checkloginvia,$required,$skiploadbal) = @_;
 1266:     my %domconfhash = &Apache::loncommon::get_domainconf($udom);
 1267:     my %servers = &get_servers($udom);
 1268:     my $lowest_load = 30000;
 1269:     my ($login_host,$hostname,$portal_path,$isredirect,$balancers);
 1270:     if ($skiploadbal) {
 1271:         ($balancers,my $cached)=&is_cached_new('loadbalancing',$udom);
 1272:         unless (defined($cached)) {
 1273:             my $cachetime = 60*60*24;
 1274:             my %domconfig =
 1275:                 &get_dom('configuration',['loadbalancing'],$udom);
 1276:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
 1277:                 $balancers = &do_cache_new('loadbalancing',$udom,$domconfig{'loadbalancing'},
 1278:                                            $cachetime);
 1279:             }
 1280:         }
 1281:     }
 1282:     foreach my $lonhost (keys(%servers)) {
 1283:         if ($skiploadbal) {
 1284:             if (ref($balancers) eq 'HASH') {
 1285:                 next if (exists($balancers->{$lonhost}));
 1286:             }
 1287:         }
 1288:         my $loginvia;
 1289:         if ($checkloginvia) {
 1290:             $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
 1291:             if ($loginvia) {
 1292:                 my ($server,$path) = split(/:/,$loginvia);
 1293:                 ($login_host, $lowest_load) =
 1294:                     &compare_server_load($server, $login_host, $lowest_load, $required);
 1295:                 if ($login_host eq $server) {
 1296:                     $portal_path = $path;
 1297:                     $isredirect = 1;
 1298:                 }
 1299:             } else {
 1300:                 ($login_host, $lowest_load) =
 1301:                     &compare_server_load($lonhost, $login_host, $lowest_load, $required);
 1302:                 if ($login_host eq $lonhost) {
 1303:                     $portal_path = '';
 1304:                     $isredirect = ''; 
 1305:                 }
 1306:             }
 1307:         } else {
 1308:             ($login_host, $lowest_load) =
 1309:                 &compare_server_load($lonhost, $login_host, $lowest_load, $required);
 1310:         }
 1311:     }
 1312:     if ($login_host ne '') {
 1313:         $hostname = &hostname($login_host);
 1314:     }
 1315:     return ($login_host,$hostname,$portal_path,$isredirect,$lowest_load);
 1316: }
 1317: 
 1318: sub get_course_sessions {
 1319:     my ($cnum,$cdom,$lastactivity) = @_;
 1320:     my %servers = &internet_dom_servers($cdom);
 1321:     my %returnhash;
 1322:     foreach my $server (sort(keys(%servers))) {
 1323:         my $rep = &reply("coursesessions:$cdom:$cnum:$lastactivity",$server);
 1324:         my @pairs=split(/\&/,$rep);
 1325:         unless (($rep eq 'unknown_cmd') || ($rep =~ /^error/)) {
 1326:             foreach my $item (@pairs) {
 1327:                 my ($key,$value)=split(/=/,$item,2);
 1328:                 $key = &unescape($key);
 1329:                 next if ($key =~ /^error: 2 /);
 1330:                 if (exists($returnhash{$key})) {
 1331:                     next if ($value < $returnhash{$key});
 1332:                 }
 1333:                 $returnhash{$key}=$value;
 1334:             }
 1335:         }
 1336:     }
 1337:     return %returnhash;
 1338: }
 1339: 
 1340: # --------------------------------------------- Try to change a user's password
 1341: 
 1342: sub changepass {
 1343:     my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
 1344:     $currentpass = &escape($currentpass);
 1345:     $newpass     = &escape($newpass);
 1346:     my $lonhost = $perlvar{'lonHostID'};
 1347:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
 1348: 		       $server);
 1349:     if (! $answer) {
 1350: 	&logthis("No reply on password change request to $server ".
 1351: 		 "by $uname in domain $udom.");
 1352:     } elsif ($answer =~ "^ok") {
 1353:         &logthis("$uname in $udom successfully changed their password ".
 1354: 		 "on $server.");
 1355:     } elsif ($answer =~ "^pwchange_failure") {
 1356: 	&logthis("$uname in $udom was unable to change their password ".
 1357: 		 "on $server.  The action was blocked by either lcpasswd ".
 1358: 		 "or pwchange");
 1359:     } elsif ($answer =~ "^non_authorized") {
 1360:         &logthis("$uname in $udom did not get their password correct when ".
 1361: 		 "attempting to change it on $server.");
 1362:     } elsif ($answer =~ "^auth_mode_error") {
 1363:         &logthis("$uname in $udom attempted to change their password despite ".
 1364: 		 "not being locally or internally authenticated on $server.");
 1365:     } elsif ($answer =~ "^unknown_user") {
 1366:         &logthis("$uname in $udom attempted to change their password ".
 1367: 		 "on $server but were unable to because $server is not ".
 1368: 		 "their home server.");
 1369:     } elsif ($answer =~ "^refused") {
 1370: 	&logthis("$server refused to change $uname in $udom password because ".
 1371: 		 "it was sent an unencrypted request to change the password.");
 1372:     } elsif ($answer =~ "invalid_client") {
 1373:         &logthis("$server refused to change $uname in $udom password because ".
 1374:                  "it was a reset by e-mail originating from an invalid server.");
 1375:     } elsif ($answer =~ "^prioruse") {
 1376:        &logthis("$server refused to change $uname in $udom password because ".
 1377:                 "the password had been used before");
 1378:     }
 1379:     return $answer;
 1380: }
 1381: 
 1382: # ----------------------- Try to determine user's current authentication scheme
 1383: 
 1384: sub queryauthenticate {
 1385:     my ($uname,$udom)=@_;
 1386:     my $uhome=&homeserver($uname,$udom);
 1387:     if ((!$uhome) || ($uhome eq 'no_host')) {
 1388: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
 1389: 	return 'no_host';
 1390:     }
 1391:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
 1392:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
 1393: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
 1394:     }
 1395:     return $answer;
 1396: }
 1397: 
 1398: # --------- Try to authenticate user from domain's lib servers (first this one)
 1399: 
 1400: sub authenticate {
 1401:     my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
 1402:     $upass=&escape($upass);
 1403:     $uname= &LONCAPA::clean_username($uname);
 1404:     my $uhome=&homeserver($uname,$udom,1);
 1405:     my $newhome;
 1406:     if ((!$uhome) || ($uhome eq 'no_host')) {
 1407: # Maybe the machine was offline and only re-appeared again recently?
 1408:         &reconlonc();
 1409: # One more
 1410: 	$uhome=&homeserver($uname,$udom,1);
 1411:         if (($uhome eq 'no_host') && $checkdefauth) {
 1412:             if (defined(&domain($udom,'primary'))) {
 1413:                 $newhome=&domain($udom,'primary');
 1414:             }
 1415:             if ($newhome ne '') {
 1416:                 $uhome = $newhome;
 1417:             }
 1418:         }
 1419: 	if ((!$uhome) || ($uhome eq 'no_host')) {
 1420: 	    &logthis("User $uname at $udom is unknown in authenticate");
 1421: 	    return 'no_host';
 1422:         }
 1423:     }
 1424:     my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
 1425:     if ($answer eq 'authorized') {
 1426:         if ($newhome) {
 1427:             &logthis("User $uname at $udom authorized by $uhome, but needs account");
 1428:             return 'no_account_on_host'; 
 1429:         } else {
 1430:             &logthis("User $uname at $udom authorized by $uhome");
 1431:             return $uhome;
 1432:         }
 1433:     }
 1434:     if ($answer eq 'non_authorized') {
 1435: 	&logthis("User $uname at $udom rejected by $uhome");
 1436: 	return 'no_host';
 1437:     }
 1438:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
 1439:     return 'no_host';
 1440: }
 1441: 
 1442: sub can_switchserver {
 1443:     my ($udom,$home) = @_;
 1444:     my ($canswitch,@intdoms);
 1445:     my $internet_names = &get_internet_names($home);
 1446:     if (ref($internet_names) eq 'ARRAY') {
 1447:         @intdoms = @{$internet_names};
 1448:     }
 1449:     my $uint_dom = &internet_dom(&domain($udom,'primary'));
 1450:     if ($uint_dom ne '' && grep(/^\Q$uint_dom\E$/,@intdoms)) {
 1451:         $canswitch = 1;
 1452:     } else {
 1453:          my $serverhomeID = &get_server_homeID(&hostname($home));
 1454:          my $serverhomedom = &host_domain($serverhomeID);
 1455:          my %defdomdefaults = &get_domain_defaults($serverhomedom);
 1456:          my %udomdefaults = &get_domain_defaults($udom);
 1457:          my $remoterev = &get_server_loncaparev('',$home);
 1458:          $canswitch = &can_host_session($udom,$home,$remoterev,
 1459:                                         $udomdefaults{'remotesessions'},
 1460:                                         $defdomdefaults{'hostedsessions'});
 1461:     }
 1462:     return $canswitch;
 1463: }
 1464: 
 1465: sub can_host_session {
 1466:     my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
 1467:     my $canhost = 1;
 1468:     my $host_idn = &internet_dom($lonhost);
 1469:     if (ref($remotesessions) eq 'HASH') {
 1470:         if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
 1471:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
 1472:                 $canhost = 0;
 1473:             } else {
 1474:                 $canhost = 1;
 1475:             }
 1476:         }
 1477:         if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
 1478:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
 1479:                 $canhost = 1;
 1480:             } else {
 1481:                 $canhost = 0;
 1482:             }
 1483:         }
 1484:         if ($canhost) {
 1485:             if ($remotesessions->{'version'} ne '') {
 1486:                 my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
 1487:                 if ($reqmajor ne '' && $reqminor ne '') {
 1488:                     if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
 1489:                         my $major = $1;
 1490:                         my $minor = $2;
 1491:                         if (($major < $reqmajor ) ||
 1492:                             (($major == $reqmajor) && ($minor < $reqminor))) {
 1493:                             $canhost = 0;
 1494:                         }
 1495:                     } else {
 1496:                         $canhost = 0;
 1497:                     }
 1498:                 }
 1499:             }
 1500:         }
 1501:     }
 1502:     if ($canhost) {
 1503:         if (ref($hostedsessions) eq 'HASH') {
 1504:             my $uprimary_id = &domain($udom,'primary');
 1505:             my $uint_dom = &internet_dom($uprimary_id);
 1506:             if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
 1507:                 if (($uint_dom ne '') && 
 1508:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'excludedomain'}}))) {
 1509:                     $canhost = 0;
 1510:                 } else {
 1511:                     $canhost = 1;
 1512:                 }
 1513:             }
 1514:             if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
 1515:                 if (($uint_dom ne '') && 
 1516:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'includedomain'}}))) {
 1517:                     $canhost = 1;
 1518:                 } else {
 1519:                     $canhost = 0;
 1520:                 }
 1521:             }
 1522:         }
 1523:     }
 1524:     return $canhost;
 1525: }
 1526: 
 1527: sub spare_can_host {
 1528:     my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
 1529:     my $canhost=1;
 1530:     my $try_server_hostname = &hostname($try_server);
 1531:     my $serverhomeID = &get_server_homeID($try_server_hostname);
 1532:     my $serverhomedom = &host_domain($serverhomeID);
 1533:     my %defdomdefaults = &get_domain_defaults($serverhomedom);
 1534:     if (ref($defdomdefaults{'offloadnow'}) eq 'HASH') {
 1535:         if ($defdomdefaults{'offloadnow'}{$try_server}) {
 1536:             $canhost = 0;
 1537:         }
 1538:     }
 1539:     if ($canhost) {
 1540:         if (ref($defdomdefaults{'offloadoth'}) eq 'HASH') {
 1541:             if ($defdomdefaults{'offloadoth'}{$try_server}) {
 1542:                 unless (&shared_institution($udom,$try_server)) {
 1543:                     $canhost = 0;
 1544:                 }
 1545:             }
 1546:         }
 1547:     }
 1548:     if (($canhost) && ($uint_dom)) {
 1549:         my @intdoms;
 1550:         my $internet_names = &get_internet_names($try_server);
 1551:         if (ref($internet_names) eq 'ARRAY') {
 1552:             @intdoms = @{$internet_names};
 1553:         }
 1554:         unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
 1555:             my $remoterev = &get_server_loncaparev(undef,$try_server);
 1556:             $canhost = &can_host_session($udom,$try_server,$remoterev,
 1557:                                          $remotesessions,
 1558:                                          $defdomdefaults{'hostedsessions'});
 1559:         }
 1560:     }
 1561:     return $canhost;
 1562: }
 1563: 
 1564: sub this_host_spares {
 1565:     my ($dom) = @_;
 1566:     my ($dom_in_use,$lonhost_in_use,$result);
 1567:     my @hosts = &current_machine_ids();
 1568:     foreach my $lonhost (@hosts) {
 1569:         if (&host_domain($lonhost) eq $dom) {
 1570:             $dom_in_use = $dom;
 1571:             $lonhost_in_use = $lonhost;
 1572:             last;
 1573:         }
 1574:     }
 1575:     if ($dom_in_use ne '') {
 1576:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
 1577:     }
 1578:     if (ref($result) ne 'HASH') {
 1579:         $lonhost_in_use = $perlvar{'lonHostID'};
 1580:         $dom_in_use = &host_domain($lonhost_in_use);
 1581:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
 1582:         if (ref($result) ne 'HASH') {
 1583:             $result = \%spareid;
 1584:         }
 1585:     }
 1586:     return $result;
 1587: }
 1588: 
 1589: sub spares_for_offload  {
 1590:     my ($dom_in_use,$lonhost_in_use) = @_;
 1591:     my ($result,$cached)=&is_cached_new('spares',$dom_in_use);
 1592:     if (defined($cached)) {
 1593:         return $result;
 1594:     } else {
 1595:         my $cachetime = 60*60*24;
 1596:         my %domconfig =
 1597:             &get_dom('configuration',['usersessions'],$dom_in_use);
 1598:         if (ref($domconfig{'usersessions'}) eq 'HASH') {
 1599:             if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
 1600:                 if (ref($domconfig{'usersessions'}{'spares'}{$lonhost_in_use}) eq 'HASH') {
 1601:                     return &do_cache_new('spares',$dom_in_use,$domconfig{'usersessions'}{'spares'}{$lonhost_in_use},$cachetime);
 1602:                 }
 1603:             }
 1604:         }
 1605:     }
 1606:     return;
 1607: }
 1608: 
 1609: sub get_lonbalancer_config {
 1610:     my ($servers) = @_;
 1611:     my ($currbalancer,$currtargets);
 1612:     if (ref($servers) eq 'HASH') {
 1613:         foreach my $server (keys(%{$servers})) {
 1614:             my %what = (
 1615:                          spareid => 1,
 1616:                          perlvar => 1,
 1617:                        );
 1618:             my ($result,$returnhash) = &get_remote_globals($server,\%what);
 1619:             if ($result eq 'ok') {
 1620:                 if (ref($returnhash) eq 'HASH') {
 1621:                     if (ref($returnhash->{'perlvar'}) eq 'HASH') {
 1622:                         if ($returnhash->{'perlvar'}->{'lonBalancer'} eq 'yes') {
 1623:                             $currbalancer = $server;
 1624:                             $currtargets = {};
 1625:                             if (ref($returnhash->{'spareid'}) eq 'HASH') {
 1626:                                 if (ref($returnhash->{'spareid'}->{'primary'}) eq 'ARRAY') {
 1627:                                     $currtargets->{'primary'} = $returnhash->{'spareid'}->{'primary'};
 1628:                                 }
 1629:                                 if (ref($returnhash->{'spareid'}->{'default'}) eq 'ARRAY') {
 1630:                                     $currtargets->{'default'} = $returnhash->{'spareid'}->{'default'};
 1631:                                 }
 1632:                             }
 1633:                             last;
 1634:                         }
 1635:                     }
 1636:                 }
 1637:             }
 1638:         }
 1639:     }
 1640:     return ($currbalancer,$currtargets);
 1641: }
 1642: 
 1643: sub check_loadbalancing {
 1644:     my ($uname,$udom,$caller) = @_;
 1645:     my ($is_balancer,$currtargets,$currrules,$dom_in_use,$homeintdom,
 1646:         $rule_in_effect,$offloadto,$otherserver,$setcookie,$dom_balancers);
 1647:     my $lonhost = $perlvar{'lonHostID'};
 1648:     my @hosts = &current_machine_ids();
 1649:     my $uprimary_id = &domain($udom,'primary');
 1650:     my $uintdom = &internet_dom($uprimary_id);
 1651:     my $intdom = &internet_dom($lonhost);
 1652:     my $serverhomedom = &host_domain($lonhost);
 1653:     my $domneedscache;
 1654:     my $cachetime = 60*60*24;
 1655: 
 1656:     if (($uintdom ne '') && ($uintdom eq $intdom)) {
 1657:         $dom_in_use = $udom;
 1658:         $homeintdom = 1;
 1659:     } else {
 1660:         $dom_in_use = $serverhomedom;
 1661:     }
 1662:     my ($result,$cached)=&is_cached_new('loadbalancing',$dom_in_use);
 1663:     unless (defined($cached)) {
 1664:         my %domconfig =
 1665:             &get_dom('configuration',['loadbalancing'],$dom_in_use);
 1666:         if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
 1667:             $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
 1668:         } else {
 1669:             $domneedscache = $dom_in_use;
 1670:         }
 1671:     }
 1672:     if (ref($result) eq 'HASH') {
 1673:         ($is_balancer,$currtargets,$currrules,$setcookie,$dom_balancers) =
 1674:             &check_balancer_result($result,@hosts);
 1675:         if ($is_balancer) {
 1676:             if (ref($currrules) eq 'HASH') {
 1677:                 if ($homeintdom) {
 1678:                     if ($uname ne '') {
 1679:                         if (($currrules->{'_LC_adv'} ne '') || ($currrules->{'_LC_author'} ne '')) {
 1680:                             my ($is_adv,$is_author) = &is_advanced_user($udom,$uname);
 1681:                             if (($currrules->{'_LC_author'} ne '') && ($is_author)) {
 1682:                                 $rule_in_effect = $currrules->{'_LC_author'};
 1683:                             } elsif (($currrules->{'_LC_adv'} ne '') && ($is_adv)) {
 1684:                                 $rule_in_effect = $currrules->{'_LC_adv'}
 1685:                             }
 1686:                         }
 1687:                         if ($rule_in_effect eq '') {
 1688:                             my %userenv = &userenvironment($udom,$uname,'inststatus');
 1689:                             if ($userenv{'inststatus'} ne '') {
 1690:                                 my @statuses = map { &unescape($_); } split(/:/,$userenv{'inststatus'});
 1691:                                 my ($othertitle,$usertypes,$types) =
 1692:                                     &Apache::loncommon::sorted_inst_types($udom);
 1693:                                 if (ref($types) eq 'ARRAY') {
 1694:                                     foreach my $type (@{$types}) {
 1695:                                         if (grep(/^\Q$type\E$/,@statuses)) {
 1696:                                             if (exists($currrules->{$type})) {
 1697:                                                 $rule_in_effect = $currrules->{$type};
 1698:                                             }
 1699:                                         }
 1700:                                     }
 1701:                                 }
 1702:                             } else {
 1703:                                 if (exists($currrules->{'default'})) {
 1704:                                     $rule_in_effect = $currrules->{'default'};
 1705:                                 }
 1706:                             }
 1707:                         }
 1708:                     } else {
 1709:                         if (exists($currrules->{'default'})) {
 1710:                             $rule_in_effect = $currrules->{'default'};
 1711:                         }
 1712:                     }
 1713:                 } else {
 1714:                     if ($currrules->{'_LC_external'} ne '') {
 1715:                         $rule_in_effect = $currrules->{'_LC_external'};
 1716:                     }
 1717:                 }
 1718:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
 1719:                                                        $uname,$udom);
 1720:             }
 1721:         }
 1722:     } elsif (($homeintdom) && ($udom ne $serverhomedom)) {
 1723:         ($result,$cached)=&is_cached_new('loadbalancing',$serverhomedom);
 1724:         unless (defined($cached)) {
 1725:             my %domconfig =
 1726:                 &get_dom('configuration',['loadbalancing'],$serverhomedom);
 1727:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
 1728:                 $result = &do_cache_new('loadbalancing',$serverhomedom,$domconfig{'loadbalancing'},$cachetime);
 1729:             } else {
 1730:                 $domneedscache = $serverhomedom;
 1731:             }
 1732:         }
 1733:         if (ref($result) eq 'HASH') {
 1734:             ($is_balancer,$currtargets,$currrules,$setcookie,$dom_balancers) =
 1735:                 &check_balancer_result($result,@hosts);
 1736:             if ($is_balancer) {
 1737:                 if (ref($currrules) eq 'HASH') {
 1738:                     if ($currrules->{'_LC_internetdom'} ne '') {
 1739:                         $rule_in_effect = $currrules->{'_LC_internetdom'};
 1740:                     }
 1741:                 }
 1742:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
 1743:                                                        $uname,$udom);
 1744:             }
 1745:         } else {
 1746:             if ($perlvar{'lonBalancer'} eq 'yes') {
 1747:                 $is_balancer = 1;
 1748:                 $offloadto = &this_host_spares($dom_in_use);
 1749:             }
 1750:             unless (defined($cached)) {
 1751:                 $domneedscache = $serverhomedom;
 1752:             }
 1753:         }
 1754:     } else {
 1755:         if ($perlvar{'lonBalancer'} eq 'yes') {
 1756:             $is_balancer = 1;
 1757:             $offloadto = &this_host_spares($dom_in_use);
 1758:         }
 1759:         unless (defined($cached)) {
 1760:             $domneedscache = $serverhomedom;
 1761:         }
 1762:     }
 1763:     if ($domneedscache) {
 1764:         &do_cache_new('loadbalancing',$domneedscache,$is_balancer,$cachetime);
 1765:     }
 1766:     if (($is_balancer) && ($caller ne 'switchserver')) {
 1767:         my $lowest_load = 30000;
 1768:         if (ref($offloadto) eq 'HASH') {
 1769:             if (ref($offloadto->{'primary'}) eq 'ARRAY') {
 1770:                 foreach my $try_server (@{$offloadto->{'primary'}}) {
 1771:                     ($otherserver,$lowest_load) =
 1772:                         &compare_server_load($try_server,$otherserver,$lowest_load);
 1773:                 }
 1774:             }
 1775:             my $found_server = ($otherserver ne '' && $lowest_load < 100);
 1776: 
 1777:             if (!$found_server) {
 1778:                 if (ref($offloadto->{'default'}) eq 'ARRAY') {
 1779:                     foreach my $try_server (@{$offloadto->{'default'}}) {
 1780:                         ($otherserver,$lowest_load) =
 1781:                             &compare_server_load($try_server,$otherserver,$lowest_load);
 1782:                     }
 1783:                 }
 1784:             }
 1785:         } elsif (ref($offloadto) eq 'ARRAY') {
 1786:             if (@{$offloadto} == 1) {
 1787:                 $otherserver = $offloadto->[0];
 1788:             } elsif (@{$offloadto} > 1) {
 1789:                 foreach my $try_server (@{$offloadto}) {
 1790:                     ($otherserver,$lowest_load) =
 1791:                         &compare_server_load($try_server,$otherserver,$lowest_load);
 1792:                 }
 1793:             }
 1794:         }
 1795:         unless ($caller eq 'login') {
 1796:             if (($otherserver ne '') && (grep(/^\Q$otherserver\E$/,@hosts))) {
 1797:                 $is_balancer = 0;
 1798:                 if ($uname ne '' && $udom ne '') {
 1799:                     if (($env{'user.name'} eq $uname) && ($env{'user.domain'} eq $udom)) {
 1800:                         &appenv({'user.loadbalexempt'     => $lonhost,
 1801:                                  'user.loadbalcheck.time' => time});
 1802:                     }
 1803:                 }
 1804:             }
 1805:         }
 1806:     }
 1807:     if (($is_balancer) && (!$homeintdom)) {
 1808:         undef($setcookie);
 1809:     }
 1810:     return ($is_balancer,$otherserver,$setcookie,$offloadto,$dom_balancers);
 1811: }
 1812: 
 1813: sub check_balancer_result {
 1814:     my ($result,@hosts) = @_;
 1815:     my ($is_balancer,$currtargets,$currrules,$setcookie,$dom_balancers);
 1816:     if (ref($result) eq 'HASH') {
 1817:         if ($result->{'lonhost'} ne '') {
 1818:             my $currbalancer = $result->{'lonhost'};
 1819:             if (grep(/^\Q$currbalancer\E$/,@hosts)) {
 1820:                 $is_balancer = 1;
 1821:                 $currtargets = $result->{'targets'};
 1822:                 $currrules = $result->{'rules'};
 1823:             }
 1824:             $dom_balancers = $currbalancer;
 1825:         } else {
 1826:             if (keys(%{$result})) {
 1827:                 foreach my $key (keys(%{$result})) {
 1828:                     if (($key ne '') && (grep(/^\Q$key\E$/,@hosts)) &&
 1829:                         (ref($result->{$key}) eq 'HASH')) {
 1830:                         $is_balancer = 1;
 1831:                         $currrules = $result->{$key}{'rules'};
 1832:                         $currtargets = $result->{$key}{'targets'};
 1833:                         $setcookie = $result->{$key}{'cookie'};
 1834:                         last;
 1835:                     }
 1836:                 }
 1837:                 $dom_balancers = join(',',sort(keys(%{$result})));
 1838:             }
 1839:         }
 1840:     }
 1841:     return ($is_balancer,$currtargets,$currrules,$setcookie,$dom_balancers);
 1842: }
 1843: 
 1844: sub get_loadbalancer_targets {
 1845:     my ($rule_in_effect,$currtargets,$uname,$udom) = @_;
 1846:     my $offloadto;
 1847:     if ($rule_in_effect eq 'none') {
 1848:         return [$perlvar{'lonHostID'}];
 1849:     } elsif ($rule_in_effect eq '') {
 1850:         $offloadto = $currtargets;
 1851:     } else {
 1852:         if ($rule_in_effect eq 'homeserver') {
 1853:             my $homeserver = &homeserver($uname,$udom);
 1854:             if ($homeserver ne 'no_host') {
 1855:                 $offloadto = [$homeserver];
 1856:             }
 1857:         } elsif ($rule_in_effect eq 'externalbalancer') {
 1858:             my %domconfig =
 1859:                 &get_dom('configuration',['loadbalancing'],$udom);
 1860:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
 1861:                 if ($domconfig{'loadbalancing'}{'lonhost'} ne '') {
 1862:                     if (&hostname($domconfig{'loadbalancing'}{'lonhost'}) ne '') {
 1863:                         $offloadto = [$domconfig{'loadbalancing'}{'lonhost'}];
 1864:                     }
 1865:                 }
 1866:             } else {
 1867:                 my %servers = &internet_dom_servers($udom);
 1868:                 my ($remotebalancer,$remotetargets) = &get_lonbalancer_config(\%servers);
 1869:                 if (&hostname($remotebalancer) ne '') {
 1870:                     $offloadto = [$remotebalancer];
 1871:                 }
 1872:             }
 1873:         } elsif (&hostname($rule_in_effect) ne '') {
 1874:             $offloadto = [$rule_in_effect];
 1875:         }
 1876:     }
 1877:     return $offloadto;
 1878: }
 1879: 
 1880: sub internet_dom_servers {
 1881:     my ($dom) = @_;
 1882:     my (%uniqservers,%servers);
 1883:     my $primaryserver = &hostname(&domain($dom,'primary'));
 1884:     my @machinedoms = &machine_domains($primaryserver);
 1885:     foreach my $mdom (@machinedoms) {
 1886:         my %currservers = %servers;
 1887:         my %server = &get_servers($mdom);
 1888:         %servers = (%currservers,%server);
 1889:     }
 1890:     my %by_hostname;
 1891:     foreach my $id (keys(%servers)) {
 1892:         push(@{$by_hostname{$servers{$id}}},$id);
 1893:     }
 1894:     foreach my $hostname (sort(keys(%by_hostname))) {
 1895:         if (@{$by_hostname{$hostname}} > 1) {
 1896:             my $match = 0;
 1897:             foreach my $id (@{$by_hostname{$hostname}}) {
 1898:                 if (&host_domain($id) eq $dom) {
 1899:                     $uniqservers{$id} = $hostname;
 1900:                     $match = 1;
 1901:                 }
 1902:             }
 1903:             unless ($match) {
 1904:                 $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
 1905:             }
 1906:         } else {
 1907:             $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
 1908:         }
 1909:     }
 1910:     return %uniqservers;
 1911: }
 1912: 
 1913: sub trusted_domains {
 1914:     my ($cmdtype,$calldom) = @_;
 1915:     my ($trusted,$untrusted);
 1916:     if (&domain($calldom) eq '') {
 1917:         return ($trusted,$untrusted);
 1918:     }
 1919:     unless ($cmdtype =~ /^(content|shared|enroll|coaurem|othcoau|domroles|catalog|reqcrs|msg)$/) {
 1920:         return ($trusted,$untrusted);
 1921:     }
 1922:     my $callprimary = &domain($calldom,'primary');
 1923:     my $intcalldom = &internet_dom($callprimary);
 1924:     if ($intcalldom eq '') {
 1925:         return ($trusted,$untrusted);
 1926:     }
 1927: 
 1928:     my ($trustconfig,$cached)=&is_cached_new('trust',$calldom);
 1929:     unless (defined($cached)) {
 1930:         my %domconfig = &get_dom('configuration',['trust'],$calldom);
 1931:         &do_cache_new('trust',$calldom,$domconfig{'trust'},3600);
 1932:         $trustconfig = $domconfig{'trust'};
 1933:     }
 1934:     if (ref($trustconfig)) {
 1935:         my (%possexc,%possinc,@allexc,@allinc); 
 1936:         if (ref($trustconfig->{$cmdtype}) eq 'HASH') {
 1937:             if (ref($trustconfig->{$cmdtype}->{'exc'}) eq 'ARRAY') {
 1938:                 map { $possexc{$_} = 1; } @{$trustconfig->{$cmdtype}->{'exc'}}; 
 1939:             }
 1940:             if (ref($trustconfig->{$cmdtype}->{'inc'}) eq 'ARRAY') {
 1941:                 $possinc{$intcalldom} = 1;
 1942:                 map { $possinc{$_} = 1; } @{$trustconfig->{$cmdtype}->{'inc'}};
 1943:             }
 1944:         }
 1945:         if (keys(%possexc)) {
 1946:             if (keys(%possinc)) {
 1947:                 foreach my $key (sort(keys(%possexc))) {
 1948:                     next if ($key eq $intcalldom);
 1949:                     unless ($possinc{$key}) {
 1950:                         push(@allexc,$key);
 1951:                     }
 1952:                 }
 1953:             } else {
 1954:                 @allexc = sort(keys(%possexc));
 1955:             }
 1956:         }
 1957:         if (keys(%possinc)) {
 1958:             $possinc{$intcalldom} = 1;
 1959:             @allinc = sort(keys(%possinc));
 1960:         }
 1961:         if ((@allexc > 0) || (@allinc > 0)) {
 1962:             my %doms_by_intdom;
 1963:             my %allintdoms = &all_host_intdom();
 1964:             my %alldoms = &all_host_domain();
 1965:             foreach my $key (%allintdoms) {
 1966:                 if (ref($doms_by_intdom{$allintdoms{$key}}) eq 'ARRAY') {
 1967:                     unless (grep(/^\Q$alldoms{$key}\E$/,@{$doms_by_intdom{$allintdoms{$key}}})) {
 1968:                         push(@{$doms_by_intdom{$allintdoms{$key}}},$alldoms{$key});
 1969:                     }
 1970:                 } else {
 1971:                     $doms_by_intdom{$allintdoms{$key}} = [$alldoms{$key}]; 
 1972:                 }
 1973:             }
 1974:             foreach my $exc (@allexc) {
 1975:                 if (ref($doms_by_intdom{$exc}) eq 'ARRAY') {
 1976:                     push(@{$untrusted},@{$doms_by_intdom{$exc}});
 1977:                 }
 1978:             }
 1979:             foreach my $inc (@allinc) {
 1980:                 if (ref($doms_by_intdom{$inc}) eq 'ARRAY') {
 1981:                     push(@{$trusted},@{$doms_by_intdom{$inc}});
 1982:                 }
 1983:             }
 1984:         }
 1985:     }
 1986:     return ($trusted,$untrusted);
 1987: }
 1988: 
 1989: sub will_trust {
 1990:     my ($cmdtype,$domain,$possdom) = @_;
 1991:     return 1 if ($domain eq $possdom);
 1992:     my ($trustedref,$untrustedref) = &trusted_domains($cmdtype,$possdom);
 1993:     my $willtrust; 
 1994:     if ((ref($trustedref) eq 'ARRAY') && (@{$trustedref} > 0)) {
 1995:         if (grep(/^\Q$domain\E$/,@{$trustedref})) {
 1996:             $willtrust = 1;
 1997:         }
 1998:     } elsif ((ref($untrustedref) eq 'ARRAY') && (@{$untrustedref} > 0)) {
 1999:         unless (grep(/^\Q$domain\E$/,@{$untrustedref})) {
 2000:             $willtrust = 1;
 2001:         }
 2002:     } else {
 2003:         $willtrust = 1;
 2004:     }
 2005:     return $willtrust;
 2006: }
 2007: 
 2008: # ---------------------- Find the homebase for a user from domain's lib servers
 2009: 
 2010: my %homecache;
 2011: sub homeserver {
 2012:     my ($uname,$udom,$ignoreBadCache)=@_;
 2013:     my $index="$uname:$udom";
 2014: 
 2015:     if (exists($homecache{$index})) { return $homecache{$index}; }
 2016: 
 2017:     my %servers = &get_servers($udom,'library');
 2018:     foreach my $tryserver (keys(%servers)) {
 2019:         next if ($ignoreBadCache ne 'true' && 
 2020: 		 exists($badServerCache{$tryserver}));
 2021: 
 2022: 	my $answer=reply("home:$udom:$uname",$tryserver);
 2023: 	if ($answer eq 'found') {
 2024: 	    delete($badServerCache{$tryserver}); 
 2025: 	    return $homecache{$index}=$tryserver;
 2026: 	} elsif ($answer eq 'no_host') {
 2027: 	    $badServerCache{$tryserver}=1;
 2028: 	}
 2029:     }    
 2030:     return 'no_host';
 2031: }
 2032: 
 2033: # ----- Find the usernames behind a list of student/employee IDs or clicker IDs
 2034: 
 2035: sub idget {
 2036:     my ($udom,$idsref,$namespace)=@_;
 2037:     my %returnhash=();
 2038:     my @ids=(); 
 2039:     if (ref($idsref) eq 'ARRAY') {
 2040:         @ids = @{$idsref};
 2041:     } else {
 2042:         return %returnhash; 
 2043:     }
 2044:     if ($namespace eq '') {
 2045:         $namespace = 'ids';
 2046:     }
 2047:     
 2048:     my %servers = &get_servers($udom,'library');
 2049:     foreach my $tryserver (keys(%servers)) {
 2050: 	my $idlist=join('&', map { &escape($_); } @ids);
 2051: 	if ($namespace eq 'ids') {
 2052: 	    $idlist=~tr/A-Z/a-z/;
 2053: 	}
 2054: 	my $reply;
 2055: 	if ($namespace eq 'ids') {
 2056: 	    $reply=&reply("idget:$udom:".$idlist,$tryserver);
 2057: 	} else {
 2058: 	    $reply=&reply("getdom:$udom:$namespace:$idlist",$tryserver);
 2059: 	}
 2060: 	my @answer=();
 2061: 	if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
 2062: 	    @answer=split(/\&/,$reply);
 2063: 	}                    ;
 2064: 	my $i;
 2065: 	for ($i=0;$i<=$#ids;$i++) {
 2066: 	    if ($answer[$i]) {
 2067: 		$returnhash{$ids[$i]}=&unescape($answer[$i]);
 2068: 	    }
 2069: 	}
 2070:     }
 2071:     return %returnhash;
 2072: }
 2073: 
 2074: # ------------------------------------- Find the IDs behind a list of usernames
 2075: 
 2076: sub idrget {
 2077:     my ($udom,@unames)=@_;
 2078:     my %returnhash=();
 2079:     foreach my $uname (@unames) {
 2080:         $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
 2081:     }
 2082:     return %returnhash;
 2083: }
 2084: 
 2085: # Store away a list of names and associated student/employee IDs or clicker IDs
 2086: 
 2087: sub idput {
 2088:     my ($udom,$idsref,$uhom,$namespace)=@_;
 2089:     my %servers=();
 2090:     my %ids=();
 2091:     my %byid = ();
 2092:     if (ref($idsref) eq 'HASH') {
 2093:         %ids=%{$idsref};
 2094:     }
 2095:     if ($namespace eq '') {
 2096:         $namespace = 'ids'; 
 2097:     }
 2098:     foreach my $uname (keys(%ids)) {
 2099: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
 2100:         if ($uhom eq '') {
 2101:             $uhom=&homeserver($uname,$udom);
 2102:         }
 2103:         if ($uhom ne 'no_host') {
 2104:             my $esc_unam=&escape($uname);
 2105:             if ($namespace eq 'ids') {
 2106:                 my $id=&escape($ids{$uname});
 2107:                 $id=~tr/A-Z/a-z/;
 2108:                 my $esc_unam=&escape($uname);
 2109:                 $servers{$uhom}.=$id.'='.$esc_unam.'&';
 2110:             } else {
 2111:                 my @currids = split(/,/,$ids{$uname});
 2112:                 foreach my $id (@currids) {
 2113:                     $byid{$uhom}{$id} .= $uname.',';
 2114:                 }
 2115:             }
 2116:         }
 2117:     }
 2118:     if ($namespace eq 'clickers') {
 2119:         foreach my $server (keys(%byid)) {
 2120:             if (ref($byid{$server}) eq 'HASH') {
 2121:                 foreach my $id (keys(%{$byid{$server}})) {
 2122:                     $byid{$server} =~ s/,$//;
 2123:                     $servers{$uhom}.=&escape($id).'='.&escape($byid{$server}).'&'; 
 2124:                 }
 2125:             }
 2126:         }
 2127:     }
 2128:     foreach my $server (keys(%servers)) {
 2129:         $servers{$server} =~ s/\&$//;
 2130:         if ($namespace eq 'ids') {     
 2131:             &critical('idput:'.$udom.':'.$servers{$server},$server);
 2132:         } else {
 2133:             &critical('updateclickers:'.$udom.':add:'.$servers{$server},$server);
 2134:         }
 2135:     }
 2136: }
 2137: 
 2138: # ------------- Delete unwanted student/employee IDs or clicker IDs from domain
 2139: 
 2140: sub iddel {
 2141:     my ($udom,$idshashref,$uhome,$namespace)=@_;
 2142:     my %result=();
 2143:     my %ids=();
 2144:     my %byid = ();
 2145:     if (ref($idshashref) eq 'HASH') {
 2146:         %ids=%{$idshashref};
 2147:     } else {
 2148:         return %result;
 2149:     }
 2150:     if ($namespace eq '') {
 2151:         $namespace = 'ids';
 2152:     }
 2153:     my %servers=();
 2154:     while (my ($id,$unamestr) = each(%ids)) {
 2155:         if ($namespace eq 'ids') {
 2156:             my $uhom = $uhome;
 2157:             if ($uhom eq '') { 
 2158:                 $uhom=&homeserver($unamestr,$udom);
 2159:             }
 2160:             if ($uhom ne 'no_host') {
 2161:                 $servers{$uhom}.='&'.&escape($id);
 2162:             }
 2163:          } else {
 2164:             my @curritems = split(/,/,$ids{$id});
 2165:             foreach my $uname (@curritems) {
 2166:                 my $uhom = $uhome;
 2167:                 if ($uhom eq '') {
 2168:                     $uhom=&homeserver($uname,$udom);
 2169:                 }
 2170:                 if ($uhom ne 'no_host') { 
 2171:                     $byid{$uhom}{$id} .= $uname.',';
 2172:                 }
 2173:             }
 2174:         }
 2175:     }
 2176:     if ($namespace eq 'clickers') {
 2177:         foreach my $server (keys(%byid)) {
 2178:             if (ref($byid{$server}) eq 'HASH') {
 2179:                 foreach my $id (keys(%{$byid{$server}})) {
 2180:                     $byid{$server}{$id} =~ s/,$//;
 2181:                     $servers{$server}.=&escape($id).'='.&escape($byid{$server}{$id}).'&';
 2182:                 }
 2183:             }
 2184:         }
 2185:     }
 2186:     foreach my $server (keys(%servers)) {
 2187:         $servers{$server} =~ s/\&$//;
 2188:         if ($namespace eq 'ids') {
 2189:             $result{$server} = &critical('iddel:'.$udom.':'.$servers{$server},$uhome);
 2190:         } elsif ($namespace eq 'clickers') {
 2191:             $result{$server} = &critical('updateclickers:'.$udom.':del:'.$servers{$server},$server);
 2192:         }
 2193:     }
 2194:     return %result;
 2195: }
 2196: 
 2197: # ----- Update clicker ID-to-username look-ups in clickers.db on library server 
 2198: 
 2199: sub updateclickers {
 2200:     my ($udom,$action,$idshashref,$uhome,$critical) = @_;
 2201:     my %clickers;
 2202:     if (ref($idshashref) eq 'HASH') {
 2203:         %clickers=%{$idshashref};
 2204:     } else {
 2205:         return;
 2206:     }
 2207:     my $items='';
 2208:     foreach my $item (keys(%clickers)) {
 2209:         $items.=&escape($item).'='.&escape($clickers{$item}).'&';
 2210:     }
 2211:     $items=~s/\&$//;
 2212:     my $request = "updateclickers:$udom:$action:$items";
 2213:     if ($critical) {
 2214:         return &critical($request,$uhome);
 2215:     } else {
 2216:         return &reply($request,$uhome);
 2217:     }
 2218: }
 2219: 
 2220: # ------------------------------dump from db file owned by domainconfig user
 2221: sub dump_dom {
 2222:     my ($namespace, $udom, $regexp) = @_;
 2223: 
 2224:     $udom ||= $env{'user.domain'};
 2225: 
 2226:     return () unless $udom;
 2227: 
 2228:     return &dump($namespace, $udom, &get_domainconfiguser($udom), $regexp);
 2229: }
 2230: 
 2231: # ------------------------------------------ get items from domain db files   
 2232: 
 2233: sub get_dom {
 2234:     my ($namespace,$storearr,$udom,$uhome,$encrypt)=@_;
 2235:     return if ($udom eq 'public');
 2236:     my $items='';
 2237:     foreach my $item (@$storearr) {
 2238:         $items.=&escape($item).'&';
 2239:     }
 2240:     $items=~s/\&$//;
 2241:     if (!$udom) {
 2242:         $udom=$env{'user.domain'};
 2243:         return if ($udom eq 'public');
 2244:         if (defined(&domain($udom,'primary'))) {
 2245:             $uhome=&domain($udom,'primary');
 2246:         } else {
 2247:             undef($uhome);
 2248:         }
 2249:     } else {
 2250:         if (!$uhome) {
 2251:             if (defined(&domain($udom,'primary'))) {
 2252:                 $uhome=&domain($udom,'primary');
 2253:             }
 2254:         }
 2255:     }
 2256:     if ($udom && $uhome && ($uhome ne 'no_host')) {
 2257:         my $rep;
 2258:         if (grep { $_ eq $uhome } &current_machine_ids()) {
 2259:             # domain information is hosted on this machine
 2260:             $rep = &LONCAPA::Lond::get_dom("getdom:$udom:$namespace:$items");
 2261:         } else {
 2262:             if ($encrypt) {
 2263:                 $rep=&reply("encrypt:egetdom:$udom:$namespace:$items",$uhome);
 2264:             } else {
 2265:                 $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
 2266:             }
 2267:         }
 2268:         my %returnhash;
 2269:         if ($rep eq '' || $rep =~ /^error: 2 /) {
 2270:             return %returnhash;
 2271:         }
 2272:         my @pairs=split(/\&/,$rep);
 2273:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
 2274:             return @pairs;
 2275:         }
 2276:         my $i=0;
 2277:         foreach my $item (@$storearr) {
 2278:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
 2279:             $i++;
 2280:         }
 2281:         return %returnhash;
 2282:     } else {
 2283:         &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
 2284:     }
 2285: }
 2286: 
 2287: # -------------------------------------------- put items in domain db files 
 2288: 
 2289: sub put_dom {
 2290:     my ($namespace,$storehash,$udom,$uhome,$encrypt)=@_;
 2291:     if (!$udom) {
 2292:         $udom=$env{'user.domain'};
 2293:         if (defined(&domain($udom,'primary'))) {
 2294:             $uhome=&domain($udom,'primary');
 2295:         } else {
 2296:             undef($uhome);
 2297:         }
 2298:     } else {
 2299:         if (!$uhome) {
 2300:             if (defined(&domain($udom,'primary'))) {
 2301:                 $uhome=&domain($udom,'primary');
 2302:             }
 2303:         }
 2304:     } 
 2305:     if ($udom && $uhome && ($uhome ne 'no_host')) {
 2306:         my $items='';
 2307:         foreach my $item (keys(%$storehash)) {
 2308:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 2309:         }
 2310:         $items=~s/\&$//;
 2311:         if ($encrypt) {
 2312:             return &reply("encrypt:putdom:$udom:$namespace:$items",$uhome);
 2313:         } else {
 2314:             return &reply("putdom:$udom:$namespace:$items",$uhome);
 2315:         }
 2316:     } else {
 2317:         &logthis("put_dom failed - no homeserver and/or domain");
 2318:     }
 2319: }
 2320: 
 2321: # --------------------- newput for items in db file owned by domainconfig user
 2322: sub newput_dom {
 2323:     my ($namespace,$storehash,$udom) = @_;
 2324:     my $result;
 2325:     if (!$udom) {
 2326:         $udom=$env{'user.domain'};
 2327:     }
 2328:     if ($udom) {
 2329:         my $uname = &get_domainconfiguser($udom);
 2330:         $result = &newput($namespace,$storehash,$udom,$uname);
 2331:     }
 2332:     return $result;
 2333: }
 2334: 
 2335: # --------------------- delete for items in db file owned by domainconfig user
 2336: sub del_dom {
 2337:     my ($namespace,$storearr,$udom)=@_;
 2338:     if (ref($storearr) eq 'ARRAY') {
 2339:         if (!$udom) {
 2340:             $udom=$env{'user.domain'};
 2341:         }
 2342:         if ($udom) {
 2343:             my $uname = &get_domainconfiguser($udom); 
 2344:             return &del($namespace,$storearr,$udom,$uname);
 2345:         }
 2346:     }
 2347: }
 2348: 
 2349: sub store_dom {
 2350:     my ($storehash,$id,$namespace,$dom,$home,$encrypt) = @_;
 2351:     $$storehash{'ip'}=&get_requestor_ip();
 2352:     $$storehash{'host'}=$perlvar{'lonHostID'};
 2353:     my $namevalue='';
 2354:     foreach my $key (keys(%{$storehash})) {
 2355:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 2356:     }
 2357:     $namevalue=~s/\&$//;
 2358:     if (grep { $_ eq $home } current_machine_ids()) {
 2359:         return LONCAPA::Lond::store_dom("storedom:$dom:$namespace:$id:$namevalue");
 2360:     } else {
 2361:         if ($namespace eq 'private') {
 2362:             return 'refused';
 2363:         } elsif ($encrypt) {
 2364:             return reply("encrypt:storedom:$dom:$namespace:$id:$namevalue",$home);
 2365:         } else {
 2366:             return reply("storedom:$dom:$namespace:$id:$namevalue",$home);
 2367:         }
 2368:     }
 2369: }
 2370: 
 2371: sub restore_dom {
 2372:     my ($id,$namespace,$dom,$home,$encrypt) = @_;
 2373:     my $answer;
 2374:     if (grep { $_ eq $home } current_machine_ids()) {
 2375:         $answer = LONCAPA::Lond::restore_dom("restoredom:$dom:$namespace:$id");
 2376:     } elsif ($namespace ne 'private') {
 2377:         if ($encrypt) {
 2378:             $answer=&reply("encrypt:restoredom:$dom:$namespace:$id",$home);
 2379:         } else {
 2380:             $answer=&reply("restoredom:$dom:$namespace:$id",$home);
 2381:         }
 2382:     }
 2383:     my %returnhash=();
 2384:     unless (($answer eq '') || ($answer eq 'con_lost') || ($answer eq 'refused') || 
 2385:             ($answer eq 'unknown_cmd') || ($answer eq 'rejected')) {
 2386:         foreach my $line (split(/\&/,$answer)) {
 2387:             my ($name,$value)=split(/\=/,$line);
 2388:             $returnhash{&unescape($name)}=&thaw_unescape($value);
 2389:         }
 2390:         my $version;
 2391:         for ($version=1;$version<=$returnhash{'version'};$version++) {
 2392:             foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
 2393:                 $returnhash{$item}=$returnhash{$version.':'.$item};
 2394:             }
 2395:         }
 2396:     }
 2397:     return %returnhash;
 2398: }
 2399: 
 2400: # ----------------------------------construct domainconfig user for a domain 
 2401: sub get_domainconfiguser {
 2402:     my ($udom) = @_;
 2403:     return $udom.'-domainconfig';
 2404: }
 2405: 
 2406: sub retrieve_inst_usertypes {
 2407:     my ($udom) = @_;
 2408:     my (%returnhash,@order);
 2409:     my %domdefs = &get_domain_defaults($udom);
 2410:     if ((ref($domdefs{'inststatustypes'}) eq 'HASH') && 
 2411:         (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
 2412:         return ($domdefs{'inststatustypes'},$domdefs{'inststatusorder'});
 2413:     } else {
 2414:         if (defined(&domain($udom,'primary'))) {
 2415:             my $uhome=&domain($udom,'primary');
 2416:             my $rep=&reply("inst_usertypes:$udom",$uhome);
 2417:             if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
 2418:                 &logthis("retrieve_inst_usertypes failed - $rep returned from $uhome in domain: $udom");
 2419:                 return (\%returnhash,\@order);
 2420:             }
 2421:             my ($hashitems,$orderitems) = split(/:/,$rep); 
 2422:             my @pairs=split(/\&/,$hashitems);
 2423:             foreach my $item (@pairs) {
 2424:                 my ($key,$value)=split(/=/,$item,2);
 2425:                 $key = &unescape($key);
 2426:                 next if ($key =~ /^error: 2 /);
 2427:                 $returnhash{$key}=&thaw_unescape($value);
 2428:             }
 2429:             my @esc_order = split(/\&/,$orderitems);
 2430:             foreach my $item (@esc_order) {
 2431:                 push(@order,&unescape($item));
 2432:             }
 2433:         } else {
 2434:             &logthis("retrieve_inst_usertypes failed - no primary domain server for $udom");
 2435:         }
 2436:         return (\%returnhash,\@order);
 2437:     }
 2438: }
 2439: 
 2440: sub is_domainimage {
 2441:     my ($url) = @_;
 2442:     if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo|login)/+[^/]-) {
 2443:         if (&domain($1) ne '') {
 2444:             return '1';
 2445:         }
 2446:     }
 2447:     return;
 2448: }
 2449: 
 2450: sub inst_directory_query {
 2451:     my ($srch) = @_;
 2452:     my $udom = $srch->{'srchdomain'};
 2453:     my %results;
 2454:     my $homeserver = &domain($udom,'primary');
 2455:     my $outcome;
 2456:     if ($homeserver ne '') {
 2457:         unless ($homeserver eq $perlvar{'lonHostID'}) {
 2458:             if ($srch->{'srchby'} eq 'email') {
 2459:                 my $lcrev = &get_server_loncaparev($udom,$homeserver);
 2460:                 my ($major,$minor) = ($lcrev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
 2461:                 if (($major eq '' && $minor eq '') || ($major < 2) ||
 2462:                     (($major == 2) && ($minor < 12))) {
 2463:                     return;
 2464:                 }
 2465:             }
 2466:         }
 2467: 	my $queryid=&reply("querysend:instdirsearch:".
 2468: 			   &escape($srch->{'srchby'}).':'.
 2469: 			   &escape($srch->{'srchterm'}).':'.
 2470: 			   &escape($srch->{'srchtype'}),$homeserver);
 2471: 	my $host=&hostname($homeserver);
 2472: 	if ($queryid !~/^\Q$host\E\_/) {
 2473: 	    &logthis('institutional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.' in domain '.$udom);
 2474: 	    return;
 2475: 	}
 2476: 	my $response = &get_query_reply($queryid);
 2477: 	my $maxtries = 5;
 2478: 	my $tries = 1;
 2479: 	while (($response=~/^timeout/) && ($tries < $maxtries)) {
 2480: 	    $response = &get_query_reply($queryid);
 2481: 	    $tries ++;
 2482: 	}
 2483: 
 2484:         if (!&error($response) && $response ne 'refused') {
 2485:             if ($response eq 'unavailable') {
 2486:                 $outcome = $response;
 2487:             } else {
 2488:                 $outcome = 'ok';
 2489:                 my @matches = split(/\n/,$response);
 2490:                 foreach my $match (@matches) {
 2491:                     my ($key,$value) = split(/=/,$match);
 2492:                     $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
 2493:                 }
 2494:             }
 2495:         }
 2496:     }
 2497:     return ($outcome,%results);
 2498: }
 2499: 
 2500: sub usersearch {
 2501:     my ($srch) = @_;
 2502:     my $dom = $srch->{'srchdomain'};
 2503:     my %results;
 2504:     my %libserv = &all_library();
 2505:     my $query = 'usersearch';
 2506:     foreach my $tryserver (keys(%libserv)) {
 2507:         if (&host_domain($tryserver) eq $dom) {
 2508:             unless ($tryserver eq $perlvar{'lonHostID'}) {
 2509:                 if ($srch->{'srchby'} eq 'email') {
 2510:                     my $lcrev = &get_server_loncaparev($dom,$tryserver);
 2511:                     my ($major,$minor) = ($lcrev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
 2512:                     next if (($major eq '' && $minor eq '') || ($major < 2) ||
 2513:                              (($major == 2) && ($minor < 12)));
 2514:                 }
 2515:             }
 2516:             my $host=&hostname($tryserver);
 2517:             my $queryid=
 2518:                 &reply("querysend:".&escape($query).':'.
 2519:                        &escape($srch->{'srchby'}).':'.
 2520:                        &escape($srch->{'srchtype'}).':'.
 2521:                        &escape($srch->{'srchterm'}),$tryserver);
 2522:             if ($queryid !~/^\Q$host\E\_/) {
 2523:                 &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
 2524:                 next;
 2525:             }
 2526:             my $reply = &get_query_reply($queryid);
 2527:             my $maxtries = 1;
 2528:             my $tries = 1;
 2529:             while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 2530:                 $reply = &get_query_reply($queryid);
 2531:                 $tries ++;
 2532:             }
 2533:             if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 2534:                 &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') -  maxtries: '.$maxtries.' tries: '.$tries);
 2535:             } else {
 2536:                 my @matches;
 2537:                 if ($reply =~ /\n/) {
 2538:                     @matches = split(/\n/,$reply);
 2539:                 } else {
 2540:                     @matches = split(/\&/,$reply);
 2541:                 }
 2542:                 foreach my $match (@matches) {
 2543:                     my ($uname,$udom,%userhash);
 2544:                     foreach my $entry (split(/:/,$match)) {
 2545:                         my ($key,$value) =
 2546:                             map {&unescape($_);} split(/=/,$entry);
 2547:                         $userhash{$key} = $value;
 2548:                         if ($key eq 'username') {
 2549:                             $uname = $value;
 2550:                         } elsif ($key eq 'domain') {
 2551:                             $udom = $value;
 2552:                         }
 2553:                     }
 2554:                     $results{$uname.':'.$udom} = \%userhash;
 2555:                 }
 2556:             }
 2557:         }
 2558:     }
 2559:     return %results;
 2560: }
 2561: 
 2562: sub get_instuser {
 2563:     my ($udom,$uname,$id) = @_;
 2564:     my $homeserver = &domain($udom,'primary');
 2565:     my ($outcome,%results);
 2566:     if ($homeserver ne '') {
 2567:         my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
 2568:                            &escape($id).':'.&escape($udom),$homeserver);
 2569:         my $host=&hostname($homeserver);
 2570:         if ($queryid !~/^\Q$host\E\_/) {
 2571:             &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
 2572:             return;
 2573:         }
 2574:         my $response = &get_query_reply($queryid);
 2575:         my $maxtries = 5;
 2576:         my $tries = 1;
 2577:         while (($response=~/^timeout/) && ($tries < $maxtries)) {
 2578:             $response = &get_query_reply($queryid);
 2579:             $tries ++;
 2580:         }
 2581:         if (!&error($response) && $response ne 'refused') {
 2582:             if ($response eq 'unavailable') {
 2583:                 $outcome = $response;
 2584:             } else {
 2585:                 $outcome = 'ok';
 2586:                 my @matches = split(/\n/,$response);
 2587:                 foreach my $match (@matches) {
 2588:                     my ($key,$value) = split(/=/,$match);
 2589:                     $results{&unescape($key)} = &thaw_unescape($value);
 2590:                 }
 2591:             }
 2592:         }
 2593:     }
 2594:     my %userinfo;
 2595:     if (ref($results{$uname}) eq 'HASH') {
 2596:         %userinfo = %{$results{$uname}};
 2597:     } 
 2598:     return ($outcome,%userinfo);
 2599: }
 2600: 
 2601: sub get_multiple_instusers {
 2602:     my ($udom,$users,$caller) = @_;
 2603:     my ($outcome,$results);
 2604:     if (ref($users) eq 'HASH') {
 2605:         my $count = keys(%{$users}); 
 2606:         my $requested = &freeze_escape($users);
 2607:         my $homeserver = &domain($udom,'primary');
 2608:         if ($homeserver ne '') {
 2609:             my $queryid=&reply('querysend:getmultinstusers:::'.$caller.'='.$requested,$homeserver);
 2610:             my $host=&hostname($homeserver);
 2611:             if ($queryid !~/^\Q$host\E\_/) {
 2612:                 &logthis('get_multiple_instusers invalid queryid: '.$queryid.
 2613:                          ' for host: '.$homeserver.'in domain '.$udom);
 2614:                 return ($outcome,$results);
 2615:             }
 2616:             my $response = &get_query_reply($queryid);
 2617:             my $maxtries = 5;
 2618:             if ($count > 100) {
 2619:                 $maxtries = 1+int($count/20);
 2620:             }
 2621:             my $tries = 1;
 2622:             while (($response=~/^timeout/) && ($tries <= $maxtries)) {
 2623:                 $response = &get_query_reply($queryid);
 2624:                 $tries ++;
 2625:             }
 2626:             if ($response eq '') {
 2627:                 $results = {};
 2628:                 foreach my $key (keys(%{$users})) {
 2629:                     my ($uname,$id);
 2630:                     if ($caller eq 'id') {
 2631:                         $id = $key;
 2632:                     } else {
 2633:                         $uname = $key;
 2634:                     }
 2635:                     my ($resp,%info) = &get_instuser($udom,$uname,$id);
 2636:                     $outcome = $resp;
 2637:                     if ($resp eq 'ok') {
 2638:                         %{$results} = (%{$results}, %info);
 2639:                     } else {
 2640:                         last;
 2641:                     }
 2642:                 }
 2643:             } elsif(!&error($response) && ($response ne 'refused')) {
 2644:                 if (($response eq 'unavailable') || ($response eq 'invalid') || ($response eq 'timeout')) {
 2645:                     $outcome = $response;
 2646:                 } else {
 2647:                     ($outcome,my $userdata) = split(/=/,$response,2);
 2648:                     if ($outcome eq 'ok') {
 2649:                         $results = &thaw_unescape($userdata); 
 2650:                     }
 2651:                 }
 2652:             }
 2653:         }
 2654:     }
 2655:     return ($outcome,$results);
 2656: }
 2657: 
 2658: sub inst_rulecheck {
 2659:     my ($udom,$uname,$id,$item,$rules) = @_;
 2660:     my %returnhash;
 2661:     if ($udom ne '') {
 2662:         if (ref($rules) eq 'ARRAY') {
 2663:             @{$rules} = map {&escape($_);} (@{$rules});
 2664:             my $rulestr = join(':',@{$rules});
 2665:             my $homeserver=&domain($udom,'primary');
 2666:             if (($homeserver ne '') && ($homeserver ne 'no_host')) {
 2667:                 my $response;
 2668:                 if ($item eq 'username') {                
 2669:                     $response=&unescape(&reply('instrulecheck:'.&escape($udom).
 2670:                                               ':'.&escape($uname).':'.$rulestr,
 2671:                                               $homeserver));
 2672:                 } elsif ($item eq 'id') {
 2673:                     $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
 2674:                                               ':'.&escape($id).':'.$rulestr,
 2675:                                               $homeserver));
 2676:                 } elsif ($item eq 'selfcreate') {
 2677:                     $response=&unescape(&reply('instselfcreatecheck:'.
 2678:                                                &escape($udom).':'.&escape($uname).
 2679:                                               ':'.$rulestr,$homeserver));
 2680:                 } elsif ($item eq 'unamemap') {
 2681:                     $response=&unescape(&reply('instunamemapcheck:'.
 2682:                                                &escape($udom).':'.&escape($uname).
 2683:                                               ':'.$rulestr,$homeserver));
 2684:                 }
 2685:                 if ($response ne 'refused') {
 2686:                     my @pairs=split(/\&/,$response);
 2687:                     foreach my $item (@pairs) {
 2688:                         my ($key,$value)=split(/=/,$item,2);
 2689:                         $key = &unescape($key);
 2690:                         next if ($key =~ /^error: 2 /);
 2691:                         $returnhash{$key}=&thaw_unescape($value);
 2692:                     }
 2693:                 }
 2694:             }
 2695:         }
 2696:     }
 2697:     return %returnhash;
 2698: }
 2699: 
 2700: sub inst_userrules {
 2701:     my ($udom,$check) = @_;
 2702:     my (%ruleshash,@ruleorder);
 2703:     if ($udom ne '') {
 2704:         my $homeserver=&domain($udom,'primary');
 2705:         if (($homeserver ne '') && ($homeserver ne 'no_host')) {
 2706:             my $response;
 2707:             if ($check eq 'id') {
 2708:                 $response=&reply('instidrules:'.&escape($udom),
 2709:                                  $homeserver);
 2710:             } elsif ($check eq 'email') {
 2711:                 $response=&reply('instemailrules:'.&escape($udom),
 2712:                                  $homeserver);
 2713:             } elsif ($check eq 'unamemap') {
 2714:                 $response=&reply('unamemaprules:'.&escape($udom),
 2715:                                  $homeserver); 
 2716:             } else {
 2717:                 $response=&reply('instuserrules:'.&escape($udom),
 2718:                                  $homeserver);
 2719:             }
 2720:             if (($response ne 'refused') && ($response ne 'error') && 
 2721:                 ($response ne 'unknown_cmd') && 
 2722:                 ($response ne 'no_such_host')) {
 2723:                 my ($hashitems,$orderitems) = split(/:/,$response);
 2724:                 my @pairs=split(/\&/,$hashitems);
 2725:                 foreach my $item (@pairs) {
 2726:                     my ($key,$value)=split(/=/,$item,2);
 2727:                     $key = &unescape($key);
 2728:                     next if ($key =~ /^error: 2 /);
 2729:                     $ruleshash{$key}=&thaw_unescape($value);
 2730:                 }
 2731:                 my @esc_order = split(/\&/,$orderitems);
 2732:                 foreach my $item (@esc_order) {
 2733:                     push(@ruleorder,&unescape($item));
 2734:                 }
 2735:             }
 2736:         }
 2737:     }
 2738:     return (\%ruleshash,\@ruleorder);
 2739: }
 2740: 
 2741: # ------------- Get Authentication, Language and User Tools Defaults for Domain
 2742: 
 2743: sub get_domain_defaults {
 2744:     my ($domain,$ignore_cache) = @_;
 2745:     return if (($domain eq '') || ($domain eq 'public'));
 2746:     my $cachetime = 60*60*24;
 2747:     unless ($ignore_cache) {
 2748:         my ($result,$cached)=&is_cached_new('domdefaults',$domain);
 2749:         if (defined($cached)) {
 2750:             if (ref($result) eq 'HASH') {
 2751:                 return %{$result};
 2752:             }
 2753:         }
 2754:     }
 2755:     my %domdefaults;
 2756:     my %domconfig =
 2757:          &get_dom('configuration',['defaults','quotas',
 2758:                                   'requestcourses','inststatus',
 2759:                                   'coursedefaults','usersessions',
 2760:                                   'requestauthor','authordefaults',
 2761:                                   'selfenrollment','coursecategories',
 2762:                                   'ssl','autoenroll','trust',
 2763:                                   'helpsettings','wafproxy',
 2764:                                   'ltisec','toolsec','privacy'],$domain);
 2765:     my @coursetypes = ('official','unofficial','community','textbook','placement');
 2766:     if (ref($domconfig{'defaults'}) eq 'HASH') {
 2767:         $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'}; 
 2768:         $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
 2769:         $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
 2770:         $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
 2771:         $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
 2772:         $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
 2773:         $domdefaults{'portal_def_email'} = $domconfig{'defaults'}{'portal_def_email'};
 2774:         $domdefaults{'portal_def_web'} = $domconfig{'defaults'}{'portal_def_web'};
 2775:         $domdefaults{'intauth_cost'} = $domconfig{'defaults'}{'intauth_cost'};
 2776:         $domdefaults{'intauth_switch'} = $domconfig{'defaults'}{'intauth_switch'};
 2777:         $domdefaults{'intauth_check'} = $domconfig{'defaults'}{'intauth_check'};
 2778:         $domdefaults{'unamemap_rule'} = $domconfig{'defaults'}{'unamemap_rule'};
 2779:     } else {
 2780:         $domdefaults{'lang_def'} = &domain($domain,'lang_def');
 2781:         $domdefaults{'auth_def'} = &domain($domain,'auth_def');
 2782:         $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
 2783:     }
 2784:     if (ref($domconfig{'quotas'}) eq 'HASH') {
 2785:         if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
 2786:             $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
 2787:         } else {
 2788:             $domdefaults{'defaultquota'} = $domconfig{'quotas'};
 2789:         }
 2790:         my @usertools = ('aboutme','blog','webdav','portfolio','portaccess');
 2791:         foreach my $item (@usertools) {
 2792:             if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
 2793:                 $domdefaults{$item} = $domconfig{'quotas'}{$item};
 2794:             }
 2795:         }
 2796:         if (ref($domconfig{'quotas'}{'authorquota'}) eq 'HASH') {
 2797:             $domdefaults{'authorquota'} = $domconfig{'quotas'}{'authorquota'};
 2798:         }
 2799:     }
 2800:     if (ref($domconfig{'requestcourses'}) eq 'HASH') {
 2801:         foreach my $item ('official','unofficial','community','textbook','placement') {
 2802:             $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
 2803:         }
 2804:     }
 2805:     if (ref($domconfig{'requestauthor'}) eq 'HASH') {
 2806:         $domdefaults{'requestauthor'} = $domconfig{'requestauthor'};
 2807:     }
 2808:     if (ref($domconfig{'authordefaults'}) eq 'HASH') {
 2809:         foreach my $item ('nocodemirror','copyright','sourceavail','domcoordacc','editors','archive') {
 2810:             if ($item eq 'editors') {
 2811:                 if (ref($domconfig{'authordefaults'}{'editors'}) eq 'ARRAY') {
 2812:                     $domdefaults{$item} = join(',',@{$domconfig{'authordefaults'}{'editors'}});
 2813:                 }
 2814:             } else {
 2815:                 $domdefaults{$item} = $domconfig{'authordefaults'}{$item};
 2816:             }
 2817:         }
 2818:     }
 2819:     if (ref($domconfig{'inststatus'}) eq 'HASH') {
 2820:         foreach my $item ('inststatustypes','inststatusorder','inststatusguest') {
 2821:             $domdefaults{$item} = $domconfig{'inststatus'}{$item};
 2822:         }
 2823:     }
 2824:     if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
 2825:         $domdefaults{'canuse_pdfforms'} = $domconfig{'coursedefaults'}{'canuse_pdfforms'};
 2826:         $domdefaults{'usejsme'} = $domconfig{'coursedefaults'}{'usejsme'};
 2827:         $domdefaults{'inline_chem'} = $domconfig{'coursedefaults'}{'inline_chem'};
 2828:         $domdefaults{'uselcmath'} = $domconfig{'coursedefaults'}{'uselcmath'};
 2829:         if (ref($domconfig{'coursedefaults'}{'postsubmit'}) eq 'HASH') {
 2830:             $domdefaults{'postsubmit'} = $domconfig{'coursedefaults'}{'postsubmit'}{'client'};
 2831:         }
 2832:         foreach my $type (@coursetypes) {
 2833:             if (ref($domconfig{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
 2834:                 unless ($type eq 'community') {
 2835:                     $domdefaults{$type.'credits'} = $domconfig{'coursedefaults'}{'coursecredits'}{$type};
 2836:                 }
 2837:             }
 2838:             if (ref($domconfig{'coursedefaults'}{'uploadquota'}) eq 'HASH') {
 2839:                 $domdefaults{$type.'quota'} = $domconfig{'coursedefaults'}{'uploadquota'}{$type};
 2840:             }
 2841:             if (ref($domconfig{'coursedefaults'}{'coursequota'}) eq 'HASH') {
 2842:                 $domdefaults{$type.'coursequota'} = $domconfig{'coursedefaults'}{'coursequota'}{$type};
 2843:             }
 2844:             if ($domdefaults{'postsubmit'} eq 'on') {
 2845:                 if (ref($domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}) eq 'HASH') {
 2846:                     $domdefaults{$type.'postsubtimeout'} = 
 2847:                         $domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}{$type}; 
 2848:                 }
 2849:             }
 2850:             if (ref($domconfig{'coursedefaults'}{'domexttool'}) eq 'HASH') {
 2851:                 $domdefaults{$type.'domexttool'} = $domconfig{'coursedefaults'}{'domexttool'}{$type};
 2852:             } else {
 2853:                 $domdefaults{$type.'domexttool'} = 1;
 2854:             }
 2855:             if (ref($domconfig{'coursedefaults'}{'exttool'}) eq 'HASH') {
 2856:                 $domdefaults{$type.'exttool'} = $domconfig{'coursedefaults'}{'exttool'}{$type};
 2857:             } else {
 2858:                 $domdefaults{$type.'exttool'} = 0;
 2859:             }
 2860:             if (ref($domconfig{'coursedefaults'}{'crsauthor'}) eq 'HASH') {
 2861:                 $domdefaults{$type.'crsauthor'} = $domconfig{'coursedefaults'}{'crsauthor'}{$type};
 2862:             } else {
 2863:                 $domdefaults{$type.'crsauthor'} = 1;
 2864:             }
 2865:             if (ref($domconfig{'coursedefaults'}{'crseditors'}) eq 'ARRAY') {
 2866:                 $domdefaults{'crseditors'}=join(',',@{$domconfig{'coursedefaults'}{'crseditors'}});
 2867:             }
 2868:         }
 2869:         if (ref($domconfig{'coursedefaults'}{'canclone'}) eq 'HASH') {
 2870:             if (ref($domconfig{'coursedefaults'}{'canclone'}{'instcode'}) eq 'ARRAY') {
 2871:                 my @clonecodes = @{$domconfig{'coursedefaults'}{'canclone'}{'instcode'}};
 2872:                 if (@clonecodes) {
 2873:                     $domdefaults{'canclone'} = join('+',@clonecodes);
 2874:                 }
 2875:             }
 2876:         } elsif ($domconfig{'coursedefaults'}{'canclone'}) {
 2877:             $domdefaults{'canclone'}=$domconfig{'coursedefaults'}{'canclone'};
 2878:         }
 2879:         if ($domconfig{'coursedefaults'}{'texengine'}) {
 2880:             $domdefaults{'texengine'} = $domconfig{'coursedefaults'}{'texengine'};
 2881:         }
 2882:         if (exists($domconfig{'coursedefaults'}{'ltiauth'})) {
 2883:             $domdefaults{'crsltiauth'} = $domconfig{'coursedefaults'}{'ltiauth'};
 2884:         }
 2885:     }
 2886:     if (ref($domconfig{'usersessions'}) eq 'HASH') {
 2887:         if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
 2888:             $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
 2889:         }
 2890:         if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
 2891:             $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
 2892:         }
 2893:         if (ref($domconfig{'usersessions'}{'offloadnow'}) eq 'HASH') {
 2894:             $domdefaults{'offloadnow'} = $domconfig{'usersessions'}{'offloadnow'};
 2895:         }
 2896:         if (ref($domconfig{'usersessions'}{'offloadoth'}) eq 'HASH') {
 2897:             $domdefaults{'offloadoth'} = $domconfig{'usersessions'}{'offloadoth'};
 2898:         }
 2899:     }
 2900:     if (ref($domconfig{'selfenrollment'}) eq 'HASH') {
 2901:         if (ref($domconfig{'selfenrollment'}{'admin'}) eq 'HASH') {
 2902:             my @settings = ('types','registered','enroll_dates','access_dates','section',
 2903:                             'approval','limit');
 2904:             foreach my $type (@coursetypes) {
 2905:                 if (ref($domconfig{'selfenrollment'}{'admin'}{$type}) eq 'HASH') {
 2906:                     my @mgrdc = ();
 2907:                     foreach my $item (@settings) {
 2908:                         if ($domconfig{'selfenrollment'}{'admin'}{$type}{$item} eq '0') {
 2909:                             push(@mgrdc,$item);
 2910:                         }
 2911:                     }
 2912:                     if (@mgrdc) {
 2913:                         $domdefaults{$type.'selfenrolladmdc'} = join(',',@mgrdc);
 2914:                     }
 2915:                 }
 2916:             }
 2917:         }
 2918:         if (ref($domconfig{'selfenrollment'}{'default'}) eq 'HASH') {
 2919:             foreach my $type (@coursetypes) {
 2920:                 if (ref($domconfig{'selfenrollment'}{'default'}{$type}) eq 'HASH') {
 2921:                     foreach my $item (keys(%{$domconfig{'selfenrollment'}{'default'}{$type}})) {
 2922:                         $domdefaults{$type.'selfenroll'.$item} = $domconfig{'selfenrollment'}{'default'}{$type}{$item};
 2923:                     }
 2924:                 }
 2925:             }
 2926:         }
 2927:     }
 2928:     if (ref($domconfig{'coursecategories'}) eq 'HASH') {
 2929:         $domdefaults{'catauth'} = 'std';
 2930:         $domdefaults{'catunauth'} = 'std';
 2931:         if ($domconfig{'coursecategories'}{'auth'}) {
 2932:             $domdefaults{'catauth'} = $domconfig{'coursecategories'}{'auth'};
 2933:         }
 2934:         if ($domconfig{'coursecategories'}{'unauth'}) {
 2935:             $domdefaults{'catunauth'} = $domconfig{'coursecategories'}{'unauth'};
 2936:         }
 2937:     }
 2938:     if (ref($domconfig{'ssl'}) eq 'HASH') {
 2939:         if (ref($domconfig{'ssl'}{'replication'}) eq 'HASH') {
 2940:             $domdefaults{'replication'} = $domconfig{'ssl'}{'replication'};
 2941:         }
 2942:         if (ref($domconfig{'ssl'}{'connto'}) eq 'HASH') {
 2943:             $domdefaults{'connect'} = $domconfig{'ssl'}{'connto'};
 2944:         }
 2945:         if (ref($domconfig{'ssl'}{'connfrom'}) eq 'HASH') {
 2946:             $domdefaults{'connect'} = $domconfig{'ssl'}{'connfrom'};
 2947:         }
 2948:     }
 2949:     if (ref($domconfig{'trust'}) eq 'HASH') {
 2950:         my @prefixes = qw(content shared enroll othcoau coaurem domroles catalog reqcrs msg);
 2951:         foreach my $prefix (@prefixes) {
 2952:             if (ref($domconfig{'trust'}{$prefix}) eq 'HASH') {
 2953:                 $domdefaults{'trust'.$prefix} = $domconfig{'trust'}{$prefix};
 2954:             }
 2955:         }
 2956:     }
 2957:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
 2958:         $domdefaults{'autofailsafe'} = $domconfig{'autoenroll'}{'autofailsafe'};
 2959:         $domdefaults{'failsafe'} = $domconfig{'autoenroll'}{'failsafe'};
 2960:     }
 2961:     if (ref($domconfig{'helpsettings'}) eq 'HASH') {
 2962:         $domdefaults{'submitbugs'} = $domconfig{'helpsettings'}{'submitbugs'};
 2963:         if (ref($domconfig{'helpsettings'}{'adhoc'}) eq 'HASH') {
 2964:             $domdefaults{'adhocroles'} = $domconfig{'helpsettings'}{'adhoc'};
 2965:         }
 2966:     }
 2967:     if (ref($domconfig{'wafproxy'}) eq 'HASH') {
 2968:         foreach my $item ('ipheader','trusted','vpnint','vpnext','sslopt') {
 2969:             if ($domconfig{'wafproxy'}{$item}) {
 2970:                 $domdefaults{'waf_'.$item} = $domconfig{'wafproxy'}{$item};
 2971:             }
 2972:         }
 2973:     }
 2974:     if (ref($domconfig{'ltisec'}) eq 'HASH') {
 2975:         if (ref($domconfig{'ltisec'}{'encrypt'}) eq 'HASH') {
 2976:             $domdefaults{'linkprotenc_crs'} = $domconfig{'ltisec'}{'encrypt'}{'crs'};
 2977:             $domdefaults{'linkprotenc_dom'} = $domconfig{'ltisec'}{'encrypt'}{'dom'};
 2978:             $domdefaults{'ltienc_consumers'} = $domconfig{'ltisec'}{'encrypt'}{'consumers'};
 2979:         }
 2980:         if (ref($domconfig{'ltisec'}{'private'}) eq 'HASH') {
 2981:             if (ref($domconfig{'ltisec'}{'private'}{'keys'}) eq 'ARRAY') {
 2982:                 $domdefaults{'ltiprivhosts'} = $domconfig{'ltisec'}{'private'}{'keys'};
 2983:             }
 2984:         }
 2985:         if (ref($domconfig{'ltisec'}{'suggested'}) eq 'HASH') {
 2986:             my %suggestions = %{$domconfig{'ltisec'}{'suggested'}};
 2987:             foreach my $item (keys(%{$domconfig{'ltisec'}{'suggested'}})) {
 2988:                 unless (ref($domconfig{'ltisec'}{'suggested'}{$item}) eq 'HASH') {
 2989:                     delete($suggestions{$item});
 2990:                 }
 2991:             }
 2992:             if (keys(%suggestions)) {
 2993:                 $domdefaults{'linkprotsuggested'} = \%suggestions;
 2994:             }
 2995:         }
 2996:     }
 2997:     if (ref($domconfig{'toolsec'}) eq 'HASH') {
 2998:         if (ref($domconfig{'toolsec'}{'encrypt'}) eq 'HASH') {
 2999:             $domdefaults{'toolenc_crs'} = $domconfig{'toolsec'}{'encrypt'}{'crs'};
 3000:             $domdefaults{'toolenc_dom'} = $domconfig{'toolsec'}{'encrypt'}{'dom'};
 3001:         }
 3002:         if (ref($domconfig{'toolsec'}{'private'}) eq 'HASH') {
 3003:             if (ref($domconfig{'toolsec'}{'private'}{'keys'}) eq 'ARRAY') {
 3004:                 $domdefaults{'toolprivhosts'} = $domconfig{'toolsec'}{'private'}{'keys'};
 3005:             }
 3006:         }
 3007:     }
 3008:     if (ref($domconfig{'privacy'}) eq 'HASH') {
 3009:         if (ref($domconfig{'privacy'}{'approval'}) eq 'HASH') {
 3010:             foreach my $domtype ('instdom','extdom') {
 3011:                 if (ref($domconfig{'privacy'}{'approval'}{$domtype}) eq 'HASH') {
 3012:                     foreach my $roletype ('domain','author','course','community') {
 3013:                         if ($domconfig{'privacy'}{'approval'}{$domtype}{$roletype} eq 'user') {
 3014:                             $domdefaults{'userapprovals'} = 1;
 3015:                             last;
 3016:                         }
 3017:                     }
 3018:                 }
 3019:                 last if ($domdefaults{'userapprovals'});
 3020:             }
 3021:         }
 3022:     }
 3023:     &do_cache_new('domdefaults',$domain,\%domdefaults,$cachetime);
 3024:     return %domdefaults;
 3025: }
 3026: 
 3027: sub get_dom_cats {
 3028:     my ($dom) = @_;
 3029:     return unless (&domain($dom));
 3030:     my ($cats,$cached)=&is_cached_new('cats',$dom);
 3031:     unless (defined($cached)) {
 3032:         my %domconfig = &get_dom('configuration',['coursecategories'],$dom);
 3033:         if (ref($domconfig{'coursecategories'}) eq 'HASH') {
 3034:             if (ref($domconfig{'coursecategories'}{'cats'}) eq 'HASH') {
 3035:                 %{$cats} = %{$domconfig{'coursecategories'}{'cats'}};
 3036:             } else {
 3037:                 $cats = {};
 3038:             }
 3039:         } else {
 3040:             $cats = {};
 3041:         }
 3042:         &do_cache_new('cats',$dom,$cats,3600);
 3043:     }
 3044:     return $cats;
 3045: }
 3046: 
 3047: sub get_dom_instcats {
 3048:     my ($dom) = @_;
 3049:     return unless (&domain($dom));
 3050:     my ($instcats,$cached)=&is_cached_new('instcats',$dom);
 3051:     unless (defined($cached)) {
 3052:         my (%coursecodes,%codes,@codetitles,%cat_titles,%cat_order);
 3053:         my $totcodes = &retrieve_instcodes(\%coursecodes,$dom);
 3054:         if ($totcodes > 0) {
 3055:             my $caller = 'global';
 3056:             if (&auto_instcode_format($caller,$dom,\%coursecodes,\%codes,
 3057:                                       \@codetitles,\%cat_titles,\%cat_order) eq 'ok') {
 3058:                 $instcats = {
 3059:                                 totcodes => $totcodes,
 3060:                                 codes => \%codes,
 3061:                                 codetitles => \@codetitles,
 3062:                                 cat_titles => \%cat_titles,
 3063:                                 cat_order => \%cat_order,
 3064:                             };
 3065:                 &do_cache_new('instcats',$dom,$instcats,3600);
 3066:             }
 3067:         }
 3068:     }
 3069:     return $instcats;
 3070: }
 3071: 
 3072: sub retrieve_instcodes {
 3073:     my ($coursecodes,$dom) = @_;
 3074:     my $totcodes;
 3075:     my %courses = &courseiddump($dom,'.',1,'.','.','.',undef,undef,'Course');
 3076:     foreach my $course (keys(%courses)) {
 3077:         if (ref($courses{$course}) eq 'HASH') {
 3078:             if ($courses{$course}{'inst_code'} ne '') {
 3079:                 $$coursecodes{$course} = $courses{$course}{'inst_code'};
 3080:                 $totcodes ++;
 3081:             }
 3082:         }
 3083:     }
 3084:     return $totcodes;
 3085: }
 3086: 
 3087: sub course_portal_url {
 3088:     my ($cnum,$cdom,$r) = @_;
 3089:     my $chome = &homeserver($cnum,$cdom);
 3090:     my $hostname = &hostname($chome);
 3091:     my $protocol = $protocol{$chome};
 3092:     $protocol = 'http' if ($protocol ne 'https');
 3093:     my %domdefaults = &get_domain_defaults($cdom);
 3094:     my $firsturl;
 3095:     if ($domdefaults{'portal_def'}) {
 3096:         $firsturl = $domdefaults{'portal_def'};
 3097:     } else {
 3098:         my $alias = &use_proxy_alias($r,$chome);
 3099:         $hostname = $alias if ($alias ne '');
 3100:         $firsturl = $protocol.'://'.$hostname;
 3101:     }
 3102:     return $firsturl;
 3103: }
 3104: 
 3105: sub url_prefix {
 3106:     my ($r,$dom,$home,$context) = @_;
 3107:     my $prefix;
 3108:     my %domdefs = &get_domain_defaults($dom);
 3109:     if ($domdefs{'portal_def'} && $domdefs{'portal_def_'.$context}) {
 3110:         if ($domdefs{'portal_def'} =~ m{^(https?://[^/]+)}) {
 3111:             $prefix = $1;
 3112:         }
 3113:     }
 3114:     if ($prefix eq '') {
 3115:         my $hostname = &hostname($home);
 3116:         my $protocol = $protocol{$home};
 3117:         $protocol = 'http' if ($protocol{$home} ne 'https');
 3118:         my $alias = &use_proxy_alias($r,$home);
 3119:         $hostname = $alias if ($alias ne '');
 3120:         $prefix = $protocol.'://'.$hostname;
 3121:     }
 3122:     return $prefix;
 3123: }
 3124: 
 3125: # --------------------------------------------- Get domain config for passwords
 3126: 
 3127: sub get_passwdconf {
 3128:     my ($dom) = @_;
 3129:     my (%passwdconf,$gotconf,$lookup);
 3130:     my ($result,$cached)=&is_cached_new('passwdconf',$dom);
 3131:     if (defined($cached)) {
 3132:         if (ref($result) eq 'HASH') {
 3133:             %passwdconf = %{$result};
 3134:             $gotconf = 1;
 3135:         }
 3136:     }
 3137:     unless ($gotconf) {
 3138:         my %domconfig = &get_dom('configuration',['passwords'],$dom);
 3139:         if (ref($domconfig{'passwords'}) eq 'HASH') {
 3140:             %passwdconf = %{$domconfig{'passwords'}};
 3141:         }
 3142:         my $cachetime = 24*60*60;
 3143:         &do_cache_new('passwdconf',$dom,\%passwdconf,$cachetime);
 3144:     }
 3145:     return %passwdconf;
 3146: }
 3147: 
 3148: # --------------------------------------------------- Assign a key to a student
 3149: 
 3150: sub assign_access_key {
 3151: #
 3152: # a valid key looks like uname:udom#comments
 3153: # comments are being appended
 3154: #
 3155:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
 3156:     $kdom=
 3157:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
 3158:     $knum=
 3159:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
 3160:     $cdom=
 3161:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 3162:     $cnum=
 3163:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 3164:     $udom=$env{'user.name'} unless (defined($udom));
 3165:     $uname=$env{'user.domain'} unless (defined($uname));
 3166:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
 3167:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
 3168:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
 3169:                                                   # assigned to this person
 3170:                                                   # - this should not happen,
 3171:                                                   # unless something went wrong
 3172:                                                   # the first time around
 3173: # ready to assign
 3174:         $logentry=$1.'; '.$logentry;
 3175:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
 3176:                                                  $kdom,$knum) eq 'ok') {
 3177: # key now belongs to user
 3178: 	    my $envkey='key.'.$cdom.'_'.$cnum;
 3179:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
 3180:                 &appenv({'environment.'.$envkey => $ckey});
 3181:                 return 'ok';
 3182:             } else {
 3183:                 return 
 3184:   'error: Count not permanently assign key, will need to be re-entered later.';
 3185: 	    }
 3186:         } else {
 3187:             return 'error: Could not assign key, try again later.';
 3188:         }
 3189:     } elsif (!$existing{$ckey}) {
 3190: # the key does not exist
 3191: 	return 'error: The key does not exist';
 3192:     } else {
 3193: # the key is somebody else's
 3194: 	return 'error: The key is already in use';
 3195:     }
 3196: }
 3197: 
 3198: # ------------------------------------------ put an additional comment on a key
 3199: 
 3200: sub comment_access_key {
 3201: #
 3202: # a valid key looks like uname:udom#comments
 3203: # comments are being appended
 3204: #
 3205:     my ($ckey,$cdom,$cnum,$logentry)=@_;
 3206:     $cdom=
 3207:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 3208:     $cnum=
 3209:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 3210:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
 3211:     if ($existing{$ckey}) {
 3212:         $existing{$ckey}.='; '.$logentry;
 3213: # ready to assign
 3214:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
 3215:                                                  $cdom,$cnum) eq 'ok') {
 3216: 	    return 'ok';
 3217:         } else {
 3218: 	    return 'error: Count not store comment.';
 3219:         }
 3220:     } else {
 3221: # the key does not exist
 3222: 	return 'error: The key does not exist';
 3223:     }
 3224: }
 3225: 
 3226: # ------------------------------------------------------ Generate a set of keys
 3227: 
 3228: sub generate_access_keys {
 3229:     my ($number,$cdom,$cnum,$logentry)=@_;
 3230:     $cdom=
 3231:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 3232:     $cnum=
 3233:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 3234:     unless (&allowed('mky',$cdom)) { return 0; }
 3235:     unless (($cdom) && ($cnum)) { return 0; }
 3236:     if ($number>10000) { return 0; }
 3237:     sleep(2); # make sure don't get same seed twice
 3238:     srand(time()^($$+($$<<15))); # from "Programming Perl"
 3239:     my $total=0;
 3240:     for (my $i=1;$i<=$number;$i++) {
 3241:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
 3242:                   sprintf("%lx",int(100000*rand)).'-'.
 3243:                   sprintf("%lx",int(100000*rand));
 3244:        $newkey=~s/1/g/g; # folks mix up 1 and l
 3245:        $newkey=~s/0/h/g; # and also 0 and O
 3246:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
 3247:        if ($existing{$newkey}) {
 3248:            $i--;
 3249:        } else {
 3250: 	  if (&put('accesskeys',
 3251:               { $newkey => '# generated '.localtime().
 3252:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
 3253:                            '; '.$logentry },
 3254: 		   $cdom,$cnum) eq 'ok') {
 3255:               $total++;
 3256: 	  }
 3257:        }
 3258:     }
 3259:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
 3260:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
 3261:     return $total;
 3262: }
 3263: 
 3264: # ------------------------------------------------------- Validate an accesskey
 3265: 
 3266: sub validate_access_key {
 3267:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
 3268:     $cdom=
 3269:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 3270:     $cnum=
 3271:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 3272:     $udom=$env{'user.domain'} unless (defined($udom));
 3273:     $uname=$env{'user.name'} unless (defined($uname));
 3274:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
 3275:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
 3276: }
 3277: 
 3278: # ------------------------------------- Find the section of student in a course
 3279: sub devalidate_getsection_cache {
 3280:     my ($udom,$unam,$courseid)=@_;
 3281:     my $hashid="$udom:$unam:$courseid";
 3282:     &devalidate_cache_new('getsection',$hashid);
 3283: }
 3284: 
 3285: sub courseid_to_courseurl {
 3286:     my ($courseid) = @_;
 3287:     #already url style courseid
 3288:     return $courseid if ($courseid =~ m{^/});
 3289: 
 3290:     if (exists($env{'course.'.$courseid.'.num'})) {
 3291: 	my $cnum = $env{'course.'.$courseid.'.num'};
 3292: 	my $cdom = $env{'course.'.$courseid.'.domain'};
 3293: 	return "/$cdom/$cnum";
 3294:     }
 3295: 
 3296:     my %courseinfo=&coursedescription($courseid);
 3297:     if (exists($courseinfo{'num'})) {
 3298: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
 3299:     }
 3300: 
 3301:     return undef;
 3302: }
 3303: 
 3304: sub getsection {
 3305:     my ($udom,$unam,$courseid)=@_;
 3306:     my $cachetime=1800;
 3307: 
 3308:     my $hashid="$udom:$unam:$courseid";
 3309:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
 3310:     if (defined($cached)) { return $result; }
 3311: 
 3312:     my %Pending; 
 3313:     my %Expired;
 3314:     #
 3315:     # Each role can either have not started yet (pending), be active, 
 3316:     #    or have expired.
 3317:     #
 3318:     # If there is an active role, we are done.
 3319:     #
 3320:     # If there is more than one role which has not started yet, 
 3321:     #     choose the one which will start sooner
 3322:     # If there is one role which has not started yet, return it.
 3323:     #
 3324:     # If there is more than one expired role, choose the one which ended last.
 3325:     # If there is a role which has expired, return it.
 3326:     #
 3327:     $courseid = &courseid_to_courseurl($courseid);
 3328:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
 3329:     foreach my $key (keys(%roleshash)) {
 3330:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
 3331:         my $section=$1;
 3332:         if ($key eq $courseid.'_st') { $section=''; }
 3333:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
 3334:         my $now=time;
 3335:         if (defined($end) && $end && ($now > $end)) {
 3336:             $Expired{$end}=$section;
 3337:             next;
 3338:         }
 3339:         if (defined($start) && $start && ($now < $start)) {
 3340:             $Pending{$start}=$section;
 3341:             next;
 3342:         }
 3343:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
 3344:     }
 3345:     #
 3346:     # Presumedly there will be few matching roles from the above
 3347:     # loop and the sorting time will be negligible.
 3348:     if (scalar(keys(%Pending))) {
 3349:         my ($time) = sort {$a <=> $b} keys(%Pending);
 3350:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
 3351:     } 
 3352:     if (scalar(keys(%Expired))) {
 3353:         my @sorted = sort {$a <=> $b} keys(%Expired);
 3354:         my $time = pop(@sorted);
 3355:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
 3356:     }
 3357:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
 3358: }
 3359: 
 3360: sub save_cache {
 3361:     &purge_remembered();
 3362:     #&Apache::loncommon::validate_page();
 3363:     undef(%env);
 3364:     undef($env_loaded);
 3365: }
 3366: 
 3367: my $to_remember=-1;
 3368: my %remembered;
 3369: my %accessed;
 3370: my $kicks=0;
 3371: my $hits=0;
 3372: sub make_key {
 3373:     my ($name,$id) = @_;
 3374:     if (length($id) > 65 
 3375: 	&& length(&escape($id)) > 200) {
 3376: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
 3377:     }
 3378:     return &escape($name.':'.$id);
 3379: }
 3380: 
 3381: sub devalidate_cache_new {
 3382:     my ($name,$id,$debug) = @_;
 3383:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
 3384:     my $remembered_id=$name.':'.$id;
 3385:     $id=&make_key($name,$id);
 3386:     $memcache->delete($id);
 3387:     delete($remembered{$remembered_id});
 3388:     delete($accessed{$remembered_id});
 3389: }
 3390: 
 3391: sub is_cached_new {
 3392:     my ($name,$id,$debug) = @_;
 3393:     my $remembered_id=$name.':'.$id; # this is to avoid make_key (which is slow) whenever possible
 3394:     if (exists($remembered{$remembered_id})) {
 3395: 	if ($debug) { &Apache::lonnet::logthis("Early return $remembered_id of $remembered{$remembered_id} "); }
 3396: 	$accessed{$remembered_id}=[&gettimeofday()];
 3397: 	$hits++;
 3398: 	return ($remembered{$remembered_id},1);
 3399:     }
 3400:     $id=&make_key($name,$id);
 3401:     my $value = $memcache->get($id);
 3402:     if (!(defined($value))) {
 3403: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
 3404: 	return (undef,undef);
 3405:     }
 3406:     if ($value eq '__undef__') {
 3407: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
 3408: 	$value=undef;
 3409:     }
 3410:     &make_room($remembered_id,$value,$debug);
 3411:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
 3412:     return ($value,1);
 3413: }
 3414: 
 3415: sub do_cache_new {
 3416:     my ($name,$id,$value,$time,$debug) = @_;
 3417:     my $remembered_id=$name.':'.$id;
 3418:     $id=&make_key($name,$id);
 3419:     my $setvalue=$value;
 3420:     if (!defined($setvalue)) {
 3421: 	$setvalue='__undef__';
 3422:     }
 3423:     if (!defined($time) ) {
 3424: 	$time=600;
 3425:     }
 3426:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
 3427:     my $result = $memcache->set($id,$setvalue,$time);
 3428:     if (! $result) {
 3429: 	&logthis("caching of id -> $id  failed");
 3430: 	$memcache->disconnect_all();
 3431:     }
 3432:     # need to make a copy of $value
 3433:     &make_room($remembered_id,$value,$debug);
 3434:     return $value;
 3435: }
 3436: 
 3437: sub make_room {
 3438:     my ($remembered_id,$value,$debug)=@_;
 3439: 
 3440:     $remembered{$remembered_id}= (ref($value)) ? &Storable::dclone($value)
 3441:                                     : $value;
 3442:     if ($to_remember<0) { return; }
 3443:     $accessed{$remembered_id}=[&gettimeofday()];
 3444:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
 3445:     my $to_kick;
 3446:     my $max_time=0;
 3447:     foreach my $other (keys(%accessed)) {
 3448: 	if (&tv_interval($accessed{$other}) > $max_time) {
 3449: 	    $to_kick=$other;
 3450: 	    $max_time=&tv_interval($accessed{$other});
 3451: 	}
 3452:     }
 3453:     delete($remembered{$to_kick});
 3454:     delete($accessed{$to_kick});
 3455:     $kicks++;
 3456:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
 3457:     return;
 3458: }
 3459: 
 3460: sub purge_remembered {
 3461:     #&logthis("Tossing ".scalar(keys(%remembered)));
 3462:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
 3463:     undef(%remembered);
 3464:     undef(%accessed);
 3465: }
 3466: # ------------------------------------- Read an entry from a user's environment
 3467: 
 3468: sub userenvironment {
 3469:     my ($udom,$unam,@what)=@_;
 3470:     my $items;
 3471:     foreach my $item (@what) {
 3472:         $items.=&escape($item).'&';
 3473:     }
 3474:     $items=~s/\&$//;
 3475:     my %returnhash=();
 3476:     my $uhome = &homeserver($unam,$udom);
 3477:     unless ($uhome eq 'no_host') {
 3478:         my @answer=split(/\&/, 
 3479:             &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
 3480:         if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
 3481:             return %returnhash;
 3482:         }
 3483:         my $i;
 3484:         for ($i=0;$i<=$#what;$i++) {
 3485: 	    $returnhash{$what[$i]}=&unescape($answer[$i]);
 3486:         }
 3487:     }
 3488:     return %returnhash;
 3489: }
 3490: 
 3491: # ---------------------------------------------------------- Get a studentphoto
 3492: sub studentphoto {
 3493:     my ($udom,$unam,$ext) = @_;
 3494:     my $home=&homeserver($unam,$udom);
 3495:     if (defined($env{'request.course.id'})) {
 3496:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
 3497:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
 3498:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
 3499:             } else {
 3500:                 my ($result,$perm_reqd)=
 3501: 		    &auto_photo_permission($unam,$udom);
 3502:                 if ($result eq 'ok') {
 3503:                     if (!($perm_reqd eq 'yes')) {
 3504:                         return(&retrievestudentphoto($udom,$unam,$ext));
 3505:                     }
 3506:                 }
 3507:             }
 3508:         }
 3509:     } else {
 3510:         my ($result,$perm_reqd) = 
 3511: 	    &auto_photo_permission($unam,$udom);
 3512:         if ($result eq 'ok') {
 3513:             if (!($perm_reqd eq 'yes')) {
 3514:                 return(&retrievestudentphoto($udom,$unam,$ext));
 3515:             }
 3516:         }
 3517:     }
 3518:     return '/adm/lonKaputt/lonlogo_broken.gif';
 3519: }
 3520: 
 3521: sub retrievestudentphoto {
 3522:     my ($udom,$unam,$ext,$type) = @_;
 3523:     my $home=&homeserver($unam,$udom);
 3524:     my $ret=&reply("studentphoto:$udom:$unam:$ext:$type",$home);
 3525:     if ($ret eq 'ok') {
 3526:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
 3527:         if ($type eq 'thumbnail') {
 3528:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
 3529:         }
 3530:         my $tokenurl=&tokenwrapper($url);
 3531:         return $tokenurl;
 3532:     } else {
 3533:         if ($type eq 'thumbnail') {
 3534:             return '/adm/lonKaputt/genericstudent_tn.gif';
 3535:         } else { 
 3536:             return '/adm/lonKaputt/lonlogo_broken.gif';
 3537:         }
 3538:     }
 3539: }
 3540: 
 3541: # -------------------------------------------------------------------- New chat
 3542: 
 3543: sub chatsend {
 3544:     my ($newentry,$anon,$group)=@_;
 3545:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
 3546:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 3547:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
 3548:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
 3549: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
 3550: 		   &escape($newentry)).':'.$group,$chome);
 3551: }
 3552: 
 3553: # ------------------------------------------ Find current version of a resource
 3554: 
 3555: sub getversion {
 3556:     my $fname=&clutter(shift);
 3557:     unless ($fname=~m{^(/adm/wrapper|)/res/}) { return -1; }
 3558:     return &currentversion(&filelocation('',$fname));
 3559: }
 3560: 
 3561: sub currentversion {
 3562:     my $fname=shift;
 3563:     my $author=$fname;
 3564:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 3565:     my ($udom,$uname)=split(/\//,$author);
 3566:     my $home=&homeserver($uname,$udom);
 3567:     if ($home eq 'no_host') { 
 3568:         return -1; 
 3569:     }
 3570:     my $answer=&reply("currentversion:$fname",$home);
 3571:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
 3572: 	return -1;
 3573:     }
 3574:     return $answer;
 3575: }
 3576: 
 3577: #
 3578: # Return special version number of resource if set by override, empty otherwise
 3579: #
 3580: sub usedversion {
 3581:     my $fname=shift;
 3582:     unless ($fname) { $fname=$env{'request.uri'}; }
 3583:     my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
 3584:     if ($urlversion) { return $urlversion; }
 3585:     return '';
 3586: }
 3587: 
 3588: # ----------------------------- Subscribe to a resource, return URL if possible
 3589: 
 3590: sub subscribe {
 3591:     my $fname=shift;
 3592:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
 3593:     $fname=~s/[\n\r]//g;
 3594:     my $author=$fname;
 3595:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 3596:     my ($udom,$uname)=split(/\//,$author);
 3597:     my $home=homeserver($uname,$udom);
 3598:     if ($home eq 'no_host') {
 3599:         return 'not_found';
 3600:     }
 3601:     my $answer=reply("sub:$fname",$home);
 3602:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
 3603: 	$answer.=' by '.$home;
 3604:     }
 3605:     return $answer;
 3606: }
 3607:     
 3608: # -------------------------------------------------------------- Replicate file
 3609: 
 3610: sub repcopy {
 3611:     my $filename=shift;
 3612:     $filename=~s/\/+/\//g;
 3613:     my $londocroot = $perlvar{'lonDocRoot'};
 3614:     if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
 3615:     if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
 3616:     if ($filename=~m{^\Q$londocroot/userfiles/\E} or
 3617: 	$filename=~m{^/*(uploaded|editupload)/}) {
 3618: 	return &repcopy_userfile($filename);
 3619:     }
 3620:     $filename=~s/[\n\r]//g;
 3621:     my $transname="$filename.in.transfer";
 3622: # FIXME: this should flock
 3623:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
 3624:     my $remoteurl=subscribe($filename);
 3625:     if ($remoteurl =~ /^con_lost by/) {
 3626: 	   &logthis("Subscribe returned $remoteurl: $filename");
 3627:            return 'unavailable';
 3628:     } elsif ($remoteurl eq 'not_found') {
 3629: 	   #&logthis("Subscribe returned not_found: $filename");
 3630: 	   return 'not_found';
 3631:     } elsif ($remoteurl =~ /^rejected by/) {
 3632: 	   &logthis("Subscribe returned $remoteurl: $filename");
 3633:            return 'forbidden';
 3634:     } elsif ($remoteurl eq 'directory') {
 3635:            return 'ok';
 3636:     } else {
 3637:         my $author=$filename;
 3638:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 3639:         my ($udom,$uname)=split(/\//,$author);
 3640:         my $home=homeserver($uname,$udom);
 3641:         unless ($home eq $perlvar{'lonHostID'}) {
 3642:            my @parts=split(/\//,$filename);
 3643:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
 3644:            if ($path ne "$londocroot/res") {
 3645:                &logthis("Malconfiguration for replication: $filename");
 3646: 	       return 'bad_request';
 3647:            }
 3648:            my $count;
 3649:            for ($count=5;$count<$#parts;$count++) {
 3650:                $path.="/$parts[$count]";
 3651:                if ((-e $path)!=1) {
 3652: 		   mkdir($path,0777);
 3653:                }
 3654:            }
 3655:            my $request=new HTTP::Request('GET',"$remoteurl");
 3656:            my $response;
 3657:            if ($remoteurl =~ m{/raw/}) {
 3658:                $response=&LONCAPA::LWPReq::makerequest($home,$request,$transname,\%perlvar,'',0,1);
 3659:            } else {
 3660:                $response=&LONCAPA::LWPReq::makerequest($home,$request,$transname,\%perlvar,'',1);
 3661:            }
 3662:            if ($response->is_error()) {
 3663: 	       unlink($transname);
 3664:                my $message=$response->status_line;
 3665:                &logthis("<font color=\"blue\">WARNING:"
 3666:                        ." LWP get: $message: $filename</font>");
 3667:                return 'unavailable';
 3668:            } else {
 3669: 	       if ($remoteurl!~/\.meta$/) {
 3670:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
 3671:                   my $mresponse;
 3672:                   if ($remoteurl =~ m{/raw/}) {
 3673:                       $mresponse = &LONCAPA::LWPReq::makerequest($home,$mrequest,$filename.'.meta',\%perlvar,'',0,1);
 3674:                   } else {
 3675:                       $mresponse = &LONCAPA::LWPReq::makerequest($home,$mrequest,$filename.'.meta',\%perlvar,'',1);
 3676:                   }
 3677:                   if ($mresponse->is_error()) {
 3678: 		      unlink($filename.'.meta');
 3679:                       &logthis(
 3680:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
 3681:                   }
 3682: 	       }
 3683:                rename($transname,$filename);
 3684:                return 'ok';
 3685:            }
 3686:        }
 3687:     }
 3688: }
 3689: 
 3690: # ------------------------------------------------- Unsubscribe from a resource
 3691: 
 3692: sub unsubscribe {
 3693:     my ($fname) = @_;
 3694:     my $answer;
 3695:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return $answer; }
 3696:     $fname=~s/[\n\r]//g;
 3697:     my $author=$fname;
 3698:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 3699:     my ($udom,$uname)=split(/\//,$author);
 3700:     my $home=homeserver($uname,$udom);
 3701:     if ($home eq 'no_host') {
 3702:         $answer = 'no_host';
 3703:     } elsif (grep { $_ eq $home } &current_machine_ids()) {
 3704:         $answer = 'home';
 3705:     } else {
 3706:         my $defdom = $perlvar{'lonDefDomain'};
 3707:         if (&will_trust('content',$defdom,$udom)) {
 3708:             $answer = reply("unsub:$fname",$home);
 3709:         } else {
 3710:             $answer = 'untrusted';
 3711:         }
 3712:     }
 3713:     return $answer;
 3714: }
 3715: 
 3716: # ------------------------------------------------ Get server side include body
 3717: sub ssi_body {
 3718:     my ($filelink,%form)=@_;
 3719:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
 3720:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
 3721:     }
 3722:     my $output='';
 3723:     my $response;
 3724:     if ($filelink=~/^https?\:/) {
 3725:        ($output,$response)=&externalssi($filelink);
 3726:     } else {
 3727:        $filelink .= $filelink=~/\?/ ? '&' : '?';
 3728:        $filelink .= 'inhibitmenu=yes';
 3729:        ($output,$response)=&ssi($filelink,%form);
 3730:     }
 3731:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
 3732:     $output=~s/^.*?\<body[^\>]*\>//si;
 3733:     $output=~s/\<\/body\s*\>.*?$//si;
 3734:     if (wantarray) {
 3735:         return ($output, $response);
 3736:     } else {
 3737:         return $output;
 3738:     }
 3739: }
 3740: 
 3741: # --------------------------------------------------------- Server Side Include
 3742: 
 3743: sub absolute_url {
 3744:     my ($host_name,$unalias,$keep_proto) = @_;
 3745:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
 3746:     if ($host_name eq '') {
 3747: 	$host_name = $ENV{'SERVER_NAME'};
 3748:     }
 3749:     if ($unalias) {
 3750:         my $alias = &get_proxy_alias();
 3751:         if ($alias eq $host_name) {
 3752:             my $lonhost = $perlvar{'lonHostID'};
 3753:             my $hostname = &hostname($lonhost);
 3754:             my $lcproto; 
 3755:             if (($keep_proto) || ($hostname eq '')) {
 3756:                 $lcproto = $protocol;
 3757:             } else {
 3758:                 $lcproto = $protocol{$lonhost};
 3759:                 $lcproto = 'http' if ($lcproto ne 'https');
 3760:                 $lcproto .= '://';
 3761:             }
 3762:             unless ($hostname eq '') {
 3763:                 return $lcproto.$hostname;
 3764:             }
 3765:         }
 3766:     }
 3767:     return $protocol.$host_name;
 3768: }
 3769: 
 3770: #
 3771: #   Server side include.
 3772: # Parameters:
 3773: #  fn     Possibly encrypted resource name/id.
 3774: #  form   Hash that describes how the rendering should be done
 3775: #         and other things.
 3776: # Returns:
 3777: #   Scalar context: The content of the response.
 3778: #   Array context:  2 element list of the content and the full response object.
 3779: #     
 3780: sub ssi {
 3781: 
 3782:     my ($fn,%form)=@_;
 3783:     my ($host,$request,$response);
 3784:     $host = &absolute_url('',1);
 3785: 
 3786:     $form{'no_update_last_known'}=1;
 3787:     &Apache::lonenc::check_encrypt(\$fn);
 3788:     if (%form) {
 3789:       $request=new HTTP::Request('POST',$host.$fn);
 3790:       $request->content(join('&',map { 
 3791:             my $name = escape($_);
 3792:             "$name=" . ( ref($form{$_}) eq 'ARRAY' 
 3793:             ? join("&$name=", map {escape($_) } @{$form{$_}}) 
 3794:             : &escape($form{$_}) );    
 3795:         } keys(%form)));
 3796:     } else {
 3797:       $request=new HTTP::Request('GET',$host.$fn);
 3798:     }
 3799: 
 3800:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
 3801:     my $lonhost = $perlvar{'lonHostID'};
 3802:     my $islocal;
 3803:     if (($env{'request.course.id'}) &&
 3804:         ($form{'grade_courseid'} eq $env{'request.course.id'}) &&
 3805:         ($form{'grade_username'} ne '') && ($form{'grade_domain'} ne '') &&
 3806:         ($form{'grade_symb'} ne '') &&
 3807:         (&allowed('mgr',$env{'request.course.id'}.
 3808:                         ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:'')))) {
 3809:         $islocal = 1;
 3810:     }
 3811:     $response= &LONCAPA::LWPReq::makerequest($lonhost,$request,'',\%perlvar,
 3812:                                              '','','',$islocal);
 3813: 
 3814:     if (wantarray) {
 3815: 	return ($response->content, $response);
 3816:     } else {
 3817: 	return $response->content;
 3818:     }
 3819: }
 3820: 
 3821: sub externalssi {
 3822:     my ($url)=@_;
 3823:     my $request=new HTTP::Request('GET',$url);
 3824:     my $response = &LONCAPA::LWPReq::makerequest('',$request,'',\%perlvar);
 3825:     if (wantarray) {
 3826:         return ($response->content, $response);
 3827:     } else {
 3828:         return $response->content;
 3829:     }
 3830: }
 3831: 
 3832: 
 3833: # If the local copy of a replicated resource is outdated, trigger a  
 3834: # connection from the homeserver to flush the delayed queue. If no update 
 3835: # happens, remove local copies of outdated resource (and corresponding
 3836: # metadata file).
 3837: 
 3838: sub remove_stale_resfile {
 3839:     my ($url) = @_;
 3840:     my $removed;
 3841:     if ($url=~m{^/res/($match_domain)/($match_username)/}) {
 3842:         my $audom = $1;
 3843:         my $auname = $2;
 3844:         unless (($url =~ /\.\d+\.\w+$/) || ($url =~ m{^/res/lib/templates/})) {
 3845:             my $homeserver = &homeserver($auname,$audom);
 3846:             unless (($homeserver eq 'no_host') ||
 3847:                     (grep { $_ eq $homeserver } &current_machine_ids())) {
 3848:                 my $fname = &filelocation('',$url);
 3849:                 if (-e $fname) {
 3850:                     my $hostname = &hostname($homeserver);
 3851:                     if ($hostname) {
 3852:                         my $protocol = $protocol{$homeserver};
 3853:                         $protocol = 'http' if ($protocol ne 'https');
 3854:                         my $uri = &declutter($url);
 3855:                         my $request=new HTTP::Request('HEAD',$protocol.'://'.$hostname.'/raw/'.$uri);
 3856:                         my $response = &LONCAPA::LWPReq::makerequest($homeserver,$request,'',\%perlvar,5,0,1);
 3857:                         if ($response->is_success()) {
 3858:                             my $remmodtime = &HTTP::Date::str2time( $response->header('Last-modified') );
 3859:                             my $locmodtime = (stat($fname))[9];
 3860:                             if ($locmodtime < $remmodtime) {
 3861:                                 my $stale;
 3862:                                 my $answer = &reply('pong',$homeserver);
 3863:                                 if ($answer eq $homeserver.':'.$perlvar{'lonHostID'}) {
 3864:                                     sleep(0.2);
 3865:                                     $locmodtime = (stat($fname))[9];
 3866:                                     if ($locmodtime < $remmodtime) {
 3867:                                         my $posstransfer = $fname.'.in.transfer';
 3868:                                         if ((-e $posstransfer) && ($remmodtime < (stat($posstransfer))[9])) {
 3869:                                             $removed = 1;
 3870:                                         } else {
 3871:                                             $stale = 1;
 3872:                                         }
 3873:                                     } else {
 3874:                                         $removed = 1;
 3875:                                     }
 3876:                                 } else {
 3877:                                     $stale = 1;
 3878:                                 }
 3879:                                 if ($stale) {
 3880:                                     if (unlink($fname)) {
 3881:                                         if ($uri!~/\.meta$/) {
 3882:                                             if (-e $fname.'.meta') {
 3883:                                                 unlink($fname.'.meta');
 3884:                                             }
 3885:                                         }
 3886:                                         my $unsubresult = &unsubscribe($fname);
 3887:                                         unless ($unsubresult eq 'ok') {
 3888:                                             &logthis("no unsub of $fname from $homeserver, reason: $unsubresult");
 3889:                                         }
 3890:                                         $removed = 1;
 3891:                                     }
 3892:                                 }
 3893:                             }
 3894:                         }
 3895:                     }
 3896:                 }
 3897:             }
 3898:         }
 3899:     }
 3900:     return $removed;
 3901: }
 3902: 
 3903: # -------------------------------- Allow a /uploaded/ URI to be vouched for
 3904: 
 3905: sub allowuploaded {
 3906:     my ($srcurl,$url)=@_;
 3907:     $url=&clutter(&declutter($url));
 3908:     my $dir=$url;
 3909:     $dir=~s/\/[^\/]+$//;
 3910:     my %httpref=();
 3911:     my $httpurl=&hreflocation('',$url);
 3912:     $httpref{'httpref.'.$httpurl}=$srcurl;
 3913:     &Apache::lonnet::appenv(\%httpref);
 3914: }
 3915: 
 3916: #
 3917: # Determine if the current user should be able to edit a particular resource,
 3918: # when viewing in course context.
 3919: # (a) When viewing resource used to determine if "Edit" item is included in 
 3920: #     Functions.
 3921: # (b) When displaying folder contents in course editor, used to determine if
 3922: #     "Edit" link will be displayed alongside resource.
 3923: #
 3924: #  input: six args -- filename (decluttered), course number, course domain,
 3925: #                   url, symb (if registered) and group (if this is a group
 3926: #                   item -- e.g., bulletin board, group page etc.).
 3927: #  output: array of five scalars -- 
 3928: #          $cfile -- url for file editing if editable on current server
 3929: #          $home -- homeserver of resource (i.e., for author if published,
 3930: #                                           or course if uploaded.).
 3931: #          $switchserver --  1 if server switch will be needed.
 3932: #          $forceedit -- 1 if icon/link should be to go to edit mode 
 3933: #          $forceview -- 1 if icon/link should be to go to view mode
 3934: #
 3935: 
 3936: sub can_edit_resource {
 3937:     my ($file,$cnum,$cdom,$resurl,$symb,$group) = @_;
 3938:     my ($cfile,$home,$switchserver,$forceedit,$forceview,$uploaded,$incourse);
 3939: #
 3940: # For aboutme pages user can only edit his/her own.
 3941: #
 3942:     if ($resurl =~ m{^/?adm/($match_domain)/($match_username)/aboutme$}) {
 3943:         my ($sdom,$sname) = ($1,$2);
 3944:         if (($sdom eq $env{'user.domain'}) && ($sname eq $env{'user.name'})) {
 3945:             $home = $env{'user.home'};
 3946:             $cfile = $resurl;
 3947:             if ($env{'form.forceedit'}) {
 3948:                 $forceview = 1;
 3949:             } else {
 3950:                 $forceedit = 1;
 3951:             }
 3952:             return ($cfile,$home,$switchserver,$forceedit,$forceview);
 3953:         } else {
 3954:             return;
 3955:         }
 3956:     }
 3957: 
 3958: #
 3959: # For /adm/viewcoauthors can only edit if author or co-author who is manager.
 3960: #
 3961: 
 3962:     if (($resurl eq '/adm/viewcoauthors') && ($cnum ne '') && ($cdom ne '')) {
 3963:         if (((&allowed('cca',"$cdom/$cnum")) ||
 3964:              (&allowed('caa',"$cdom/$cnum"))) ||
 3965:              ((&allowed('vca',"$cdom/$cnum") ||
 3966:                &allowed('vaa',"$cdom/$cnum")) &&
 3967:               ($env{"environment.internal.manager./$cdom/$cnum"}))) {
 3968:             $home = $env{'user.home'};
 3969:             $cfile = $resurl;
 3970:             if ($env{'form.forceedit'}) {
 3971:                 $forceview = 1;
 3972:             } else {
 3973:                 $forceedit = 1;
 3974:             }
 3975:             return ($cfile,$home,$switchserver,$forceedit,$forceview);
 3976:         } else {
 3977:             return;
 3978:         }
 3979:     }
 3980: 
 3981:     if ($env{'request.course.id'}) {
 3982:         my $crsedit = &allowed('mdc',$env{'request.course.id'});
 3983:         if ($group ne '') {
 3984: # if this is a group homepage or group bulletin board, check group privs
 3985:             my $allowed = 0;
 3986:             if ($resurl =~ m{^/?adm/$cdom/$cnum/$group/smppg$}) {
 3987:                 if ((&allowed('mdg',$env{'request.course.id'}.
 3988:                               ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
 3989:                         (&allowed('mgh',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
 3990:                     $allowed = 1;
 3991:                 }
 3992:             } elsif ($resurl =~ m{^/?adm/$cdom/$cnum/\d+/bulletinboard$}) {
 3993:                 if ((&allowed('mdg',$env{'request.course.id'}.($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
 3994:                         (&allowed('cgb',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
 3995:                     $allowed = 1;
 3996:                 }
 3997:             }
 3998:             if ($allowed) {
 3999:                 $home=&homeserver($cnum,$cdom);
 4000:                 if ($env{'form.forceedit'}) {
 4001:                     $forceview = 1;
 4002:                 } else {
 4003:                     $forceedit = 1;
 4004:                 }
 4005:                 $cfile = $resurl;
 4006:             } else {
 4007:                 return;
 4008:             }
 4009:         } else {
 4010:             if ($resurl =~ m{^/?adm/viewclasslist$}) {
 4011:                 unless (&allowed('opa',$env{'request.course.id'})) {
 4012:                     return;
 4013:                 }
 4014:             } elsif (!$crsedit) {
 4015:                 if ($env{'request.role'} =~ m{^st\./$cdom/$cnum}) {
 4016: #
 4017: # No edit allowed where CC has switched to student role.
 4018: #
 4019:                     return;
 4020:                 } elsif (($resurl !~ m{^/res/$match_domain/$match_username/}) ||
 4021:                          ($resurl =~ m{^/res/lib/templates/})) {
 4022:                     return;
 4023:                 }
 4024:             }
 4025:         }
 4026:     }
 4027: 
 4028:     if ($file ne '') {
 4029:         if (($cnum =~ /$match_courseid/) && ($cdom =~ /$match_domain/)) {
 4030:             if (&is_course_upload($file,$cnum,$cdom)) {
 4031:                 $uploaded = 1;
 4032:                 $incourse = 1;
 4033:                 if ($file =~/\.(htm|html|css|js|txt)$/) {
 4034:                     $cfile = &hreflocation('',$file);
 4035:                     if ($env{'form.forceedit'}) {
 4036:                         $forceview = 1;
 4037:                     } else {
 4038:                         $forceedit = 1;
 4039:                     }
 4040:                 }
 4041:             } elsif ($resurl =~ m{^/public/$cdom/$cnum/syllabus}) {
 4042:                 $incourse = 1;
 4043:                 if ($env{'form.forceedit'}) {
 4044:                     $forceview = 1;
 4045:                 } else {
 4046:                     $forceedit = 1;
 4047:                 }
 4048:                 $cfile = $resurl;
 4049:             } elsif (($resurl ne '') && (&is_on_map($resurl))) {
 4050:                 if ($resurl =~ m{^/adm/$match_domain/$match_username/\d+/smppg|bulletinboard$}) {
 4051:                     $incourse = 1;
 4052:                     if ($env{'form.forceedit'}) {
 4053:                         $forceview = 1;
 4054:                     } else {
 4055:                         $forceedit = 1;
 4056:                     }
 4057:                     $cfile = $resurl;
 4058:                 } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem') {
 4059:                     $incourse = 1;
 4060:                     $cfile = $resurl.'/smpedit';
 4061:                 } elsif ($resurl =~ m{^/adm/wrapper/ext/}) {
 4062:                     $incourse = 1;
 4063:                     if ($env{'form.forceedit'}) {
 4064:                         $forceview = 1;
 4065:                     } else {
 4066:                         $forceedit = 1;
 4067:                     }
 4068:                     $cfile = $resurl;
 4069:                 } elsif (($resurl =~ m{^/ext/}) && ($symb ne '')) {
 4070:                     my ($map,$id,$res) = &decode_symb($symb);
 4071:                     if ($map =~ /\.page$/) {
 4072:                         $incourse = 1;
 4073:                         if ($env{'form.forceedit'}) {
 4074:                             $forceview = 1;
 4075:                             $cfile = $map;
 4076:                         } else {
 4077:                             $forceedit = 1;
 4078:                             $cfile =  '/adm/wrapper'.$resurl;
 4079:                         }
 4080:                     }
 4081:                 } elsif ($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/ext\.tool$}) {
 4082:                     $incourse = 1;
 4083:                     if ($env{'form.forceedit'}) {
 4084:                         $forceview = 1;
 4085:                     } else {
 4086:                         $forceedit = 1;
 4087:                     }
 4088:                     $cfile = $resurl;
 4089:                 } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
 4090:                     $incourse = 1;
 4091:                     if ($env{'form.forceedit'}) {
 4092:                         $forceview = 1;
 4093:                     } else {
 4094:                         $forceedit = 1;
 4095:                     }
 4096:                     $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
 4097:                 }
 4098:             } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem/smpedit') {
 4099:                 my $template = '/res/lib/templates/simpleproblem.problem';
 4100:                 if (&is_on_map($template)) { 
 4101:                     $incourse = 1;
 4102:                     $forceview = 1;
 4103:                     $cfile = $template;
 4104:                 }
 4105:             } elsif (($resurl =~ m{^/adm/wrapper/ext/}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
 4106:                 $incourse = 1;
 4107:                 if ($env{'form.forceedit'}) {
 4108:                     $forceview = 1;
 4109:                 } else {
 4110:                     $forceedit = 1;
 4111:                 }
 4112:                 $cfile = $resurl;
 4113:             } elsif (($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/ext\.tool$}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
 4114:                 $incourse = 1;
 4115:                 if ($env{'form.forceedit'}) {
 4116:                     $forceview = 1;
 4117:                 } else {
 4118:                     $forceedit = 1;
 4119:                 }
 4120:                 $cfile = $resurl;
 4121:             } elsif (($resurl eq '/adm/extresedit') && ($symb || $env{'form.folderpath'})) {
 4122:                 $incourse = 1;
 4123:                 $forceview = 1;
 4124:                 if ($symb) {
 4125:                     my ($map,$id,$res)=&decode_symb($symb);
 4126:                     $env{'request.symb'} = $symb;
 4127:                     $cfile = &clutter($res);
 4128:                 } else {
 4129:                     $cfile = $env{'form.suppurl'};
 4130:                     my $escfile = &unescape($cfile);
 4131:                     if ($escfile =~ m{^/adm/$cdom/$cnum/\d+/ext\.tool$}) {
 4132:                         $cfile = '/adm/wrapper'.$escfile;
 4133:                     } else {
 4134:                         $escfile =~ s{^http://}{};
 4135:                         $cfile = &escape("/adm/wrapper/ext/$escfile");
 4136:                     }
 4137:                 }
 4138:             } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
 4139:                 if ($env{'form.forceedit'}) {
 4140:                     $forceview = 1;
 4141:                 } else {
 4142:                     $forceedit = 1;
 4143:                 }
 4144:                 $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
 4145:             }
 4146:         }
 4147:         if ($uploaded || $incourse) {
 4148:             $home=&homeserver($cnum,$cdom);
 4149:         } elsif ($file !~ m{/$}) {
 4150:             $file=~s{^(priv/$match_domain/$match_username)}{/$1};
 4151:             $file=~s{^($match_domain/$match_username)}{/priv/$1};
 4152:             # Check that the user has permission to edit this resource
 4153:             my $setpriv = 1;
 4154:             my ($cfuname,$cfudom)=&constructaccess($file,$setpriv);
 4155:             if (defined($cfudom)) {
 4156:                 $home=&homeserver($cfuname,$cfudom);
 4157:                 $cfile=$file;
 4158:             }
 4159:         }
 4160:         if (($cfile ne '') && (!$incourse || $uploaded) && 
 4161:             (($home ne '') && ($home ne 'no_host'))) {
 4162:             my @ids=&current_machine_ids();
 4163:             unless (grep(/^\Q$home\E$/,@ids)) {
 4164:                 $switchserver=1;
 4165:             }
 4166:         }
 4167:     }
 4168:     return ($cfile,$home,$switchserver,$forceedit,$forceview);
 4169: }
 4170: 
 4171: sub is_course_upload {
 4172:     my ($file,$cnum,$cdom) = @_;
 4173:     my $uploadpath = &LONCAPA::propath($cdom,$cnum);
 4174:     $uploadpath =~ s{^\/}{};
 4175:     if (($file =~ m{^\Q$uploadpath\E/userfiles/(docs|supplemental)/}) ||
 4176:         ($file =~ m{^userfiles/\Q$cdom\E/\Q$cnum\E/(docs|supplemental)/})) {
 4177:         return 1;
 4178:     }
 4179:     return;
 4180: }
 4181: 
 4182: sub in_course {
 4183:     my ($udom,$uname,$cdom,$cnum,$type,$hideprivileged) = @_;
 4184:     if ($hideprivileged) {
 4185:         my $skipuser;
 4186:         my %coursehash = &coursedescription($cdom.'_'.$cnum);
 4187:         my @possdoms = ($cdom);  
 4188:         if ($coursehash{'checkforpriv'}) { 
 4189:             push(@possdoms,split(/,/,$coursehash{'checkforpriv'})); 
 4190:         }
 4191:         if (&privileged($uname,$udom,\@possdoms)) {
 4192:             $skipuser = 1;
 4193:             if ($coursehash{'nothideprivileged'}) {
 4194:                 foreach my $item (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 4195:                     my $user;
 4196:                     if ($item =~ /:/) {
 4197:                         $user = $item;
 4198:                     } else {
 4199:                         $user = join(':',split(/[\@]/,$item));
 4200:                     }
 4201:                     if ($user eq $uname.':'.$udom) {
 4202:                         undef($skipuser);
 4203:                         last;
 4204:                     }
 4205:                 }
 4206:             }
 4207:             if ($skipuser) {
 4208:                 return 0;
 4209:             }
 4210:         }
 4211:     }
 4212:     $type ||= 'any';
 4213:     if (!defined($cdom) || !defined($cnum)) {
 4214:         my $cid  = $env{'request.course.id'};
 4215:         $cdom = $env{'course.'.$cid.'.domain'};
 4216:         $cnum = $env{'course.'.$cid.'.num'};
 4217:     }
 4218:     my $typesref;
 4219:     if (($type eq 'any') || ($type eq 'all')) {
 4220:         $typesref = ['active','previous','future'];
 4221:     } elsif ($type eq 'previous' || $type eq 'future') {
 4222:         $typesref = [$type];
 4223:     }
 4224:     my %roles = &get_my_roles($uname,$udom,'userroles',
 4225:                               $typesref,undef,[$cdom]);
 4226:     my ($tmp) = keys(%roles);
 4227:     return 0 if ($tmp =~ /^(con_lost|error|no_such_host)/i);
 4228:     my @course_roles = grep(/^\Q$cnum\E:\Q$cdom\E:/, keys(%roles));
 4229:     if (@course_roles > 0) {
 4230:         return 1;
 4231:     }
 4232:     return 0;
 4233: }
 4234: 
 4235: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
 4236: # input: action, courseID, current domain, intended
 4237: #        path to file, source of file, instruction to parse file for objects,
 4238: #        ref to hash for embedded objects,
 4239: #        ref to hash for codebase of java objects.
 4240: #        reference to scalar to accommodate mime type determined
 4241: #          from File::MMagic if $parser = parse.
 4242: #
 4243: # output: url to file (if action was uploaddoc), 
 4244: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
 4245: #
 4246: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
 4247: # course.
 4248: #
 4249: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 4250: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
 4251: #          course's home server.
 4252: #
 4253: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
 4254: #          be copied from $source (current location) to 
 4255: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 4256: #         and will then be copied to
 4257: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
 4258: #         course's home server.
 4259: #
 4260: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 4261: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
 4262: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 4263: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
 4264: #         in course's home server.
 4265: #
 4266: 
 4267: sub process_coursefile {
 4268:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
 4269:         $mimetype)=@_;
 4270:     my $fetchresult;
 4271:     my $home=&homeserver($docuname,$docudom);
 4272:     if ($action eq 'propagate') {
 4273:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 4274: 			     $home);
 4275:     } else {
 4276:         my $fpath = '';
 4277:         my $fname = $file;
 4278:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 4279:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 4280:         my $filepath = &build_filepath($fpath);
 4281:         if ($action eq 'copy') {
 4282:             if ($source eq '') {
 4283:                 $fetchresult = 'no source file';
 4284:                 return $fetchresult;
 4285:             } else {
 4286:                 my $destination = $filepath.'/'.$fname;
 4287:                 rename($source,$destination);
 4288:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 4289:                                  $home);
 4290:             }
 4291:         } elsif ($action eq 'uploaddoc') {
 4292:             open(my $fh,'>',$filepath.'/'.$fname);
 4293:             print $fh $env{'form.'.$source};
 4294:             close($fh);
 4295:             if ($parser eq 'parse') {
 4296:                 my $mm = new File::MMagic;
 4297:                 my $type = $mm->checktype_filename($filepath.'/'.$fname);
 4298:                 if ($type eq 'text/html') {
 4299:                     my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
 4300:                     unless ($parse_result eq 'ok') {
 4301:                         &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
 4302:                     }
 4303:                 }
 4304:                 if (ref($mimetype)) {
 4305:                     $$mimetype = $type;
 4306:                 } 
 4307:             }
 4308:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 4309:                                  $home);
 4310:             if ($fetchresult eq 'ok') {
 4311:                 return '/uploaded/'.$fpath.'/'.$fname;
 4312:             } else {
 4313:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 4314:                         ' to host '.$home.': '.$fetchresult);
 4315:                 return '/adm/notfound.html';
 4316:             }
 4317:         }
 4318:     }
 4319:     unless ( $fetchresult eq 'ok') {
 4320:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 4321:              ' to host '.$home.': '.$fetchresult);
 4322:     }
 4323:     return $fetchresult;
 4324: }
 4325: 
 4326: sub build_filepath {
 4327:     my ($fpath) = @_;
 4328:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
 4329:     unless ($fpath eq '') {
 4330:         my @parts=split('/',$fpath);
 4331:         foreach my $part (@parts) {
 4332:             $filepath.= '/'.$part;
 4333:             if ((-e $filepath)!=1) {
 4334:                 mkdir($filepath,0777);
 4335:             }
 4336:         }
 4337:     }
 4338:     return $filepath;
 4339: }
 4340: 
 4341: sub store_edited_file {
 4342:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
 4343:     my $file = $primary_url;
 4344:     $file =~ s#^/uploaded/$docudom/$docuname/##;
 4345:     my $fpath = '';
 4346:     my $fname = $file;
 4347:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 4348:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 4349:     my $filepath = &build_filepath($fpath);
 4350:     open(my $fh,'>',$filepath.'/'.$fname);
 4351:     print $fh $content;
 4352:     close($fh);
 4353:     my $home=&homeserver($docuname,$docudom);
 4354:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 4355: 			  $home);
 4356:     if ($$fetchresult eq 'ok') {
 4357:         return '/uploaded/'.$fpath.'/'.$fname;
 4358:     } else {
 4359:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 4360: 		 ' to host '.$home.': '.$$fetchresult);
 4361:         return '/adm/notfound.html';
 4362:     }
 4363: }
 4364: 
 4365: sub clean_filename {
 4366:     my ($fname,$args)=@_;
 4367: # Replace Windows backslashes by forward slashes
 4368:     $fname=~s/\\/\//g;
 4369:     if (!$args->{'keep_path'}) {
 4370:         # Get rid of everything but the actual filename
 4371: 	$fname=~s/^.*\/([^\/]+)$/$1/;
 4372:     }
 4373: # Replace spaces by underscores
 4374:     $fname=~s/\s+/\_/g;
 4375: # Transliterate non-ascii text to ascii
 4376:     my $lang = &Apache::lonlocal::current_language();
 4377:     $fname = &LONCAPA::transliterate::fname_to_ascii($fname,$lang);
 4378: # Replace all other weird characters by nothing
 4379:     $fname=~s{[^/\w\.\-]}{}g;
 4380: # Replace all .\d. sequences with _\d. so they no longer look like version
 4381: # numbers
 4382:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
 4383: # Replace three or more adjacent underscores with one for consistency 
 4384: # with loncfile::filename_check() so complete url can be extracted by
 4385: # lonnet::decode_symb()
 4386:     $fname=~s/_{3,}/_/g;
 4387:     return $fname;
 4388: }
 4389: 
 4390: # This Function checks if an Image's dimensions exceed either $resizewidth (width) 
 4391: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an 
 4392: # image with the same aspect ratio as the original, but with dimensions which do 
 4393: # not exceed $resizewidth and $resizeheight.
 4394:  
 4395: sub resizeImage {
 4396:     my ($img_path,$resizewidth,$resizeheight) = @_;
 4397:     my $ima = Image::Magick->new;
 4398:     my $resized;
 4399:     if (-e $img_path) {
 4400:         $ima->Read($img_path);
 4401:         if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
 4402:             my $width = $ima->Get('width');
 4403:             my $height = $ima->Get('height');
 4404:             if ($width > $resizewidth) {
 4405: 	        my $factor = $width/$resizewidth;
 4406:                 my $newheight = $height/$factor;
 4407:                 $ima->Scale(width=>$resizewidth,height=>$newheight);
 4408:                 $resized = 1;
 4409:             }
 4410:         }
 4411:         if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
 4412:             my $width = $ima->Get('width');
 4413:             my $height = $ima->Get('height');
 4414:             if ($height > $resizeheight) {
 4415:                 my $factor = $height/$resizeheight;
 4416:                 my $newwidth = $width/$factor;
 4417:                 $ima->Scale(width=>$newwidth,height=>$resizeheight);
 4418:                 $resized = 1;
 4419:             }
 4420:         }
 4421:         if ($resized) {
 4422:             $ima->Write($img_path);
 4423:         }
 4424:     }
 4425:     return;
 4426: }
 4427: 
 4428: # --------------- Take an uploaded file and put it into the userfiles directory
 4429: # input: $formname - the contents of the file are in $env{"form.$formname"}
 4430: #                    the desired filename is in $env{"form.$formname.filename"}
 4431: #        $context - possible values: coursedoc, existingfile, overwrite, 
 4432: #                                    canceloverwrite, scantron, toollogo  or ''.
 4433: #                   if 'coursedoc': upload to the current course
 4434: #                   if 'existingfile': write file to tmp/overwrites directory 
 4435: #                   if 'canceloverwrite': delete file written to tmp/overwrites directory
 4436: #                   $context is passed as argument to &finishuserfileupload
 4437: #        $subdir - directory in userfile to store the file into
 4438: #        $parser - instruction to parse file for objects ($parser = parse) or
 4439: #                  if context is 'scantron', $parser is hashref of csv column mapping
 4440: #                  (e.g.,{ PaperID => 0, LastName => 1, FirstName => 2, ID => 3, 
 4441: #                          Section => 4, CODE => 5, FirstQuestion => 9 }).
 4442: #        $allfiles - reference to hash for embedded objects
 4443: #        $codebase - reference to hash for codebase of java objects
 4444: #        $destuname - username for permanent storage of uploaded file
 4445: #        $destudom - domain for permanaent storage of uploaded file
 4446: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
 4447: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
 4448: #        $resizewidth - width (pixels) to which to resize uploaded image
 4449: #        $resizeheight - height (pixels) to which to resize uploaded image
 4450: #        $mimetype - reference to scalar to accommodate mime type determined
 4451: #                    from File::MMagic.
 4452: # 
 4453: # output: url of file in userspace, or error: <message> 
 4454: #             or /adm/notfound.html if failure to upload occurse
 4455: 
 4456: sub userfileupload {
 4457:     my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
 4458:         $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
 4459:     if (!defined($subdir)) { $subdir='unknown'; }
 4460:     my $fname=$env{'form.'.$formname.'.filename'};
 4461:     $fname=&clean_filename($fname);
 4462:     # See if there is anything left
 4463:     unless ($fname) { return 'error: no uploaded file'; }
 4464:     # If filename now begins with a . prepend unix timestamp _ milliseconds
 4465:     if ($fname =~ /^\./) {
 4466:         my ($s,$usec) = &gettimeofday();
 4467:         while (length($usec) < 6) {
 4468:             $usec = '0'.$usec;
 4469:         }
 4470:         $fname = $s.'_'.substr($usec,0,3).$fname;
 4471:     }
 4472:     # Files uploaded to help request form, or uploaded to "create course" page are handled differently
 4473:     if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
 4474:         (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
 4475:          ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
 4476:         my $now = time;
 4477:         my $filepath;
 4478:         if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
 4479:              $filepath = 'tmp/helprequests/'.$now;
 4480:         } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
 4481:              $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
 4482:                          '_'.$env{'user.domain'}.'/pending';
 4483:         } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
 4484:             my ($docuname,$docudom);
 4485:             if ($destudom =~ /^$match_domain$/) {
 4486:                 $docudom = $destudom;
 4487:             } else {
 4488:                 $docudom = $env{'user.domain'};
 4489:             }
 4490:             if ($destuname =~ /^$match_username$/) {
 4491:                 $docuname = $destuname;
 4492:             } else {
 4493:                 $docuname = $env{'user.name'};
 4494:             }
 4495:             if (exists($env{'form.group'})) {
 4496:                 $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 4497:                 $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 4498:             }
 4499:             $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
 4500:             if ($context eq 'canceloverwrite') {
 4501:                 my $tempfile =  $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
 4502:                 if (-e  $tempfile) {
 4503:                     my @info = stat($tempfile);
 4504:                     if ($info[9] eq $env{'form.timestamp'}) {
 4505:                         unlink($tempfile);
 4506:                     }
 4507:                 }
 4508:                 return;
 4509:             }
 4510:         }
 4511:         # Create the directory if not present
 4512:         my @parts=split(/\//,$filepath);
 4513:         my $fullpath = $perlvar{'lonDaemons'};
 4514:         for (my $i=0;$i<@parts;$i++) {
 4515:             $fullpath .= '/'.$parts[$i];
 4516:             if ((-e $fullpath)!=1) {
 4517:                 mkdir($fullpath,0777);
 4518:             }
 4519:         }
 4520:         open(my $fh,'>',$fullpath.'/'.$fname);
 4521:         print $fh $env{'form.'.$formname};
 4522:         close($fh);
 4523:         if ($context eq 'existingfile') {
 4524:             my @info = stat($fullpath.'/'.$fname);
 4525:             return ($fullpath.'/'.$fname,$info[9]);
 4526:         } else {
 4527:             return $fullpath.'/'.$fname;
 4528:         }
 4529:     }
 4530:     if ($subdir eq 'scantron') {
 4531:         $fname = 'scantron_orig_'.$fname;
 4532:     } else {
 4533:         $fname="$subdir/$fname";
 4534:     }
 4535:     if ($context eq 'coursedoc') {
 4536: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 4537: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 4538:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
 4539:             return &finishuserfileupload($docuname,$docudom,
 4540: 					 $formname,$fname,$parser,$allfiles,
 4541: 					 $codebase,$thumbwidth,$thumbheight,
 4542:                                          $resizewidth,$resizeheight,$context,$mimetype);
 4543:         } else {
 4544:             if ($env{'form.folder'}) {
 4545:                 $fname=$env{'form.folder'}.'/'.$fname;
 4546:             }
 4547:             return &process_coursefile('uploaddoc',$docuname,$docudom,
 4548: 				       $fname,$formname,$parser,
 4549: 				       $allfiles,$codebase,$mimetype);
 4550:         }
 4551:     } elsif (defined($destuname)) {
 4552:         my $docuname=$destuname;
 4553:         my $docudom=$destudom;
 4554: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
 4555: 				     $parser,$allfiles,$codebase,
 4556:                                      $thumbwidth,$thumbheight,
 4557:                                      $resizewidth,$resizeheight,$context,$mimetype);
 4558:     } else {
 4559:         my $docuname=$env{'user.name'};
 4560:         my $docudom=$env{'user.domain'};
 4561:         if ((exists($env{'form.group'})) || ($context eq 'syllabus')) {
 4562:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 4563:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 4564:         }
 4565: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
 4566: 				     $parser,$allfiles,$codebase,
 4567:                                      $thumbwidth,$thumbheight,
 4568:                                      $resizewidth,$resizeheight,$context,$mimetype);
 4569:     }
 4570: }
 4571: 
 4572: sub finishuserfileupload {
 4573:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
 4574:         $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
 4575:     my $path=$docudom.'/'.$docuname.'/';
 4576:     my $filepath=$perlvar{'lonDocRoot'};
 4577:   
 4578:     my ($fnamepath,$file,$fetchthumb);
 4579:     $file=$fname;
 4580:     if ($fname=~m|/|) {
 4581:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
 4582: 	$path.=$fnamepath.'/';
 4583:     }
 4584:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
 4585:     my $count;
 4586:     for ($count=4;$count<=$#parts;$count++) {
 4587:         $filepath.="/$parts[$count]";
 4588:         if ((-e $filepath)!=1) {
 4589: 	    mkdir($filepath,0777);
 4590:         }
 4591:     }
 4592: 
 4593: # Save the file
 4594:     {
 4595: 	if (!open(FH,'>',$filepath.'/'.$file)) {
 4596: 	    &logthis('Failed to create '.$filepath.'/'.$file);
 4597: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
 4598: 	    return '/adm/notfound.html';
 4599: 	}
 4600:         if ($context eq 'overwrite') {
 4601:             my $source =  LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
 4602:             my $target = $filepath.'/'.$file;
 4603:             if (-e $source) {
 4604:                 my @info = stat($source);
 4605:                 if ($info[9] eq $env{'form.timestamp'}) {   
 4606:                     unless (&File::Copy::move($source,$target)) {
 4607:                         &logthis('Failed to overwrite '.$filepath.'/'.$file);
 4608:                         return "Moving from $source failed";
 4609:                     }
 4610:                 } else {
 4611:                     return "Temporary file: $source had unexpected date/time for last modification";
 4612:                 }
 4613:             } else {
 4614:                 return "Temporary file: $source missing";
 4615:             }
 4616:         } elsif (!print FH ($env{'form.'.$formname})) {
 4617: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
 4618: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
 4619: 	    return '/adm/notfound.html';
 4620: 	}
 4621: 	close(FH);
 4622:         if ($resizewidth && $resizeheight) {
 4623:             my $mm = new File::MMagic;
 4624:             my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
 4625:             if ($mime_type =~ m{^image/}) {
 4626: 	        &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
 4627:             }  
 4628: 	}
 4629:     }
 4630:     if (($context eq 'coursedoc') || ($parser eq 'parse')) {
 4631:         if (ref($mimetype)) {
 4632:             if ($$mimetype eq '') {
 4633:                 my $mm = new File::MMagic;
 4634:                 my $type = $mm->checktype_filename($filepath.'/'.$file);
 4635:                 $$mimetype = $type;
 4636:             }
 4637:         }
 4638:     }
 4639:     if (($context ne 'scantron') && ($parser eq 'parse')) {
 4640:         if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
 4641:             my $parse_result = &extract_embedded_items($filepath.'/'.$file,
 4642:                                                        $allfiles,$codebase);
 4643:             unless ($parse_result eq 'ok') {
 4644:                 &logthis('Failed to parse '.$filepath.$file.
 4645: 	   	         ' for embedded media: '.$parse_result); 
 4646:             }
 4647:         }
 4648:     } elsif (($context eq 'scantron') && (ref($parser) eq 'HASH')) {
 4649:         my $format = $env{'form.scantron_format'};
 4650:         &bubblesheet_converter($docudom,$filepath.'/'.$file,$parser,$format);
 4651:     }
 4652:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
 4653:         my $input = $filepath.'/'.$file;
 4654:         my $output = $filepath.'/'.'tn-'.$file;
 4655:         my $makethumb; 
 4656:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
 4657:         if ($context eq 'toollogo') {
 4658:             my ($fullwidth,$fullheight) = &check_dimensions($input);
 4659:             if ($fullwidth ne '' && $fullheight ne '') {
 4660:                 if ($fullwidth > $thumbwidth && $fullheight > $thumbheight) {
 4661:                     $makethumb = 1;
 4662:                 }
 4663:             }
 4664:         } else {
 4665:             $makethumb = 1;
 4666:         }
 4667:         if ($makethumb) {
 4668:             my @args = ('convert','-sample',$thumbsize,$input,$output);
 4669:             system({$args[0]} @args);
 4670:             if (-e $filepath.'/'.'tn-'.$file) {
 4671:                 $fetchthumb  = 1; 
 4672:             }
 4673:         }
 4674:     }
 4675:  
 4676: # Notify homeserver to grep it
 4677: #
 4678:     my $docuhome=&homeserver($docuname,$docudom);	
 4679:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
 4680:     if ($fetchresult eq 'ok') {
 4681:         if ($fetchthumb) {
 4682:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
 4683:             if ($thumbresult ne 'ok') {
 4684:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
 4685:                          $docuhome.': '.$thumbresult);
 4686:             }
 4687:         }
 4688: #
 4689: # Return the URL to it
 4690:         return '/uploaded/'.$path.$file;
 4691:     } else {
 4692:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
 4693: 		 ': '.$fetchresult);
 4694:         return '/adm/notfound.html';
 4695:     }
 4696: }
 4697: 
 4698: sub extract_embedded_items {
 4699:     my ($fullpath,$allfiles,$codebase,$content) = @_;
 4700:     my @state = ();
 4701:     my (%lastids,%related,%shockwave,%flashvars);
 4702:     my %javafiles = (
 4703:                       codebase => '',
 4704:                       code => '',
 4705:                       archive => ''
 4706:                     );
 4707:     my %mediafiles = (
 4708:                       src => '',
 4709:                       movie => '',
 4710:                      );
 4711:     my $p;
 4712:     if ($content) {
 4713:         $p = HTML::LCParser->new($content);
 4714:     } else {
 4715:         $p = HTML::LCParser->new($fullpath);
 4716:     }
 4717:     while (my $t=$p->get_token()) {
 4718: 	if ($t->[0] eq 'S') {
 4719: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
 4720: 	    push(@state, $tagname);
 4721:             if (lc($tagname) eq 'allow') {
 4722:                 &add_filetype($allfiles,$attr->{'src'},'src');
 4723:             }
 4724: 	    if (lc($tagname) eq 'img') {
 4725: 		&add_filetype($allfiles,$attr->{'src'},'src');
 4726: 	    }
 4727: 	    if (lc($tagname) eq 'a') {
 4728:                 unless (($attr->{'href'} =~ /^#/) || ($attr->{'href'} eq '')) {
 4729:                     &add_filetype($allfiles,$attr->{'href'},'href');
 4730:                 }
 4731: 	    }
 4732:             if (lc($tagname) eq 'script') {
 4733:                 my $src;
 4734:                 if ($attr->{'archive'} =~ /\.jar$/i) {
 4735:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
 4736:                 } else {
 4737:                     if ($attr->{'src'} ne '') {
 4738:                         $src = $attr->{'src'};
 4739:                         &add_filetype($allfiles,$src,'src');
 4740:                     }
 4741:                 }
 4742:                 my $text = $p->get_trimmed_text();
 4743:                 if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
 4744:                     my @swfargs = split(/,/,$1);
 4745:                     foreach my $item (@swfargs) {
 4746:                         $item =~ s/["']//g;
 4747:                         $item =~ s/^\s+//;
 4748:                         $item =~ s/\s+$//;
 4749:                     }
 4750:                     if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
 4751:                         if (ref($related{$swfargs[0]}) eq 'ARRAY') {
 4752:                             push(@{$related{$swfargs[0]}},$swfargs[2]);
 4753:                         } else {
 4754:                             $related{$swfargs[0]} = [$swfargs[2]];
 4755:                         }
 4756:                     }
 4757:                 }
 4758:             }
 4759:             if (lc($tagname) eq 'link') {
 4760:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
 4761:                     &add_filetype($allfiles,$attr->{'href'},'href');
 4762:                 }
 4763:             }
 4764: 	    if (lc($tagname) eq 'object' ||
 4765: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
 4766: 		foreach my $item (keys(%javafiles)) {
 4767: 		    $javafiles{$item} = '';
 4768: 		}
 4769:                 if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
 4770:                     $lastids{lc($tagname)} = $attr->{'id'};
 4771:                 }
 4772: 	    }
 4773: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
 4774: 		my $name = lc($attr->{'name'});
 4775: 		foreach my $item (keys(%javafiles)) {
 4776: 		    if ($name eq $item) {
 4777: 			$javafiles{$item} = $attr->{'value'};
 4778: 			last;
 4779: 		    }
 4780: 		}
 4781:                 my $pathfrom;
 4782: 		foreach my $item (keys(%mediafiles)) {
 4783: 		    if ($name eq $item) {
 4784:                         $pathfrom = $attr->{'value'};
 4785:                         $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
 4786: 			&add_filetype($allfiles,$pathfrom,$name);
 4787: 			last;
 4788: 		    }
 4789: 		}
 4790:                 if ($name eq 'flashvars') {
 4791:                     $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
 4792:                 }
 4793:                 if ($pathfrom ne '') {
 4794:                     &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
 4795:                                          $pathfrom);
 4796:                 }
 4797: 	    }
 4798: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
 4799: 		foreach my $item (keys(%javafiles)) {
 4800: 		    if ($attr->{$item}) {
 4801: 			$javafiles{$item} = $attr->{$item};
 4802: 			last;
 4803: 		    }
 4804: 		}
 4805: 		foreach my $item (keys(%mediafiles)) {
 4806: 		    if ($attr->{$item}) {
 4807: 			&add_filetype($allfiles,$attr->{$item},$item);
 4808: 			last;
 4809: 		    }
 4810: 		}
 4811:                 if (lc($tagname) eq 'embed') {
 4812:                     if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
 4813:                         &embedded_dependency($allfiles,\%related,$attr->{'name'},
 4814:                                              $attr->{'src'});
 4815:                     }
 4816:                 }
 4817: 	    }
 4818:             if (lc($tagname) eq 'iframe') {
 4819:                 my $src = $attr->{'src'} ;
 4820:                 if (($src ne '') && ($src !~ m{^(/|https?://)})) {
 4821:                     &add_filetype($allfiles,$src,'src');
 4822:                 } elsif ($src =~ m{^/}) {
 4823:                     if ($env{'request.course.id'}) {
 4824:                         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 4825:                         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 4826:                         my $url = &hreflocation('',$fullpath);
 4827:                         if ($url =~ m{^/uploaded/$cdom/$cnum/docs/(\w+/\d+)/}) {
 4828:                             my $relpath = $1;
 4829:                             if ($src =~ m{^/uploaded/$cdom/$cnum/docs/\Q$relpath\E/(.+)$}) {
 4830:                                 &add_filetype($allfiles,$1,'src');
 4831:                             }
 4832:                         }
 4833:                     }
 4834:                 }
 4835:             }
 4836:             if ($t->[4] =~ m{/>$}) {
 4837:                 pop(@state);
 4838:             }
 4839: 	} elsif ($t->[0] eq 'E') {
 4840: 	    my ($tagname) = ($t->[1]);
 4841: 	    if ($javafiles{'codebase'} ne '') {
 4842: 		$javafiles{'codebase'} .= '/';
 4843: 	    }  
 4844: 	    if (lc($tagname) eq 'applet' ||
 4845: 		lc($tagname) eq 'object' ||
 4846: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
 4847: 		) {
 4848: 		foreach my $item (keys(%javafiles)) {
 4849: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
 4850: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
 4851: 			&add_filetype($allfiles,$file,$item);
 4852: 		    }
 4853: 		}
 4854: 	    } 
 4855: 	    pop @state;
 4856: 	}
 4857:     }
 4858:     foreach my $id (sort(keys(%flashvars))) {
 4859:         if ($shockwave{$id} ne '') {
 4860:             my @pairs = split(/\&/,$flashvars{$id});
 4861:             foreach my $pair (@pairs) {
 4862:                 my ($key,$value) = split(/\=/,$pair);
 4863:                 if ($key eq 'thumb') {
 4864:                     &add_filetype($allfiles,$value,$key);
 4865:                 } elsif ($key eq 'content') {
 4866:                     my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
 4867:                     my ($ext) = ($value =~ /\.([^.]+)$/);
 4868:                     if ($ext ne '') {
 4869:                         &add_filetype($allfiles,$path.$value,$ext);
 4870:                     }
 4871:                 }
 4872:             }
 4873:         }
 4874:     }
 4875:     return 'ok';
 4876: }
 4877: 
 4878: sub add_filetype {
 4879:     my ($allfiles,$file,$type)=@_;
 4880:     if (exists($allfiles->{$file})) {
 4881: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
 4882: 	    push(@{$allfiles->{$file}}, &escape($type));
 4883: 	}
 4884:     } else {
 4885: 	@{$allfiles->{$file}} = (&escape($type));
 4886:     }
 4887: }
 4888: 
 4889: sub embedded_dependency {
 4890:     my ($allfiles,$related,$identifier,$pathfrom) = @_;
 4891:     if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
 4892:         if (($identifier ne '') &&
 4893:             (ref($related->{$identifier}) eq 'ARRAY') &&
 4894:             ($pathfrom ne '')) {
 4895:             my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
 4896:             foreach my $dep (@{$related->{$identifier}}) {
 4897:                 &add_filetype($allfiles,$path.$dep,'object');
 4898:             }
 4899:         }
 4900:     }
 4901:     return;
 4902: }
 4903: 
 4904: sub check_dimensions {
 4905:     my ($inputfile) = @_;
 4906:     my ($fullwidth,$fullheight);
 4907:     if (($inputfile =~ m|^[/\w.\-]+$|) && (-e $inputfile)) {
 4908:         my $mm = new File::MMagic;
 4909:         my $mime_type = $mm->checktype_filename($inputfile);
 4910:         if ($mime_type =~ m{^image/}) {
 4911:             if (open(PIPE,"identify $inputfile 2>&1 |")) {
 4912:                 my $imageinfo = <PIPE>;
 4913:                 if (!close(PIPE)) {
 4914:                     &Apache::lonnet::logthis("Failed to close PIPE opened to retrieve image information for $inputfile");
 4915:                 }
 4916:                 chomp($imageinfo);
 4917:                 my ($fullsize) =
 4918:                     ($imageinfo =~ /^\Q$inputfile\E\s+\w+\s+(\d+x\d+)/);
 4919:                 if ($fullsize) {
 4920:                     ($fullwidth,$fullheight) = split(/x/,$fullsize);
 4921:                 }
 4922:             }
 4923:         }
 4924:     }
 4925:     return ($fullwidth,$fullheight);
 4926: }
 4927: 
 4928: sub bubblesheet_converter {
 4929:     my ($cdom,$fullpath,$config,$format) = @_;
 4930:     if ((&domain($cdom) ne '') &&
 4931:         ($fullpath =~ m{^\Q$perlvar{'lonDocRoot'}/userfiles/$cdom/\E$match_courseid/scantron_orig}) &&
 4932:         (-e $fullpath) && (ref($config) eq 'HASH') && ($format ne '')) {
 4933:         my (%csvcols,%csvoptions);
 4934:         if (ref($config->{'fields'}) eq 'HASH') {  
 4935:             %csvcols = %{$config->{'fields'}};
 4936:         }
 4937:         if (ref($config->{'options'}) eq 'HASH') {
 4938:             %csvoptions = %{$config->{'options'}};
 4939:         }
 4940:         my %csvbynum = reverse(%csvcols);
 4941:         my %scantronconf = &get_scantron_config($format,$cdom);
 4942:         if (keys(%scantronconf)) {
 4943:             my %bynum = (
 4944:                           $scantronconf{CODEstart} => 'CODEstart',
 4945:                           $scantronconf{IDstart}   => 'IDstart',
 4946:                           $scantronconf{PaperID}   => 'PaperID',
 4947:                           $scantronconf{FirstName} => 'FirstName',
 4948:                           $scantronconf{LastName}  => 'LastName',
 4949:                           $scantronconf{Qstart}    => 'Qstart',
 4950:                         );
 4951:             my @ordered;
 4952:             foreach my $item (sort { $a <=> $b } keys(%bynum)) {
 4953:                 push(@ordered,$bynum{$item});
 4954:             }
 4955:             my %mapstart = (
 4956:                               CODEstart => 'CODE',
 4957:                               IDstart   => 'ID',
 4958:                               PaperID   => 'PaperID',
 4959:                               FirstName => 'FirstName',
 4960:                               LastName  => 'LastName',
 4961:                               Qstart    => 'FirstQuestion',
 4962:                            );
 4963:             my %maplength = (
 4964:                               CODEstart => 'CODElength',
 4965:                               IDstart   => 'IDlength',
 4966:                               PaperID   => 'PaperIDlength',
 4967:                               FirstName => 'FirstNamelength',
 4968:                               LastName  => 'LastNamelength',
 4969:             );
 4970:             if (open(my $fh,'<',$fullpath)) {
 4971:                 my $output;
 4972:                 my %lettdig = &letter_to_digits();
 4973:                 my %diglett = reverse(%lettdig);
 4974:                 my $numletts = scalar(keys(%lettdig));
 4975:                 my $num = 0;
 4976:                 while (my $line=<$fh>) {
 4977:                     $num ++;
 4978:                     next if (($num == 1) && ($csvoptions{'hdr'} == 1));
 4979:                     $line =~ s{[\r\n]+$}{};
 4980:                     my %found;
 4981:                     my @values = split(/,/,$line,-1);
 4982:                     my ($qstart,$record);
 4983:                     for (my $i=0; $i<@values; $i++) {
 4984:                         if ((($qstart ne '') && ($i > $qstart)) ||
 4985:                             ($csvbynum{$i} eq 'FirstQuestion')) {
 4986:                             if ($values[$i] eq '') {
 4987:                                 $values[$i] = $scantronconf{'Qoff'};
 4988:                             } elsif ($scantronconf{'Qon'} eq 'number') {
 4989:                                 if ($values[$i] =~ /^[A-Ja-j]$/) {
 4990:                                     $values[$i] = $lettdig{uc($values[$i])};
 4991:                                 }
 4992:                             } elsif ($scantronconf{'Qon'} eq 'letter') {
 4993:                                 if ($values[$i] =~ /^[0-9]$/) {
 4994:                                     $values[$i] = $diglett{$values[$i]};
 4995:                                 }
 4996:                             } else {
 4997:                                 if ($values[$i] =~ /^[0-9A-Ja-j]$/) {
 4998:                                     my $digit;
 4999:                                     if ($values[$i] =~ /^[A-Ja-j]$/) {
 5000:                                         $digit = $lettdig{uc($values[$i])}-1;
 5001:                                         if ($values[$i] eq 'J') {
 5002:                                             $digit += $numletts;
 5003:                                         }
 5004:                                     } elsif ($values[$i] =~ /^[0-9]$/) {
 5005:                                         $digit = $values[$i]-1;
 5006:                                         if ($values[$i] eq '0') {
 5007:                                             $digit += $numletts;
 5008:                                         }
 5009:                                     }
 5010:                                     my $qval='';
 5011:                                     for (my $j=0; $j<$scantronconf{'Qlength'}; $j++) {
 5012:                                         if ($j == $digit) {
 5013:                                             $qval .= $scantronconf{'Qon'};
 5014:                                         } else {
 5015:                                             $qval .= $scantronconf{'Qoff'};
 5016:                                         }
 5017:                                     }
 5018:                                     $values[$i] = $qval;
 5019:                                 }
 5020:                             }
 5021:                             if (length($values[$i]) > $scantronconf{'Qlength'}) {
 5022:                                 $values[$i] = substr($values[$i],0,$scantronconf{'Qlength'});
 5023:                             }
 5024:                             my $numblank = $scantronconf{'Qlength'} - length($values[$i]);
 5025:                             if ($numblank > 0) {
 5026:                                  $values[$i] .= ($scantronconf{'Qoff'} x $numblank);
 5027:                             }
 5028:                             if ($csvbynum{$i} eq 'FirstQuestion') {
 5029:                                 $qstart = $i;
 5030:                                 $found{$csvbynum{$i}} = $values[$i];
 5031:                             } else {
 5032:                                 $found{'FirstQuestion'} .= $values[$i];
 5033:                             }
 5034:                         } elsif (exists($csvbynum{$i})) {
 5035:                             if ($csvoptions{'rem'}) {
 5036:                                 $values[$i] =~ s/^\s+//;
 5037:                             }
 5038:                             if (($csvbynum{$i} eq 'PaperID') && ($csvoptions{'pad'})) {
 5039:                                 while (length($values[$i]) < $scantronconf{$maplength{$csvbynum{$i}}}) {
 5040:                                     $values[$i] = '0'.$values[$i];
 5041:                                 }
 5042:                             }
 5043:                             $found{$csvbynum{$i}} = $values[$i];
 5044:                         }
 5045:                     }
 5046:                     foreach my $item (@ordered) {
 5047:                         my $currlength = 1+length($record);
 5048:                         my $numspaces = $scantronconf{$item} - $currlength;
 5049:                         if ($numspaces > 0) {
 5050:                             $record .= (' ' x $numspaces);
 5051:                         }
 5052:                         if (($mapstart{$item} ne '') && (exists($found{$mapstart{$item}}))) {
 5053:                             unless ($item eq 'Qstart') {
 5054:                                 if (length($found{$mapstart{$item}}) > $scantronconf{$maplength{$item}}) {
 5055:                                     $found{$mapstart{$item}} = substr($found{$mapstart{$item}},0,$scantronconf{$maplength{$item}});
 5056:                                 }
 5057:                             }
 5058:                             $record .= $found{$mapstart{$item}};
 5059:                         }
 5060:                     }
 5061:                     $output .= "$record\n";
 5062:                 }
 5063:                 close($fh);
 5064:                 if ($output) {
 5065:                     if (open(my $fh,'>',$fullpath)) {
 5066:                         print $fh $output;
 5067:                         close($fh);
 5068:                     }
 5069:                 }
 5070:             }
 5071:         }
 5072:         return;
 5073:     }
 5074: }
 5075: 
 5076: sub letter_to_digits {
 5077:     my %lettdig = (
 5078:                     A => 1,
 5079:                     B => 2,
 5080:                     C => 3,
 5081:                     D => 4,
 5082:                     E => 5,
 5083:                     F => 6,
 5084:                     G => 7,
 5085:                     H => 8,
 5086:                     I => 9,
 5087:                     J => 0,
 5088:                   );
 5089:     return %lettdig;
 5090: }
 5091: 
 5092: sub get_scantron_config {
 5093:     my ($which,$cdom) = @_;
 5094:     my @lines = &get_scantronformat_file($cdom);
 5095:     my %config;
 5096:     #FIXME probably should move to XML it has already gotten a bit much now
 5097:     foreach my $line (@lines) {
 5098:         my ($name,$descrip)=split(/:/,$line);
 5099:         if ($name ne $which ) { next; }
 5100:         chomp($line);
 5101:         my @config=split(/:/,$line);
 5102:         $config{'name'}=$config[0];
 5103:         $config{'description'}=$config[1];
 5104:         $config{'CODElocation'}=$config[2];
 5105:         $config{'CODEstart'}=$config[3];
 5106:         $config{'CODElength'}=$config[4];
 5107:         $config{'IDstart'}=$config[5];
 5108:         $config{'IDlength'}=$config[6];
 5109:         $config{'Qstart'}=$config[7];
 5110:         $config{'Qlength'}=$config[8];
 5111:         $config{'Qoff'}=$config[9];
 5112:         $config{'Qon'}=$config[10];
 5113:         $config{'PaperID'}=$config[11];
 5114:         $config{'PaperIDlength'}=$config[12];
 5115:         $config{'FirstName'}=$config[13];
 5116:         $config{'FirstNamelength'}=$config[14];
 5117:         $config{'LastName'}=$config[15];
 5118:         $config{'LastNamelength'}=$config[16];
 5119:         $config{'BubblesPerRow'}=$config[17];
 5120:         last;
 5121:     }
 5122:     return %config;
 5123: }
 5124: 
 5125: sub get_scantronformat_file {
 5126:     my ($cdom) = @_;
 5127:     if ($cdom eq '') {
 5128:         $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
 5129:     }
 5130:     my %domconfig = &get_dom('configuration',['scantron'],$cdom);
 5131:     my $gottab = 0;
 5132:     my @lines;
 5133:     if (ref($domconfig{'scantron'}) eq 'HASH') {
 5134:         if ($domconfig{'scantron'}{'scantronformat'} ne '') {
 5135:             my $formatfile = &getfile($perlvar{'lonDocRoot'}.$domconfig{'scantron'}{'scantronformat'});
 5136:             if ($formatfile ne '-1') {
 5137:                 @lines = split("\n",$formatfile,-1);
 5138:                 $gottab = 1;
 5139:             }
 5140:         }
 5141:     }
 5142:     if (!$gottab) {
 5143:         my $confname = $cdom.'-domainconfig';
 5144:         my $default = $perlvar{'lonDocRoot'}.'/res/'.$cdom.'/'.$confname.'/default.tab';
 5145:         my $formatfile = &getfile($default);
 5146:         if ($formatfile ne '-1') {
 5147:             @lines = split("\n",$formatfile,-1);
 5148:             $gottab = 1;
 5149:         }
 5150:     }
 5151:     if (!$gottab) {
 5152:         my @domains = &current_machine_domains();
 5153:         if (grep(/^\Q$cdom\E$/,@domains)) {
 5154:             if (open(my $fh,'<',$perlvar{'lonTabDir'}.'/scantronformat.tab')) {
 5155:                 @lines = <$fh>;
 5156:                 close($fh);
 5157:             }
 5158:         } else {
 5159:             if (open(my $fh,'<',$perlvar{'lonTabDir'}.'/default_scantronformat.tab')) {
 5160:                 @lines = <$fh>;
 5161:                 close($fh);
 5162:             }
 5163:         }
 5164:         chomp(@lines);
 5165:     }
 5166:     return @lines;
 5167: }
 5168: 
 5169: sub removeuploadedurl {
 5170:     my ($url)=@_;	
 5171:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);    
 5172:     return &removeuserfile($uname,$udom,$fname);
 5173: }
 5174: 
 5175: sub removeuserfile {
 5176:     my ($docuname,$docudom,$fname)=@_;
 5177:     my $home=&homeserver($docuname,$docudom);    
 5178:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
 5179:     if ($result eq 'ok') {	
 5180:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
 5181:             my $metafile = $fname.'.meta';
 5182:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
 5183: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
 5184:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];	   
 5185:             my $sqlresult = 
 5186:                 &update_portfolio_table($docuname,$docudom,$file,
 5187:                                         'portfolio_metadata',$group,
 5188:                                         'delete');
 5189:         }
 5190:     }
 5191:     return $result;
 5192: }
 5193: 
 5194: sub mkdiruserfile {
 5195:     my ($docuname,$docudom,$dir)=@_;
 5196:     my $home=&homeserver($docuname,$docudom);
 5197:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
 5198: }
 5199: 
 5200: sub renameuserfile {
 5201:     my ($docuname,$docudom,$old,$new)=@_;
 5202:     my $home=&homeserver($docuname,$docudom);
 5203:     my $result = &reply("renameuserfile:$docudom:$docuname:".
 5204:                         &escape("$old").':'.&escape("$new"),$home);
 5205:     if ($result eq 'ok') {
 5206:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
 5207:             my $oldmeta = $old.'.meta';
 5208:             my $newmeta = $new.'.meta';
 5209:             my $metaresult = 
 5210:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
 5211: 	    my $url = "/uploaded/$docudom/$docuname/$old";
 5212:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
 5213:             my $sqlresult = 
 5214:                 &update_portfolio_table($docuname,$docudom,$file,
 5215:                                         'portfolio_metadata',$group,
 5216:                                         'delete');
 5217:         }
 5218:     }
 5219:     return $result;
 5220: }
 5221: 
 5222: # ------------------------------------------------------------------------- Log
 5223: 
 5224: sub log {
 5225:     my ($dom,$nam,$hom,$what)=@_;
 5226:     return critical("log:$dom:$nam:$what",$hom);
 5227: }
 5228: 
 5229: # ------------------------------------------------------------------ Course Log
 5230: #
 5231: # This routine flushes several buffers of non-mission-critical nature
 5232: #
 5233: 
 5234: sub flushcourselogs {
 5235:     &logthis('Flushing log buffers');
 5236: #
 5237: # course logs
 5238: # This is a log of all transactions in a course, which can be used
 5239: # for data mining purposes
 5240: #
 5241: # It also collects the courseid database, which lists last transaction
 5242: # times and course titles for all courseids
 5243: #
 5244:     my %courseidbuffer=();
 5245:     foreach my $crsid (keys(%courselogs)) {
 5246:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
 5247: 		          &escape($courselogs{$crsid}),
 5248: 		          $coursehombuf{$crsid}) eq 'ok') {
 5249: 	    delete $courselogs{$crsid};
 5250:         } else {
 5251:             &logthis('Failed to flush log buffer for '.$crsid);
 5252:             if (length($courselogs{$crsid})>40000) {
 5253:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
 5254:                         " exceeded maximum size, deleting.</font>");
 5255:                delete $courselogs{$crsid};
 5256:             }
 5257:         }
 5258:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
 5259:             'description' => $coursedescrbuf{$crsid},
 5260:             'inst_code'    => $courseinstcodebuf{$crsid},
 5261:             'type'        => $coursetypebuf{$crsid},
 5262:             'owner'       => $courseownerbuf{$crsid},
 5263:         };
 5264:     }
 5265: #
 5266: # Write course id database (reverse lookup) to homeserver of courses 
 5267: # Is used in pickcourse
 5268: #
 5269:     foreach my $crs_home (keys(%courseidbuffer)) {
 5270:         my $response = &courseidput(&host_domain($crs_home),
 5271:                                     $courseidbuffer{$crs_home},
 5272:                                     $crs_home,'timeonly');
 5273:     }
 5274: #
 5275: # File accesses
 5276: # Writes to the dynamic metadata of resources to get hit counts, etc.
 5277: #
 5278:     foreach my $entry (keys(%accesshash)) {
 5279:         if ($entry =~ /___count$/) {
 5280:             my ($dom,$name);
 5281:             ($dom,$name,undef)=
 5282: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
 5283:             if (! defined($dom) || $dom eq '' || 
 5284:                 ! defined($name) || $name eq '') {
 5285:                 my $cid = $env{'request.course.id'};
 5286: #
 5287: # FIXME 11/29/2021
 5288: # Typo in rev. 1.458 (2003/12/09)??
 5289: # These should likely by $env{'course.'.$cid.'.domain'} and $env{'course.'.$cid.'.num'}
 5290: #
 5291: # While these remain as $env{'request.'.$cid.'.domain'} and $env{'request.'.$cid.'.num'}
 5292: # $dom and $name will always be null, so the &inc() call will default to storing this data
 5293: # in a nohist_accesscount.db file for the user rather than the course.
 5294: #
 5295: # That said there is a lot of noise in the data being stored.
 5296: # So counts for prtspool/  and adm/ etc. are recorded.
 5297: #
 5298: # A review of which items ending '___count' are written to %accesshash should likely be 
 5299: # made before deciding whether to set these to 'course.' instead of 'request.'
 5300: #
 5301: # Under the current scheme each user receives a nohist_accesscount.db file listing 
 5302: # accesses for things which are not published resources, regardless of course, and
 5303: # there is not a nohist_accesscount.db file in a course, which might log accesses from
 5304: # anyone in the course for things which are not published resources.
 5305: #
 5306: # For an author, nohist_accesscount.db ends up having records for other items
 5307: # mixed up with the legitimate access counts for the author's published resources.
 5308: #
 5309:                 $dom  = $env{'request.'.$cid.'.domain'};
 5310:                 $name = $env{'request.'.$cid.'.num'};
 5311:             }
 5312:             my $value = $accesshash{$entry};
 5313:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
 5314:             my %temphash=($url => $value);
 5315:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
 5316:             if ($result eq 'ok') {
 5317:                 delete $accesshash{$entry};
 5318:             }
 5319:         } else {
 5320:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
 5321:             if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
 5322:             my %temphash=($entry => $accesshash{$entry});
 5323:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
 5324:                 delete $accesshash{$entry};
 5325:             }
 5326:         }
 5327:     }
 5328: #
 5329: # Roles
 5330: # Reverse lookup of user roles for course faculty/staff and co-authorship
 5331: #
 5332:     foreach my $entry (keys(%userrolehash)) {
 5333:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
 5334: 	    split(/\:/,$entry);
 5335:         if (&put('nohist_userroles',
 5336:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
 5337:                 $rudom,$runame) eq 'ok') {
 5338: 	    delete $userrolehash{$entry};
 5339:         }
 5340:     }
 5341: #
 5342: # Reverse lookup of domain roles (dc, ad, li, sc, dh, da, au)
 5343: #
 5344:     my %domrolebuffer = ();
 5345:     foreach my $entry (keys(%domainrolehash)) {
 5346:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
 5347:         if ($domrolebuffer{$rudom}) {
 5348:             $domrolebuffer{$rudom}.='&'.&escape($entry).
 5349:                       '='.&escape($domainrolehash{$entry});
 5350:         } else {
 5351:             $domrolebuffer{$rudom}.=&escape($entry).
 5352:                       '='.&escape($domainrolehash{$entry});
 5353:         }
 5354:         delete $domainrolehash{$entry};
 5355:     }
 5356:     foreach my $dom (keys(%domrolebuffer)) {
 5357: 	my %servers;
 5358: 	if (defined(&domain($dom,'primary'))) {
 5359: 	    my $primary=&domain($dom,'primary');
 5360: 	    my $hostname=&hostname($primary);
 5361: 	    $servers{$primary} = $hostname;
 5362: 	} else { 
 5363: 	    %servers = &get_servers($dom,'library');
 5364: 	}
 5365: 	foreach my $tryserver (keys(%servers)) {
 5366: 	    if (&reply('domroleput:'.$dom.':'.
 5367: 		       $domrolebuffer{$dom},$tryserver) eq 'ok') {
 5368: 		last;
 5369: 	    } else {  
 5370: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
 5371: 	    }
 5372:         }
 5373:     }
 5374:     $dumpcount++;
 5375: }
 5376: 
 5377: sub courselog {
 5378:     my $what=shift;
 5379:     $what=time.':'.$what;
 5380:     unless ($env{'request.course.id'}) { return ''; }
 5381:     $coursedombuf{$env{'request.course.id'}}=
 5382:        $env{'course.'.$env{'request.course.id'}.'.domain'};
 5383:     $coursenumbuf{$env{'request.course.id'}}=
 5384:        $env{'course.'.$env{'request.course.id'}.'.num'};
 5385:     $coursehombuf{$env{'request.course.id'}}=
 5386:        $env{'course.'.$env{'request.course.id'}.'.home'};
 5387:     $coursedescrbuf{$env{'request.course.id'}}=
 5388:        $env{'course.'.$env{'request.course.id'}.'.description'};
 5389:     $courseinstcodebuf{$env{'request.course.id'}}=
 5390:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
 5391:     $courseownerbuf{$env{'request.course.id'}}=
 5392:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
 5393:     $coursetypebuf{$env{'request.course.id'}}=
 5394:        $env{'course.'.$env{'request.course.id'}.'.type'};
 5395:     if (defined $courselogs{$env{'request.course.id'}}) {
 5396: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
 5397:     } else {
 5398: 	$courselogs{$env{'request.course.id'}}.=$what;
 5399:     }
 5400:     if (length($courselogs{$env{'request.course.id'}})>4048) {
 5401: 	&flushcourselogs();
 5402:     }
 5403: }
 5404: 
 5405: sub courseacclog {
 5406:     my $fnsymb=shift;
 5407:     unless ($env{'request.course.id'}) { return ''; }
 5408:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
 5409:     if ($fnsymb=~/$LONCAPA::assess_re/) {
 5410:         $what.=':POST';
 5411:         # FIXME: Probably ought to escape things....
 5412: 	foreach my $key (keys(%env)) {
 5413:             if ($key=~/^form\.(.*)/) {
 5414:                 my $formitem = $1;
 5415:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
 5416:                     $what.=':'.$formitem.'='.$env{$key};
 5417:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
 5418:                     if ($formitem eq 'proctorpassword') {
 5419:                         $what.=':'.$formitem.'=' . '*' x length($env{$key});
 5420:                     } else {
 5421:                         $what.=':'.$formitem.'='.$env{$key};
 5422:                     }
 5423:                 }
 5424:             }
 5425:         }
 5426:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
 5427:         # FIXME: We should not be depending on a form parameter that someone
 5428:         # editing lonsearchcat.pm might change in the future.
 5429:         if ($env{'form.phase'} eq 'course_search') {
 5430:             $what.= ':POST';
 5431:             # FIXME: Probably ought to escape things....
 5432:             foreach my $element ('courseexp','crsfulltext','crsrelated',
 5433:                                  'crsdiscuss') {
 5434:                 $what.=':'.$element.'='.$env{'form.'.$element};
 5435:             }
 5436:         }
 5437:     }
 5438:     &courselog($what);
 5439: }
 5440: 
 5441: sub countacc {
 5442:     my $url=&declutter(shift);
 5443:     return if (! defined($url) || $url eq '');
 5444:     unless ($env{'request.course.id'}) { return ''; }
 5445: #
 5446: # Mark that this url was used in this course
 5447: #
 5448:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
 5449: #
 5450: # Increase the access count for this resource in this child process
 5451: #
 5452:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
 5453:     $accesshash{$key}++;
 5454: }
 5455: 
 5456: sub linklog {
 5457:     my ($from,$to)=@_;
 5458:     $from=&declutter($from);
 5459:     $to=&declutter($to);
 5460:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
 5461:     $accesshash{$to.'___'.$from.'___goto'}=1;
 5462: }
 5463: 
 5464: sub statslog {
 5465:     my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
 5466:     if ($users<2) { return; }
 5467:     my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
 5468:             'course'       => $env{'request.course.id'},
 5469:             'sections'     => '"all"',
 5470:             'num_students' => $users,
 5471:             'part'         => $part,
 5472:             'symb'         => $symb,
 5473:             'mean_tries'   => $av_attempts,
 5474:             'deg_of_diff'  => $degdiff});
 5475:     foreach my $key (keys(%dynstore)) {
 5476:         $accesshash{$key}=$dynstore{$key};
 5477:     }
 5478: }
 5479:   
 5480: sub userrolelog {
 5481:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
 5482:     if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
 5483:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 5484:        $userrolehash
 5485:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 5486:                     =$tend.':'.$tstart;
 5487:     }
 5488:     if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
 5489:        $userrolehash
 5490:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
 5491:                     =$tend.':'.$tstart;
 5492:     }
 5493:     if ($trole =~ /^(dc|ad|li|au|dg|sc|dh|da)/ ) {
 5494:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 5495:        $domainrolehash
 5496:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 5497:                     = $tend.':'.$tstart;
 5498:     }
 5499: }
 5500: 
 5501: sub courserolelog {
 5502:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,
 5503:         $context,$othdomby,$requester)=@_;
 5504:     if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
 5505:         my $cdom = $1;
 5506:         my $cnum = $2;
 5507:         my $sec = $3;
 5508:         my $namespace = 'rolelog';
 5509:         my %storehash = (
 5510:                            role    => $trole,
 5511:                            start   => $tstart,
 5512:                            end     => $tend,
 5513:                            selfenroll => $selfenroll,
 5514:                            context    => $context,
 5515:                         );
 5516:         if ($othdomby) {
 5517:             if ($othdomby eq 'othdombydc') {
 5518:                 $storehash{'approval'} = 'domain';
 5519:             } elsif ($othdomby eq 'othdombyuser') {
 5520:                 $storehash{'approval'} = 'user'; 
 5521:             }
 5522:             if ($requester ne '') {
 5523:                 $storehash{'requester'} = $requester;
 5524:             }
 5525:         }
 5526:         if ($trole eq 'gr') {
 5527:             $namespace = 'groupslog';
 5528:             $storehash{'group'} = $sec;
 5529:         } else {
 5530:             $storehash{'section'} = $sec;
 5531:             my ($curruserdomstr,$newuserdomstr);
 5532:             if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.userdomains'})) {
 5533:                 $curruserdomstr = $env{'course.'.$env{'request.course.id'}.'.internal.userdomains'};
 5534:             } else {
 5535:                 my %courseinfo = &coursedescription($cdom.'/'.$cnum);
 5536:                 $curruserdomstr = $courseinfo{'internal.userdomains'};
 5537:             }
 5538:             if ($curruserdomstr ne '') {
 5539:                 my @udoms = split(/,/,$curruserdomstr);
 5540:                 unless (grep(/^\Q$domain\E/,@udoms)) {
 5541:                     push(@udoms,$domain);
 5542:                     $newuserdomstr = join(',',sort(@udoms));
 5543:                 }
 5544:             } else {
 5545:                 $newuserdomstr = $domain;
 5546:             }
 5547:             if ($newuserdomstr ne '') {
 5548:                 my $putresult = &put('environment',{ 'internal.userdomains' => $newuserdomstr },
 5549:                                      $cdom,$cnum);
 5550:                 if ($putresult eq 'ok') {
 5551:                     unless (($selfenroll) || ($context eq 'selfenroll')) { 
 5552:                         if (($context eq 'createcourse') || ($context eq 'requestcourses') ||
 5553:                             ($context eq 'automated') || ($context eq 'domain')) {
 5554:                             $env{'course.'.$cdom.'_'.$cnum.'.internal.userdomains'} = $newuserdomstr;
 5555:                         } elsif ($env{'request.course.id'} eq $cdom.'_'.$cnum) {
 5556:                             &appenv({'course.'.$cdom.'_'.$cnum.'.internal.userdomains' => $newuserdomstr});
 5557:                         }
 5558:                     }
 5559:                 }
 5560:             }
 5561:         }
 5562:         &write_log('course',$namespace,\%storehash,$delflag,$username,
 5563:                    $domain,$cnum,$cdom);
 5564:         if (($trole ne 'st') || ($sec ne '')) {
 5565:             &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
 5566:         }
 5567:     }
 5568:     return;
 5569: }
 5570: 
 5571: sub domainrolelog {
 5572:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,
 5573:         $context,$othdomby,$requester)=@_;
 5574:     if ($area =~ m{^/($match_domain)/$}) {
 5575:         my $cdom = $1;
 5576:         my $domconfiguser = &get_domainconfiguser($cdom);
 5577:         my $namespace = 'rolelog';
 5578:         my %storehash = (
 5579:                            role    => $trole,
 5580:                            start   => $tstart,
 5581:                            end     => $tend,
 5582:                            context => $context,
 5583:                         );
 5584:         if ($othdomby) {
 5585:             if ($othdomby eq 'othdombydc') {
 5586:                 $storehash{'approval'} = 'domain';
 5587:             } elsif ($othdomby eq 'othdombyuser') {
 5588:                 $storehash{'approval'} = 'user';
 5589:             }
 5590:             if ($requester ne '') {
 5591:                 $storehash{'requester'} = $requester;
 5592:             }
 5593:         }
 5594:         &write_log('domain',$namespace,\%storehash,$delflag,$username,
 5595:                    $domain,$domconfiguser,$cdom);
 5596:     }
 5597:     return;
 5598: 
 5599: }
 5600: 
 5601: sub coauthorrolelog {
 5602:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,
 5603:         $context,$othdomby,$requester)=@_;
 5604:     if ($area =~ m{^/($match_domain)/($match_username)$}) {
 5605:         my $audom = $1;
 5606:         my $auname = $2;
 5607:         my $namespace = 'rolelog';
 5608:         my %storehash = (
 5609:                            role    => $trole,
 5610:                            start   => $tstart,
 5611:                            end     => $tend,
 5612:                            context => $context,
 5613:                         );
 5614:         if ($othdomby) {
 5615:             if ($othdomby eq 'othdombydc') {
 5616:                 $storehash{'approval'} = 'domain';
 5617:             } elsif ($othdomby eq 'othdombyuser') {
 5618:                 $storehash{'approval'} = 'user';
 5619:             }
 5620:             if ($requester ne '') {
 5621:                 $storehash{'requester'} = $requester;
 5622:             }
 5623:         }
 5624:         &write_log('author',$namespace,\%storehash,$delflag,$username,
 5625:                    $domain,$auname,$audom);
 5626:     }
 5627:     return;
 5628: }
 5629: 
 5630: sub authorarchivelog {
 5631:     my ($hashref,$size,$filesdest,$action) = @_;
 5632:     my $lonprtdir = $Apache::lonnet::perlvar{'lonPrtDir'};
 5633:     my $londocroot = $Apache::lonnet::perlvar{'lonDocRoot'};
 5634:     $filesdest =~ s{^\Q$lonprtdir/\E}{};
 5635:     if ($filesdest =~ m{^($match_username)_($match_domain)_archive_(\d+_\d+_\d+(|[.\w]+))$}) {
 5636:         my ($auname,$audom,$id) = ($1,$2,$3);
 5637:         if (ref($hashref) eq 'HASH') {
 5638:             my $namespace = 'archivelog';
 5639:             my $dir;
 5640:             if ($hashref->{dir} =~ m{^\Q$londocroot/priv/$audom/$auname\E(.*)$}) {
 5641:                 $dir = $1;
 5642:             }
 5643:             my $delflag = 0;
 5644:             my %storehash = (
 5645:                               id      => $id,
 5646:                               dir     => $dir,
 5647:                               files   => $hashref->{numfiles},
 5648:                               subdirs => $hashref->{numdirs},
 5649:                               bytes   => $hashref->{bytes},
 5650:                               size    => $size,
 5651:                               action  => $action,
 5652:                             );
 5653:             if ($action eq 'delete') {
 5654:                 $delflag = 1;
 5655:             }
 5656:             &write_log('author',$namespace,\%storehash,$delflag,$auname,
 5657:                        $audom,$auname,$audom);
 5658:         }
 5659:     }
 5660:     return;
 5661: }
 5662: 
 5663: sub get_course_adv_roles {
 5664:     my ($cid,$codes) = @_;
 5665:     $cid=$env{'request.course.id'} unless (defined($cid));
 5666:     my %coursehash=&coursedescription($cid);
 5667:     my $crstype = &Apache::loncommon::course_type($cid);
 5668:     my %nothide=();
 5669:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 5670:         if ($user !~ /:/) {
 5671: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
 5672:         } else {
 5673:             $nothide{$user}=1;
 5674:         }
 5675:     }
 5676:     my @possdoms = ($coursehash{'domain'});
 5677:     if ($coursehash{'checkforpriv'}) {
 5678:         push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
 5679:     }
 5680:     my %returnhash=();
 5681:     my %dumphash=
 5682:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
 5683:     my $now=time;
 5684:     my %privileged;
 5685:     foreach my $entry (keys(%dumphash)) {
 5686: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
 5687:         if (($tstart) && ($tstart<0)) { next; }
 5688:         if (($tend) && ($tend<$now)) { next; }
 5689:         if (($tstart) && ($now<$tstart)) { next; }
 5690:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
 5691: 	if ($username eq '' || $domain eq '') { next; }
 5692:         if ((&privileged($username,$domain,\@possdoms)) &&
 5693:             (!$nothide{$username.':'.$domain})) { next; }
 5694: 	if ($role eq 'cr') { next; }
 5695:         if ($codes) {
 5696:             if ($section) { $role .= ':'.$section; }
 5697:             if ($returnhash{$role}) {
 5698:                 $returnhash{$role}.=','.$username.':'.$domain;
 5699:             } else {
 5700:                 $returnhash{$role}=$username.':'.$domain;
 5701:             }
 5702:         } else {
 5703:             my $key=&plaintext($role,$crstype);
 5704:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
 5705:             if ($returnhash{$key}) {
 5706: 	        $returnhash{$key}.=','.$username.':'.$domain;
 5707:             } else {
 5708:                 $returnhash{$key}=$username.':'.$domain;
 5709:             }
 5710:         }
 5711:     }
 5712:     return %returnhash;
 5713: }
 5714: 
 5715: sub get_my_roles {
 5716:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
 5717:     unless (defined($uname)) { $uname=$env{'user.name'}; }
 5718:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
 5719:     my (%dumphash,%nothide);
 5720:     if ($context eq 'userroles') {
 5721:         %dumphash = &dump('roles',$udom,$uname);
 5722:     } else {
 5723:         %dumphash = &dump('nohist_userroles',$udom,$uname);
 5724:         if ($hidepriv) {
 5725:             my %coursehash=&coursedescription($udom.'_'.$uname);
 5726:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 5727:                 if ($user !~ /:/) {
 5728:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
 5729:                 } else {
 5730:                     $nothide{$user} = 1;
 5731:                 }
 5732:             }
 5733:         }
 5734:     }
 5735:     my %returnhash=();
 5736:     my $now=time;
 5737:     my %privileged;
 5738:     foreach my $entry (keys(%dumphash)) {
 5739:         my ($role,$tend,$tstart);
 5740:         if ($context eq 'userroles') {
 5741:             next if ($entry =~ /^rolesdef/);
 5742: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
 5743:         } else {
 5744:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
 5745:         }
 5746:         if (($tstart) && ($tstart<0)) { next; }
 5747:         my $status = 'active';
 5748:         if (($tend) && ($tend<=$now)) {
 5749:             $status = 'previous';
 5750:         } 
 5751:         if (($tstart) && ($now<$tstart)) {
 5752:             $status = 'future';
 5753:         }
 5754:         if (ref($types) eq 'ARRAY') {
 5755:             if (!grep(/^\Q$status\E$/,@{$types})) {
 5756:                 next;
 5757:             } 
 5758:         } else {
 5759:             if ($status ne 'active') {
 5760:                 next;
 5761:             }
 5762:         }
 5763:         my ($rolecode,$username,$domain,$section,$area);
 5764:         if ($context eq 'userroles') {
 5765:             ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
 5766:             (undef,$domain,$username,$section) = split(/\//,$area);
 5767:         } else {
 5768:             ($role,$username,$domain,$section) = split(/\:/,$entry);
 5769:         }
 5770:         if (ref($roledoms) eq 'ARRAY') {
 5771:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
 5772:                 next;
 5773:             }
 5774:         }
 5775:         if (ref($roles) eq 'ARRAY') {
 5776:             if (!grep(/^\Q$role\E$/,@{$roles})) {
 5777:                 if ($role =~ /^cr\//) {
 5778:                     if (!grep(/^cr$/,@{$roles})) {
 5779:                         next;
 5780:                     }
 5781:                 } elsif ($role =~ /^gr\//) {
 5782:                     if (!grep(/^gr$/,@{$roles})) {
 5783:                         next;
 5784:                     }
 5785:                 } else {
 5786:                     next;
 5787:                 }
 5788:             }
 5789:         }
 5790:         if ($hidepriv) {
 5791:             my @privroles = ('dc','su');
 5792:             if ($context eq 'userroles') {
 5793:                 next if (grep(/^\Q$role\E$/,@privroles));
 5794:             } else {
 5795:                 my $possdoms = [$domain];
 5796:                 if (ref($roledoms) eq 'ARRAY') {
 5797:                    push(@{$possdoms},@{$roledoms}); 
 5798:                 }
 5799:                 if (&privileged($username,$domain,$possdoms,\@privroles)) {
 5800:                     if (!$nothide{$username.':'.$domain}) {
 5801:                         next;
 5802:                     }
 5803:                 }
 5804:             }
 5805:         }
 5806:         if ($withsec) {
 5807:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
 5808:                 $tstart.':'.$tend;
 5809:         } else {
 5810:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
 5811:         }
 5812:     }
 5813:     return %returnhash;
 5814: }
 5815: 
 5816: sub get_all_adhocroles {
 5817:     my ($dom) = @_;
 5818:     my @roles_by_num = ();
 5819:     my %domdefaults = &get_domain_defaults($dom);
 5820:     my (%description,%access_in_dom,%access_info);
 5821:     if (ref($domdefaults{'adhocroles'}) eq 'HASH') {
 5822:         my $count = 0;
 5823:         my %domcurrent = %{$domdefaults{'adhocroles'}};
 5824:         my %ordered;
 5825:         foreach my $role (sort(keys(%domcurrent))) {
 5826:             my ($order,$desc,$access_in_dom);
 5827:             if (ref($domcurrent{$role}) eq 'HASH') {
 5828:                 $order = $domcurrent{$role}{'order'};
 5829:                 $desc = $domcurrent{$role}{'desc'};
 5830:                 $access_in_dom{$role} = $domcurrent{$role}{'access'};
 5831:                 $access_info{$role} = $domcurrent{$role}{$access_in_dom{$role}};
 5832:             }
 5833:             if ($order eq '') {
 5834:                 $order = $count;
 5835:             }
 5836:             $ordered{$order} = $role;
 5837:             if ($desc ne '') {
 5838:                 $description{$role} = $desc;
 5839:             } else {
 5840:                 $description{$role}= $role;
 5841:             }
 5842:             $count++;
 5843:         }
 5844:         foreach my $item (sort {$a <=> $b } (keys(%ordered))) {
 5845:             push(@roles_by_num,$ordered{$item});
 5846:         }
 5847:     }
 5848:     return (\@roles_by_num,\%description,\%access_in_dom,\%access_info);
 5849: }
 5850: 
 5851: sub get_my_adhocroles {
 5852:     my ($cid,$checkreg) = @_;
 5853:     my ($cdom,$cnum,%info,@possroles,$description,$roles_by_num);
 5854:     if ($env{'request.course.id'} eq $cid) {
 5855:         $cdom = $env{'course.'.$cid.'.domain'};
 5856:         $cnum = $env{'course.'.$cid.'.num'};
 5857:         $info{'internal.coursecode'} = $env{'course.'.$cid.'.internal.coursecode'};
 5858:     } elsif ($cid =~ /^($match_domain)_($match_courseid)$/) {
 5859:         $cdom = $1;
 5860:         $cnum = $2;
 5861:         %info = &get('environment',['internal.coursecode'],
 5862:                      $cdom,$cnum);
 5863:     }
 5864:     if (($info{'internal.coursecode'} ne '') && ($checkreg)) {
 5865:         my $user = $env{'user.name'}.':'.$env{'user.domain'};
 5866:         my %rosterhash = &get('classlist',[$user],$cdom,$cnum);
 5867:         if ($rosterhash{$user} ne '') {
 5868:             my $type = (split(/:/,$rosterhash{$user}))[5];
 5869:             return ([],{}) if ($type eq 'auto');
 5870:         }
 5871:     }
 5872:     if (($cdom ne '') && ($cnum ne ''))  {
 5873:         if (($env{"user.role.dh./$cdom/"}) || ($env{"user.role.da./$cdom/"})) {
 5874:             my $then=$env{'user.login.time'};
 5875:             my $update=$env{'user.update.time'};
 5876:             if (!$update) {
 5877:                 $update = $then;
 5878:             }
 5879:             my @liveroles;
 5880:             foreach my $role ('dh','da') {
 5881:                 if ($env{"user.role.$role./$cdom/"}) {
 5882:                     my ($tstart,$tend)=split(/\./,$env{"user.role.$role./$cdom/"});
 5883:                     my $limit = $update;
 5884:                     if ($env{'request.role'} eq "$role./$cdom/") {
 5885:                         $limit = $then;
 5886:                     }
 5887:                     my $activerole = 1;
 5888:                     if ($tstart && $tstart>$limit) { $activerole = 0; }
 5889:                     if ($tend   && $tend  <$limit) { $activerole = 0; }
 5890:                     if ($activerole) {
 5891:                         push(@liveroles,$role);
 5892:                     }
 5893:                 }
 5894:             }
 5895:             if (@liveroles) {
 5896:                 if (&homeserver($cnum,$cdom) ne 'no_host') {
 5897:                     my ($accessref,$accessinfo,%access_in_dom);
 5898:                     ($roles_by_num,$description,$accessref,$accessinfo) = &get_all_adhocroles($cdom);
 5899:                     if (ref($roles_by_num) eq 'ARRAY') {
 5900:                         if (@{$roles_by_num}) {
 5901:                             my %settings;
 5902:                             if ($env{'request.course.id'} eq $cid) {
 5903:                                 foreach my $envkey (keys(%env)) {
 5904:                                     if ($envkey =~ /^\Qcourse.$cid.\E(internal\.adhoc.+)$/) {
 5905:                                         $settings{$1} = $env{$envkey};
 5906:                                     }
 5907:                                 }
 5908:                             } else {
 5909:                                 %settings = &dump('environment',$cdom,$cnum,'internal\.adhoc');
 5910:                             }
 5911:                             my %setincrs;
 5912:                             if ($settings{'internal.adhocaccess'}) {
 5913:                                 map { $setincrs{$_} = 1; } split(/,/,$settings{'internal.adhocaccess'});
 5914:                             }
 5915:                             my @statuses;
 5916:                             if ($env{'environment.inststatus'}) {
 5917:                                 @statuses = split(/,/,$env{'environment.inststatus'});
 5918:                             }
 5919:                             my $user = $env{'user.name'}.':'.$env{'user.domain'};
 5920:                             if (ref($accessref) eq 'HASH') {
 5921:                                 %access_in_dom = %{$accessref};
 5922:                             }
 5923:                             foreach my $role (@{$roles_by_num}) {
 5924:                                 my ($curraccess,@okstatus,@personnel);
 5925:                                 if ($setincrs{$role}) {
 5926:                                     ($curraccess,my $rest) = split(/=/,$settings{'internal.adhoc.'.$role});
 5927:                                     if ($curraccess eq 'status') {
 5928:                                         @okstatus = split(/\&/,$rest);
 5929:                                     } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
 5930:                                         @personnel = split(/\&/,$rest);
 5931:                                     }
 5932:                                 } else {
 5933:                                     $curraccess = $access_in_dom{$role};
 5934:                                     if (ref($accessinfo) eq 'HASH') {
 5935:                                         if ($curraccess eq 'status') {
 5936:                                             if (ref($accessinfo->{$role}) eq 'ARRAY') {
 5937:                                                 @okstatus = @{$accessinfo->{$role}};
 5938:                                             }
 5939:                                         } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
 5940:                                             if (ref($accessinfo->{$role}) eq 'ARRAY') {
 5941:                                                 @personnel = @{$accessinfo->{$role}};
 5942:                                             }
 5943:                                         }
 5944:                                     }
 5945:                                 }
 5946:                                 if ($curraccess eq 'none') {
 5947:                                     next;
 5948:                                 } elsif ($curraccess eq 'all') {
 5949:                                     push(@possroles,$role);
 5950:                                 } elsif ($curraccess eq 'dh') {
 5951:                                     if (grep(/^dh$/,@liveroles)) {
 5952:                                         push(@possroles,$role);
 5953:                                     } else {
 5954:                                         next;
 5955:                                     }
 5956:                                 } elsif ($curraccess eq 'da') {
 5957:                                     if (grep(/^da$/,@liveroles)) {
 5958:                                         push(@possroles,$role);
 5959:                                     } else {
 5960:                                         next;
 5961:                                     }
 5962:                                 } elsif ($curraccess eq 'status') {
 5963:                                     if (@okstatus) {
 5964:                                         if (!@statuses) {
 5965:                                             if (grep(/^default$/,@okstatus)) {
 5966:                                                 push(@possroles,$role);
 5967:                                             }
 5968:                                         } else {
 5969:                                             foreach my $status (@okstatus) {
 5970:                                                 if (grep(/^\Q$status\E$/,@statuses)) {
 5971:                                                     push(@possroles,$role);
 5972:                                                     last;
 5973:                                                 }
 5974:                                             }
 5975:                                         }
 5976:                                     }
 5977:                                 } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
 5978:                                     if (grep(/^\Q$user\E$/,@personnel)) {
 5979:                                         if ($curraccess eq 'exc') {
 5980:                                             push(@possroles,$role);
 5981:                                         }
 5982:                                     } elsif ($curraccess eq 'inc') {
 5983:                                         push(@possroles,$role);
 5984:                                     }
 5985:                                 }
 5986:                             }
 5987:                         }
 5988:                     }
 5989:                 }
 5990:             }
 5991:         }
 5992:     }
 5993:     unless (ref($description) eq 'HASH') {
 5994:         if (ref($roles_by_num) eq 'ARRAY') {
 5995:             my %desc;
 5996:             map { $desc{$_} = $_; } (@{$roles_by_num});
 5997:             $description = \%desc;
 5998:         } else {
 5999:             $description = {};
 6000:         }
 6001:     }
 6002:     return (\@possroles,$description);
 6003: }
 6004: 
 6005: # ----------------------------------------------------- Frontpage Announcements
 6006: #
 6007: #
 6008: 
 6009: sub postannounce {
 6010:     my ($server,$text)=@_;
 6011:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
 6012:     unless ($text=~/\w/) { $text=''; }
 6013:     return &reply('setannounce:'.&escape($text),$server);
 6014: }
 6015: 
 6016: sub getannounce {
 6017: 
 6018:     if (open(my $fh,"<",$perlvar{'lonDocRoot'}.'/announcement.txt')) {
 6019: 	my $announcement='';
 6020: 	while (my $line = <$fh>) { $announcement .= $line; }
 6021: 	close($fh);
 6022: 	if ($announcement=~/\w/) { 
 6023: 	    return 
 6024:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
 6025:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
 6026: 	} else {
 6027: 	    return '';
 6028: 	}
 6029:     } else {
 6030: 	return '';
 6031:     }
 6032: }
 6033: 
 6034: # ---------------------------------------------------------- Course ID routines
 6035: # Deal with domain's nohist_courseid.db files
 6036: #
 6037: 
 6038: sub courseidput {
 6039:     my ($domain,$storehash,$coursehome,$caller) = @_;
 6040:     return unless (ref($storehash) eq 'HASH');
 6041:     my $outcome;
 6042:     if ($caller eq 'timeonly') {
 6043:         my $cids = '';
 6044:         foreach my $item (keys(%$storehash)) {
 6045:             $cids.=&escape($item).'&';
 6046:         }
 6047:         $cids=~s/\&$//;
 6048:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
 6049:                           $coursehome);       
 6050:     } else {
 6051:         my $items = '';
 6052:         foreach my $item (keys(%$storehash)) {
 6053:             $items.= &escape($item).'='.
 6054:                      &freeze_escape($$storehash{$item}).'&';
 6055:         }
 6056:         $items=~s/\&$//;
 6057:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
 6058:                           $coursehome);
 6059:     }
 6060:     if ($outcome eq 'unknown_cmd') {
 6061:         my $what;
 6062:         foreach my $cid (keys(%$storehash)) {
 6063:             $what .= &escape($cid).'=';
 6064:             foreach my $item ('description','inst_code','owner','type') {
 6065:                 $what .= &escape($storehash->{$cid}{$item}).':';
 6066:             }
 6067:             $what =~ s/\:$/&/;
 6068:         }
 6069:         $what =~ s/\&$//;  
 6070:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
 6071:     } else {
 6072:         return $outcome;
 6073:     }
 6074: }
 6075: 
 6076: sub courseiddump {
 6077:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
 6078:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
 6079:         $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
 6080:         $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner,
 6081:         $hasuniquecode,$reqcrsdom,$reqinstcode)=@_;
 6082:     my $as_hash = 1;
 6083:     my %returnhash;
 6084:     if (!$domfilter) { $domfilter=''; }
 6085:     my %libserv = &all_library();
 6086:     foreach my $tryserver (keys(%libserv)) {
 6087:         if ( (  $hostidflag == 1 
 6088: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
 6089: 	     || (!defined($hostidflag)) ) {
 6090: 
 6091: 	    if (($domfilter eq '') ||
 6092: 		(&host_domain($tryserver) eq $domfilter)) {
 6093:                 my $rep;
 6094:                 if (grep { $_ eq $tryserver } current_machine_ids()) {
 6095:                     $rep = LONCAPA::Lond::dump_course_id_handler(
 6096:                         join(":", (&host_domain($tryserver), $sincefilter, 
 6097:                                 &escape($descfilter), &escape($instcodefilter), 
 6098:                                 &escape($ownerfilter), &escape($coursefilter),
 6099:                                 &escape($typefilter), &escape($regexp_ok), 
 6100:                                 $as_hash, &escape($selfenrollonly), 
 6101:                                 &escape($catfilter), $showhidden, $caller, 
 6102:                                 &escape($cloner), &escape($cc_clone), $cloneonly, 
 6103:                                 &escape($createdbefore), &escape($createdafter), 
 6104:                                 &escape($creationcontext),$domcloner,$hasuniquecode,
 6105:                                 $reqcrsdom,&escape($reqinstcode))));
 6106:                 } else {
 6107:                     $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
 6108:                              $sincefilter.':'.&escape($descfilter).':'.
 6109:                              &escape($instcodefilter).':'.&escape($ownerfilter).
 6110:                              ':'.&escape($coursefilter).':'.&escape($typefilter).
 6111:                              ':'.&escape($regexp_ok).':'.$as_hash.':'.
 6112:                              &escape($selfenrollonly).':'.&escape($catfilter).':'.
 6113:                              $showhidden.':'.$caller.':'.&escape($cloner).':'.
 6114:                              &escape($cc_clone).':'.$cloneonly.':'.
 6115:                              &escape($createdbefore).':'.&escape($createdafter).':'.
 6116:                              &escape($creationcontext).':'.$domcloner.':'.$hasuniquecode.
 6117:                              ':'.$reqcrsdom.':'.&escape($reqinstcode),$tryserver);
 6118:                 }
 6119:                      
 6120:                 my @pairs=split(/\&/,$rep);
 6121:                 foreach my $item (@pairs) {
 6122:                     my ($key,$value)=split(/\=/,$item,2);
 6123:                     $key = &unescape($key);
 6124:                     next if ($key =~ /^error: 2 /);
 6125:                     my $result = &thaw_unescape($value);
 6126:                     if (ref($result) eq 'HASH') {
 6127:                         $returnhash{$key}=$result;
 6128:                     } else {
 6129:                         my @responses = split(/:/,$value);
 6130:                         my @items = ('description','inst_code','owner','type');
 6131:                         for (my $i=0; $i<@responses; $i++) {
 6132:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
 6133:                         }
 6134:                     }
 6135:                 }
 6136:             }
 6137:         }
 6138:     }
 6139:     return %returnhash;
 6140: }
 6141: 
 6142: sub courselastaccess {
 6143:     my ($cdom,$cnum,$hostidref) = @_;
 6144:     my %returnhash;
 6145:     if ($cdom && $cnum) {
 6146:         my $chome = &homeserver($cnum,$cdom);
 6147:         if ($chome ne 'no_host') {
 6148:             my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
 6149:             &extract_lastaccess(\%returnhash,$rep);
 6150:         }
 6151:     } else {
 6152:         if (!$cdom) { $cdom=''; }
 6153:         my %libserv = &all_library();
 6154:         foreach my $tryserver (keys(%libserv)) {
 6155:             if (ref($hostidref) eq 'ARRAY') {
 6156:                 next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
 6157:             } 
 6158:             if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
 6159:                 my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
 6160:                 &extract_lastaccess(\%returnhash,$rep);
 6161:             }
 6162:         }
 6163:     }
 6164:     return %returnhash;
 6165: }
 6166: 
 6167: sub extract_lastaccess {
 6168:     my ($returnhash,$rep) = @_;
 6169:     if (ref($returnhash) eq 'HASH') {
 6170:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' || 
 6171:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
 6172:                  $rep eq '') {
 6173:             my @pairs=split(/\&/,$rep);
 6174:             foreach my $item (@pairs) {
 6175:                 my ($key,$value)=split(/\=/,$item,2);
 6176:                 $key = &unescape($key);
 6177:                 next if ($key =~ /^error: 2 /);
 6178:                 $returnhash->{$key} = &thaw_unescape($value);
 6179:             }
 6180:         }
 6181:     }
 6182:     return;
 6183: }
 6184: 
 6185: # ---------------------------------------------------------- DC e-mail
 6186: 
 6187: sub dcmailput {
 6188:     my ($domain,$msgid,$message,$server)=@_;
 6189:     my $status = &critical(
 6190:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
 6191:        &escape($message),$server);
 6192:     return $status;
 6193: }
 6194: 
 6195: sub dcmaildump {
 6196:     my ($dom,$startdate,$enddate,$senders) = @_;
 6197:     my %returnhash=();
 6198: 
 6199:     if (defined(&domain($dom,'primary'))) {
 6200:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
 6201:                                                          &escape($enddate).':';
 6202: 	my @esc_senders=map { &escape($_)} @$senders;
 6203: 	$cmd.=&escape(join('&',@esc_senders));
 6204: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
 6205:             my ($key,$value) = split(/\=/,$line,2);
 6206:             if (($key) && ($value)) {
 6207:                 $returnhash{&unescape($key)} = &unescape($value);
 6208:             }
 6209:         }
 6210:     }
 6211:     return %returnhash;
 6212: }
 6213: # ---------------------------------------------------------- Domain roles
 6214: 
 6215: sub get_domain_roles {
 6216:     my ($dom,$roles,$startdate,$enddate)=@_;
 6217:     if ((!defined($startdate)) || ($startdate eq '')) {
 6218:         $startdate = '.';
 6219:     }
 6220:     if ((!defined($enddate)) || ($enddate eq '')) {
 6221:         $enddate = '.';
 6222:     }
 6223:     my $rolelist;
 6224:     if (ref($roles) eq 'ARRAY') {
 6225:         $rolelist = join('&',@{$roles});
 6226:     }
 6227:     my %personnel = ();
 6228: 
 6229:     my %servers = &get_servers($dom,'library');
 6230:     foreach my $tryserver (keys(%servers)) {
 6231: 	%{$personnel{$tryserver}}=();
 6232: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
 6233: 					    &escape($startdate).':'.
 6234: 					    &escape($enddate).':'.
 6235: 					    &escape($rolelist), $tryserver))) {
 6236: 	    my ($key,$value) = split(/\=/,$line,2);
 6237: 	    if (($key) && ($value)) {
 6238: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
 6239: 	    }
 6240: 	}
 6241:     }
 6242:     return %personnel;
 6243: }
 6244: 
 6245: sub get_active_domroles {
 6246:     my ($dom,$roles) = @_;
 6247:     return () unless (ref($roles) eq 'ARRAY');
 6248:     my $now = time;
 6249:     my %dompersonnel = &get_domain_roles($dom,$roles,$now,$now);
 6250:     my %domroles;
 6251:     foreach my $server (keys(%dompersonnel)) {
 6252:         foreach my $user (sort(keys(%{$dompersonnel{$server}}))) {
 6253:             my ($trole,$uname,$udom,$runame,$rudom,$rsec) = split(/:/,$user);
 6254:             $domroles{$uname.':'.$udom} = $dompersonnel{$server}{$user};
 6255:         }
 6256:     }
 6257:     return %domroles;
 6258: }
 6259: 
 6260: # ----------------------------------------------------------- Interval timing 
 6261: 
 6262: {
 6263: # Caches needed for speedup of navmaps
 6264: # We don't want to cache this for very long at all (5 seconds at most)
 6265: # 
 6266: # The user for whom we cache
 6267: my $cachedkey='';
 6268: # The cached times for this user
 6269: my %cachedtimes=();
 6270: # When this was last done
 6271: my $cachedtime='';
 6272: 
 6273: sub load_all_first_access {
 6274:     my ($uname,$udom,$ignorecache)=@_;
 6275:     if (($cachedkey eq $uname.':'.$udom) &&
 6276:         (abs($cachedtime-time)<5) && (!$env{'form.markaccess'}) &&
 6277:         (!$ignorecache)) {
 6278:         return;
 6279:     }
 6280:     $cachedtime=time;
 6281:     $cachedkey=$uname.':'.$udom;
 6282:     %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
 6283: }
 6284: 
 6285: sub get_first_access {
 6286:     my ($type,$argsymb,$argmap,$ignorecache)=@_;
 6287:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 6288:     if ($argsymb) { $symb=$argsymb; }
 6289:     my ($map,$id,$res)=&decode_symb($symb);
 6290:     if ($argmap) { $map = $argmap; }
 6291:     if ($type eq 'course') {
 6292: 	$res='course';
 6293:     } elsif ($type eq 'map') {
 6294: 	$res=&symbread($map);
 6295:     } else {
 6296: 	$res=$symb;
 6297:     }
 6298:     &load_all_first_access($uname,$udom,$ignorecache);
 6299:     return $cachedtimes{"$courseid\0$res"};
 6300: }
 6301: 
 6302: sub set_first_access {
 6303:     my ($type,$interval)=@_;
 6304:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 6305:     my ($map,$id,$res)=&decode_symb($symb);
 6306:     if ($type eq 'course') {
 6307: 	$res='course';
 6308:     } elsif ($type eq 'map') {
 6309: 	$res=&symbread($map);
 6310:     } else {
 6311: 	$res=$symb;
 6312:     }
 6313:     $cachedkey='';
 6314:     my $firstaccess=&get_first_access($type,$symb,$map);
 6315:     if ($firstaccess) {
 6316:         &logthis("First access time already set ($firstaccess) when attempting ".
 6317:                  "to set new value (type: $type, extent: $res) for $uname:$udom ".
 6318:                  "in $courseid");
 6319:         return 'already_set';
 6320:     } else {
 6321:         my $start = time;
 6322: 	my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
 6323:                           $udom,$uname);
 6324:         if ($putres eq 'ok') {
 6325:             &put('timerinterval',{"$courseid\0$res"=>$interval},
 6326:                  $udom,$uname); 
 6327:             &appenv(
 6328:                      {
 6329:                         'course.'.$courseid.'.firstaccess.'.$res   => $start,
 6330:                         'course.'.$courseid.'.timerinterval.'.$res => $interval,
 6331:                      }
 6332:                   );
 6333:             if (($cachedtime) && (abs($start-$cachedtime) < 5)) {
 6334:                 $cachedtimes{"$courseid\0$res"} = $start;
 6335:             }
 6336:         } elsif ($putres ne 'refused') {
 6337:             &logthis("Result: $putres when attempting to set first access time ".
 6338:                      "(type: $type, extent: $res) for $uname:$udom in $courseid");
 6339:         }
 6340:         return $putres;
 6341:     }
 6342:     return 'already_set';
 6343: }
 6344: }
 6345: 
 6346: # --------------------------------------------- Set Expire Date for Spreadsheet
 6347: 
 6348: sub expirespread {
 6349:     my ($uname,$udom,$stype,$usymb)=@_;
 6350:     my $cid=$env{'request.course.id'}; 
 6351:     if ($cid) {
 6352:        my $now=time;
 6353:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
 6354:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
 6355:                             $env{'course.'.$cid.'.num'}.
 6356: 	        	    ':nohist_expirationdates:'.
 6357:                             &escape($key).'='.$now,
 6358:                             $env{'course.'.$cid.'.home'})
 6359:     }
 6360:     return 'ok';
 6361: }
 6362: 
 6363: # ----------------------------------------------------- Devalidate Spreadsheets
 6364: 
 6365: sub devalidate {
 6366:     my ($symb,$uname,$udom)=@_;
 6367:     my $cid=$env{'request.course.id'}; 
 6368:     if ($cid) {
 6369:         # delete the stored spreadsheets for
 6370:         # - the student level sheet of this user in course's homespace
 6371:         # - the assessment level sheet for this resource 
 6372:         #   for this user in user's homespace
 6373: 	# - current conditional state info
 6374: 	my $key=$uname.':'.$udom.':';
 6375:         my $status=
 6376: 	    &del('nohist_calculatedsheets',
 6377: 		 [$key.'studentcalc:'],
 6378: 		 $env{'course.'.$cid.'.domain'},
 6379: 		 $env{'course.'.$cid.'.num'})
 6380: 		.' '.
 6381: 	    &del('nohist_calculatedsheets_'.$cid,
 6382: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
 6383:         unless ($status eq 'ok ok') {
 6384:            &logthis('Could not devalidate spreadsheet '.
 6385:                     $uname.' at '.$udom.' for '.
 6386: 		    $symb.': '.$status);
 6387:         }
 6388: 	&delenv('user.state.'.$cid);
 6389:     }
 6390: }
 6391: 
 6392: sub get_scalar {
 6393:     my ($string,$end) = @_;
 6394:     my $value;
 6395:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
 6396: 	$value = $1;
 6397:     } elsif ($$string =~ s/^([^&]*?)&//) {
 6398: 	$value = $1;
 6399:     }
 6400:     return &unescape($value);
 6401: }
 6402: 
 6403: sub array2str {
 6404:   my (@array) = @_;
 6405:   my $result=&arrayref2str(\@array);
 6406:   $result=~s/^__ARRAY_REF__//;
 6407:   $result=~s/__END_ARRAY_REF__$//;
 6408:   return $result;
 6409: }
 6410: 
 6411: sub arrayref2str {
 6412:   my ($arrayref) = @_;
 6413:   my $result='__ARRAY_REF__';
 6414:   foreach my $elem (@$arrayref) {
 6415:     if(ref($elem) eq 'ARRAY') {
 6416:       $result.=&arrayref2str($elem).'&';
 6417:     } elsif(ref($elem) eq 'HASH') {
 6418:       $result.=&hashref2str($elem).'&';
 6419:     } elsif(ref($elem)) {
 6420:       #print("Got a ref of ".(ref($elem))." skipping.");
 6421:     } else {
 6422:       $result.=&escape($elem).'&';
 6423:     }
 6424:   }
 6425:   $result=~s/\&$//;
 6426:   $result .= '__END_ARRAY_REF__';
 6427:   return $result;
 6428: }
 6429: 
 6430: sub hash2str {
 6431:   my (%hash) = @_;
 6432:   my $result=&hashref2str(\%hash);
 6433:   $result=~s/^__HASH_REF__//;
 6434:   $result=~s/__END_HASH_REF__$//;
 6435:   return $result;
 6436: }
 6437: 
 6438: sub hashref2str {
 6439:   my ($hashref)=@_;
 6440:   my $result='__HASH_REF__';
 6441:   foreach my $key (sort(keys(%$hashref))) {
 6442:     if (ref($key) eq 'ARRAY') {
 6443:       $result.=&arrayref2str($key).'=';
 6444:     } elsif (ref($key) eq 'HASH') {
 6445:       $result.=&hashref2str($key).'=';
 6446:     } elsif (ref($key)) {
 6447:       $result.='=';
 6448:       #print("Got a ref of ".(ref($key))." skipping.");
 6449:     } else {
 6450: 	if (defined($key)) {$result.=&escape($key).'=';} else { last; }
 6451:     }
 6452: 
 6453:     if(ref($hashref->{$key}) eq 'ARRAY') {
 6454:       $result.=&arrayref2str($hashref->{$key}).'&';
 6455:     } elsif(ref($hashref->{$key}) eq 'HASH') {
 6456:       $result.=&hashref2str($hashref->{$key}).'&';
 6457:     } elsif(ref($hashref->{$key})) {
 6458:        $result.='&';
 6459:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
 6460:     } else {
 6461:       $result.=&escape($hashref->{$key}).'&';
 6462:     }
 6463:   }
 6464:   $result=~s/\&$//;
 6465:   $result .= '__END_HASH_REF__';
 6466:   return $result;
 6467: }
 6468: 
 6469: sub str2hash {
 6470:     my ($string)=@_;
 6471:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
 6472:     return %$hash;
 6473: }
 6474: 
 6475: sub str2hashref {
 6476:   my ($string) = @_;
 6477: 
 6478:   my %hash;
 6479: 
 6480:   if($string !~ /^__HASH_REF__/) {
 6481:       if (! ($string eq '' || !defined($string))) {
 6482: 	  $hash{'error'}='Not hash reference';
 6483:       }
 6484:       return (\%hash, $string);
 6485:   }
 6486: 
 6487:   $string =~ s/^__HASH_REF__//;
 6488: 
 6489:   while($string !~ /^__END_HASH_REF__/) {
 6490:       #key
 6491:       my $key='';
 6492:       if($string =~ /^__HASH_REF__/) {
 6493:           ($key, $string)=&str2hashref($string);
 6494:           if(defined($key->{'error'})) {
 6495:               $hash{'error'}='Bad data';
 6496:               return (\%hash, $string);
 6497:           }
 6498:       } elsif($string =~ /^__ARRAY_REF__/) {
 6499:           ($key, $string)=&str2arrayref($string);
 6500:           if($key->[0] eq 'Array reference error') {
 6501:               $hash{'error'}='Bad data';
 6502:               return (\%hash, $string);
 6503:           }
 6504:       } else {
 6505:           $string =~ s/^(.*?)=//;
 6506: 	  $key=&unescape($1);
 6507:       }
 6508:       $string =~ s/^=//;
 6509: 
 6510:       #value
 6511:       my $value='';
 6512:       if($string =~ /^__HASH_REF__/) {
 6513:           ($value, $string)=&str2hashref($string);
 6514:           if(defined($value->{'error'})) {
 6515:               $hash{'error'}='Bad data';
 6516:               return (\%hash, $string);
 6517:           }
 6518:       } elsif($string =~ /^__ARRAY_REF__/) {
 6519:           ($value, $string)=&str2arrayref($string);
 6520:           if($value->[0] eq 'Array reference error') {
 6521:               $hash{'error'}='Bad data';
 6522:               return (\%hash, $string);
 6523:           }
 6524:       } else {
 6525: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
 6526:       }
 6527:       $string =~ s/^&//;
 6528: 
 6529:       $hash{$key}=$value;
 6530:   }
 6531: 
 6532:   $string =~ s/^__END_HASH_REF__//;
 6533: 
 6534:   return (\%hash, $string);
 6535: }
 6536: 
 6537: sub str2array {
 6538:     my ($string)=@_;
 6539:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
 6540:     return @$array;
 6541: }
 6542: 
 6543: sub str2arrayref {
 6544:   my ($string) = @_;
 6545:   my @array;
 6546: 
 6547:   if($string !~ /^__ARRAY_REF__/) {
 6548:       if (! ($string eq '' || !defined($string))) {
 6549: 	  $array[0]='Array reference error';
 6550:       }
 6551:       return (\@array, $string);
 6552:   }
 6553: 
 6554:   $string =~ s/^__ARRAY_REF__//;
 6555: 
 6556:   while($string !~ /^__END_ARRAY_REF__/) {
 6557:       my $value='';
 6558:       if($string =~ /^__HASH_REF__/) {
 6559:           ($value, $string)=&str2hashref($string);
 6560:           if(defined($value->{'error'})) {
 6561:               $array[0] ='Array reference error';
 6562:               return (\@array, $string);
 6563:           }
 6564:       } elsif($string =~ /^__ARRAY_REF__/) {
 6565:           ($value, $string)=&str2arrayref($string);
 6566:           if($value->[0] eq 'Array reference error') {
 6567:               $array[0] ='Array reference error';
 6568:               return (\@array, $string);
 6569:           }
 6570:       } else {
 6571: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
 6572:       }
 6573:       $string =~ s/^&//;
 6574: 
 6575:       push(@array, $value);
 6576:   }
 6577: 
 6578:   $string =~ s/^__END_ARRAY_REF__//;
 6579: 
 6580:   return (\@array, $string);
 6581: }
 6582: 
 6583: # -------------------------------------------------------------------Temp Store
 6584: 
 6585: sub tmpreset {
 6586:   my ($symb,$namespace,$domain,$stuname) = @_;
 6587:   if (!$symb) {
 6588:     $symb=&symbread();
 6589:     if (!$symb) { $symb= $env{'request.url'}; }
 6590:   }
 6591:   $symb=escape($symb);
 6592: 
 6593:   if (!$namespace) { $namespace=$env{'request.state'}; }
 6594:   $namespace=~s/\//\_/g;
 6595:   $namespace=~s/\W//g;
 6596: 
 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 $path=LONCAPA::tempdir();
 6603:   my %hash;
 6604:   if (tie(%hash,'GDBM_File',
 6605: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 6606: 	  &GDBM_WRCREAT(),0640)) {
 6607:     foreach my $key (keys(%hash)) {
 6608:       if ($key=~ /:$symb/) {
 6609: 	delete($hash{$key});
 6610:       }
 6611:     }
 6612:   }
 6613: }
 6614: 
 6615: sub tmpstore {
 6616:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 6617: 
 6618:   if (!$symb) {
 6619:     $symb=&symbread();
 6620:     if (!$symb) { $symb= $env{'request.url'}; }
 6621:   }
 6622:   $symb=escape($symb);
 6623: 
 6624:   if (!$namespace) {
 6625:     # I don't think we would ever want to store this for a course.
 6626:     # it seems this will only be used if we don't have a course.
 6627:     #$namespace=$env{'request.course.id'};
 6628:     #if (!$namespace) {
 6629:       $namespace=$env{'request.state'};
 6630:     #}
 6631:   }
 6632:   $namespace=~s/\//\_/g;
 6633:   $namespace=~s/\W//g;
 6634:   if (!$domain) { $domain=$env{'user.domain'}; }
 6635:   if (!$stuname) { $stuname=$env{'user.name'}; }
 6636:   if ($domain eq 'public' && $stuname eq 'public') {
 6637:       $stuname=&get_requestor_ip();
 6638:   }
 6639:   my $now=time;
 6640:   my %hash;
 6641:   my $path=LONCAPA::tempdir();
 6642:   if (tie(%hash,'GDBM_File',
 6643: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 6644: 	  &GDBM_WRCREAT(),0640)) {
 6645:     $hash{"version:$symb"}++;
 6646:     my $version=$hash{"version:$symb"};
 6647:     my $allkeys=''; 
 6648:     foreach my $key (keys(%$storehash)) {
 6649:       $allkeys.=$key.':';
 6650:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
 6651:     }
 6652:     $hash{"$version:$symb:timestamp"}=$now;
 6653:     $allkeys.='timestamp';
 6654:     $hash{"$version:keys:$symb"}=$allkeys;
 6655:     if (untie(%hash)) {
 6656:       return 'ok';
 6657:     } else {
 6658:       return "error:$!";
 6659:     }
 6660:   } else {
 6661:     return "error:$!";
 6662:   }
 6663: }
 6664: 
 6665: # -----------------------------------------------------------------Temp Restore
 6666: 
 6667: sub tmprestore {
 6668:   my ($symb,$namespace,$domain,$stuname) = @_;
 6669: 
 6670:   if (!$symb) {
 6671:     $symb=&symbread();
 6672:     if (!$symb) { $symb= $env{'request.url'}; }
 6673:   }
 6674:   $symb=escape($symb);
 6675: 
 6676:   if (!$namespace) { $namespace=$env{'request.state'}; }
 6677: 
 6678:   if (!$domain) { $domain=$env{'user.domain'}; }
 6679:   if (!$stuname) { $stuname=$env{'user.name'}; }
 6680:   if ($domain eq 'public' && $stuname eq 'public') {
 6681:       $stuname=&get_requestor_ip();
 6682:   }
 6683:   my %returnhash;
 6684:   $namespace=~s/\//\_/g;
 6685:   $namespace=~s/\W//g;
 6686:   my %hash;
 6687:   my $path=LONCAPA::tempdir();
 6688:   if (tie(%hash,'GDBM_File',
 6689: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 6690: 	  &GDBM_READER(),0640)) {
 6691:     my $version=$hash{"version:$symb"};
 6692:     $returnhash{'version'}=$version;
 6693:     my $scope;
 6694:     for ($scope=1;$scope<=$version;$scope++) {
 6695:       my $vkeys=$hash{"$scope:keys:$symb"};
 6696:       my @keys=split(/:/,$vkeys);
 6697:       my $key;
 6698:       $returnhash{"$scope:keys"}=$vkeys;
 6699:       foreach $key (@keys) {
 6700: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 6701: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 6702:       }
 6703:     }
 6704:     if (!(untie(%hash))) {
 6705:       return "error:$!";
 6706:     }
 6707:   } else {
 6708:     return "error:$!";
 6709:   }
 6710:   return %returnhash;
 6711: }
 6712: 
 6713: # ----------------------------------------------------------------------- Store
 6714: 
 6715: sub store {
 6716:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
 6717:     my $home='';
 6718: 
 6719:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 6720: 
 6721:     $symb=&symbclean($symb);
 6722:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 6723: 
 6724:     if (!$domain) { $domain=$env{'user.domain'}; }
 6725:     if (!$stuname) { $stuname=$env{'user.name'}; }
 6726: 
 6727:     &devalidate($symb,$stuname,$domain);
 6728: 
 6729:     $symb=escape($symb);
 6730:     if (!$namespace) { 
 6731:        unless ($namespace=$env{'request.course.id'}) { 
 6732:           return ''; 
 6733:        } 
 6734:     }
 6735:     if (!$home) { $home=$env{'user.home'}; }
 6736: 
 6737:     $$storehash{'ip'}=&get_requestor_ip();
 6738:     $$storehash{'host'}=$perlvar{'lonHostID'};
 6739: 
 6740:     my $namevalue='';
 6741:     foreach my $key (keys(%$storehash)) {
 6742:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 6743:     }
 6744:     $namevalue=~s/\&$//;
 6745:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
 6746:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
 6747: }
 6748: 
 6749: # -------------------------------------------------------------- Critical Store
 6750: 
 6751: sub cstore {
 6752:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
 6753:     my $home='';
 6754: 
 6755:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 6756: 
 6757:     $symb=&symbclean($symb);
 6758:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 6759: 
 6760:     if (!$domain) { $domain=$env{'user.domain'}; }
 6761:     if (!$stuname) { $stuname=$env{'user.name'}; }
 6762: 
 6763:     &devalidate($symb,$stuname,$domain);
 6764: 
 6765:     $symb=escape($symb);
 6766:     if (!$namespace) { 
 6767:        unless ($namespace=$env{'request.course.id'}) { 
 6768:           return ''; 
 6769:        } 
 6770:     }
 6771:     if (!$home) { $home=$env{'user.home'}; }
 6772: 
 6773:     $$storehash{'ip'}=&get_requestor_ip();
 6774:     $$storehash{'host'}=$perlvar{'lonHostID'};
 6775: 
 6776:     my $namevalue='';
 6777:     foreach my $key (keys(%$storehash)) {
 6778:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 6779:     }
 6780:     $namevalue=~s/\&$//;
 6781:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
 6782:     return critical
 6783:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
 6784: }
 6785: 
 6786: # --------------------------------------------------------------------- Restore
 6787: 
 6788: sub restore {
 6789:     my ($symb,$namespace,$domain,$stuname) = @_;
 6790:     my $home='';
 6791: 
 6792:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 6793: 
 6794:     if (!$symb) {
 6795:         return if ($namespace eq 'courserequests');
 6796:         unless ($symb=escape(&symbread())) { return ''; }
 6797:     } else {
 6798:         unless ($namespace eq 'courserequests') {
 6799:             $symb=&escape(&symbclean($symb));
 6800:         }
 6801:     }
 6802:     if (!$namespace) { 
 6803:        unless ($namespace=$env{'request.course.id'}) { 
 6804:           return ''; 
 6805:        } 
 6806:     }
 6807:     if (!$domain) { $domain=$env{'user.domain'}; }
 6808:     if (!$stuname) { $stuname=$env{'user.name'}; }
 6809:     if (!$home) { $home=$env{'user.home'}; }
 6810:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
 6811: 
 6812:     my %returnhash=();
 6813:     foreach my $line (split(/\&/,$answer)) {
 6814: 	my ($name,$value)=split(/\=/,$line);
 6815:         $returnhash{&unescape($name)}=&thaw_unescape($value);
 6816:     }
 6817:     my $version;
 6818:     for ($version=1;$version<=$returnhash{'version'};$version++) {
 6819:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
 6820:           $returnhash{$item}=$returnhash{$version.':'.$item};
 6821:        }
 6822:     }
 6823:     return %returnhash;
 6824: }
 6825: 
 6826: # ---------------------------------------------------------- Course Description
 6827: #
 6828: #  
 6829: 
 6830: sub coursedescription {
 6831:     my ($courseid,$args)=@_;
 6832:     $courseid=~s/^\///;
 6833:     $courseid=~s/\_/\//g;
 6834:     my ($cdomain,$cnum)=split(/\//,$courseid);
 6835:     my $chome=&homeserver($cnum,$cdomain);
 6836:     my $normalid=$cdomain.'_'.$cnum;
 6837:     # need to always cache even if we get errors otherwise we keep 
 6838:     # trying and trying and trying to get the course description.
 6839:     my %envhash=();
 6840:     my %returnhash=();
 6841:     
 6842:     my $expiretime=600;
 6843:     if ($env{'request.course.id'} eq $normalid) {
 6844: 	$expiretime=120;
 6845:     }
 6846: 
 6847:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
 6848:     if (!$args->{'freshen_cache'}
 6849: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
 6850: 	foreach my $key (keys(%env)) {
 6851: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
 6852: 	    my ($setting) = $1;
 6853: 	    $returnhash{$setting} = $env{$key};
 6854: 	}
 6855: 	return %returnhash;
 6856:     }
 6857: 
 6858:     # get the data again
 6859: 
 6860:     if (!$args->{'one_time'}) {
 6861: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
 6862:     }
 6863: 
 6864:     if ($chome ne 'no_host') {
 6865:        %returnhash=&dump('environment',$cdomain,$cnum);
 6866:        if (!exists($returnhash{'con_lost'})) {
 6867: 	   my $username = $env{'user.name'}; # Defult username
 6868: 	   if(defined $args->{'user'}) {
 6869: 	       $username = $args->{'user'};
 6870: 	   }
 6871:            $returnhash{'home'}= $chome;
 6872: 	   $returnhash{'domain'} = $cdomain;
 6873: 	   $returnhash{'num'} = $cnum;
 6874:            if (!defined($returnhash{'type'})) {
 6875:                $returnhash{'type'} = 'Course';
 6876:            }
 6877:            while (my ($name,$value) = each %returnhash) {
 6878:                $envhash{'course.'.$normalid.'.'.$name}=$value;
 6879:            }
 6880:            $returnhash{'url'}=&clutter($returnhash{'url'});
 6881:            $returnhash{'fn'}=LONCAPA::tempdir() .
 6882: 	       $username.'_'.$cdomain.'_'.$cnum;
 6883:            $envhash{'course.'.$normalid.'.home'}=$chome;
 6884:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
 6885:            $envhash{'course.'.$normalid.'.num'}=$cnum;
 6886:        }
 6887:     }
 6888:     if (!$args->{'one_time'}) {
 6889: 	&appenv(\%envhash);
 6890:     }
 6891:     return %returnhash;
 6892: }
 6893: 
 6894: sub update_released_required {
 6895:     my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
 6896:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
 6897:         $cid = $env{'request.course.id'};
 6898:         $cdom = $env{'course.'.$cid.'.domain'};
 6899:         $cnum = $env{'course.'.$cid.'.num'};
 6900:         $chome = $env{'course.'.$cid.'.home'};
 6901:     }
 6902:     if ($needsrelease) {
 6903:         my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
 6904:         my $needsupdate;
 6905:         if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
 6906:             $needsupdate = 1;
 6907:         } else {
 6908:             my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
 6909:             my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
 6910:             if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
 6911:                 $needsupdate = 1;
 6912:             }
 6913:         }
 6914:         if ($needsupdate) {
 6915:             my %needshash = (
 6916:                              'internal.releaserequired' => $needsrelease,
 6917:                             );
 6918:             my $putresult = &put('environment',\%needshash,$cdom,$cnum);
 6919:             if ($putresult eq 'ok') {
 6920:                 &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
 6921:                 my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
 6922:                 if (ref($crsinfo{$cid}) eq 'HASH') {
 6923:                     $crsinfo{$cid}{'releaserequired'} = $needsrelease;
 6924:                     &courseidput($cdom,\%crsinfo,$chome,'notime');
 6925:                 }
 6926:             }
 6927:         }
 6928:     }
 6929:     return;
 6930: }
 6931: 
 6932: # -------------------------------------------------See if a user is privileged
 6933: 
 6934: sub privileged {
 6935:     my ($username,$domain,$possdomains,$possroles)=@_;
 6936:     my $now = time;
 6937:     my $roles;
 6938:     if (ref($possroles) eq 'ARRAY') {
 6939:         $roles = $possroles; 
 6940:     } else {
 6941:         $roles = ['dc','su'];
 6942:     }
 6943:     if (ref($possdomains) eq 'ARRAY') {
 6944:         my %privileged = &privileged_by_domain($possdomains,$roles);
 6945:         foreach my $dom (@{$possdomains}) {
 6946:             if (($username =~ /^$match_username$/) && ($domain =~ /^$match_domain$/) &&
 6947:                 (ref($privileged{$dom}) eq 'HASH')) {
 6948:                 foreach my $role (@{$roles}) {
 6949:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
 6950:                         if (exists($privileged{$dom}{$role}{$username.':'.$domain})) {
 6951:                             my ($end,$start) = split(/:/,$privileged{$dom}{$role}{$username.':'.$domain});
 6952:                             return 1 unless (($end && $end < $now) ||
 6953:                                              ($start && $start > $now));
 6954:                         }
 6955:                     }
 6956:                 }
 6957:             }
 6958:         }
 6959:     } else {
 6960:         my %rolesdump = &dump("roles", $domain, $username) or return 0;
 6961:         my $now = time;
 6962: 
 6963:         for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys(%rolesdump)}) {
 6964:             my ($trole, $tend, $tstart) = split(/_/, $role);
 6965:             if (grep(/^\Q$trole\E$/,@{$roles})) {
 6966:                 return 1 unless ($tend && $tend < $now) 
 6967:                         or ($tstart && $tstart > $now);
 6968:             }
 6969:         }
 6970:     }
 6971:     return 0;
 6972: }
 6973: 
 6974: sub privileged_by_domain {
 6975:     my ($domains,$roles) = @_;
 6976:     my %privileged = ();
 6977:     my $cachetime = 60*60*24;
 6978:     my $now = time;
 6979:     unless ((ref($domains) eq 'ARRAY') && (ref($roles) eq 'ARRAY')) {
 6980:         return %privileged;
 6981:     }
 6982:     foreach my $dom (@{$domains}) {
 6983:         next if (ref($privileged{$dom}) eq 'HASH');
 6984:         my $needroles;
 6985:         foreach my $role (@{$roles}) {
 6986:             my ($result,$cached)=&is_cached_new('priv_'.$role,$dom);
 6987:             if (defined($cached)) {
 6988:                 if (ref($result) eq 'HASH') {
 6989:                     $privileged{$dom}{$role} = $result;
 6990:                 }
 6991:             } else {
 6992:                 $needroles = 1;
 6993:             }
 6994:         }
 6995:         if ($needroles) {
 6996:             my %dompersonnel = &get_domain_roles($dom,$roles);
 6997:             $privileged{$dom} = {};
 6998:             foreach my $server (keys(%dompersonnel)) {
 6999:                 if (ref($dompersonnel{$server}) eq 'HASH') {
 7000:                     foreach my $item (keys(%{$dompersonnel{$server}})) {
 7001:                         my ($trole,$uname,$udom,$rest) = split(/:/,$item,4);
 7002:                         my ($end,$start) = split(/:/,$dompersonnel{$server}{$item});
 7003:                         next if ($end && $end < $now);
 7004:                         $privileged{$dom}{$trole}{$uname.':'.$udom} = 
 7005:                             $dompersonnel{$server}{$item};
 7006:                     }
 7007:                 }
 7008:             }
 7009:             if (ref($privileged{$dom}) eq 'HASH') {
 7010:                 foreach my $role (@{$roles}) {
 7011:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
 7012:                         &do_cache_new('priv_'.$role,$dom,$privileged{$dom}{$role},$cachetime);
 7013:                     } else {
 7014:                         my %hash = ();
 7015:                         &do_cache_new('priv_'.$role,$dom,\%hash,$cachetime);
 7016:                     }
 7017:                 }
 7018:             }
 7019:         }
 7020:     }
 7021:     return %privileged;
 7022: }
 7023: 
 7024: # -------------------------------------------------------- Get user privileges
 7025: 
 7026: sub rolesinit {
 7027:     my ($domain, $username) = @_;
 7028:     my %userroles = ('user.login.time' => time);
 7029:     my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
 7030: 
 7031:     # firstaccess and timerinterval are related to timed maps/resources. 
 7032:     # also, blocking can be triggered by an activating timer
 7033:     # it's saved in the user's %env.
 7034:     my %firstaccess = &dump('firstaccesstimes', $domain, $username);
 7035:     my %timerinterval = &dump('timerinterval', $domain, $username);
 7036:     my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
 7037:         %timerintchk, %timerintenv, %coauthorenv);
 7038: 
 7039:     foreach my $key (keys(%firstaccess)) {
 7040:         my ($cid, $rest) = split(/\0/, $key);
 7041:         $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
 7042:     }
 7043: 
 7044:     foreach my $key (keys(%timerinterval)) {
 7045:         my ($cid,$rest) = split(/\0/,$key);
 7046:         $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
 7047:     }
 7048: 
 7049:     my %allroles=();
 7050:     my %allgroups=();
 7051:     my %gotcoauconfig=();
 7052:     my %domdefaults=();
 7053: 
 7054:     for my $area (grep { ! /^rolesdef_/ } keys(%rolesdump)) {
 7055:         my $role = $rolesdump{$area};
 7056:         $area =~ s/\_\w\w$//;
 7057: 
 7058:         my ($trole, $tend, $tstart, $group_privs);
 7059: 
 7060:         if ($role =~ /^cr/) {
 7061:         # Custom role, defined by a user 
 7062:         # e.g., user.role.cr/msu/smith/mynewrole
 7063:             if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
 7064:                 $trole = $1;
 7065:                 ($tend, $tstart) = split('_', $2);
 7066:             } else {
 7067:                 $trole = $role;
 7068:             }
 7069:         } elsif ($role =~ m|^gr/|) {
 7070:         # Role of member in a group, defined within a course/community
 7071:         # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
 7072:             ($trole, $tend, $tstart) = split(/_/, $role);
 7073:             next if $tstart eq '-1';
 7074:             ($trole, $group_privs) = split(/\//, $trole);
 7075:             $group_privs = &unescape($group_privs);
 7076:         } else {
 7077:         # Just a normal role, defined in roles.tab
 7078:             ($trole, $tend, $tstart) = split(/_/,$role);
 7079:         }
 7080: 
 7081:         my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
 7082:                  $username);
 7083:         @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
 7084: 
 7085:         # role expired or not available yet?
 7086:         $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or 
 7087:             ($tstart != 0 && $tstart > $userroles{'user.login.time'});
 7088: 
 7089:         next if $area eq '' or $trole eq '';
 7090: 
 7091:         my $spec = "$trole.$area";
 7092:         my ($tdummy, $tdomain, $trest) = split(/\//, $area);
 7093: 
 7094:         if ($trole =~ /^cr\//) {
 7095:         # Custom role, defined by a user
 7096:             &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
 7097:         } elsif ($trole eq 'gr') {
 7098:         # Role of a member in a group, defined within a course/community
 7099:             &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
 7100:             next;
 7101:         } else {
 7102:         # Normal role, defined in roles.tab
 7103:             &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
 7104:             if (($trole eq 'ca') || ($trole eq 'aa')) {
 7105:                 (undef,my ($audom,$auname)) = split(/\//,$area);
 7106:                 unless ($gotcoauconfig{$area}) {
 7107:                     my @ca_settings = ('authoreditors','coauthorlist','coauthoroptin');
 7108:                     my %info = &userenvironment($audom,$auname,@ca_settings);
 7109:                     $gotcoauconfig{$area} = 1;
 7110:                     foreach my $item (@ca_settings) {
 7111:                         if (exists($info{$item})) {
 7112:                             my $name = $item;
 7113:                             if ($item eq 'authoreditors') {
 7114:                                 $name = 'editors';
 7115:                                 unless ($info{'authoreditors'}) {
 7116:                                     my %domdefs;
 7117:                                     if (ref($domdefaults{$audom}) eq 'HASH') {
 7118:                                         %domdefs = %{$domdefaults{$audom}};
 7119:                                     } else {
 7120:                                         %domdefs = &get_domain_defaults($audom);
 7121:                                         $domdefaults{$audom} = \%domdefs;
 7122:                                     }
 7123:                                     if ($domdefs{$name} ne '') {
 7124:                                         $info{'authoreditors'} = $domdefs{$name};
 7125:                                     } else {
 7126:                                         $info{'authoreditors'} = 'edit,xml';
 7127:                                     }
 7128:                                 }
 7129:                             }
 7130:                             $coauthorenv{"environment.internal.$name.$area"} = $info{$item};
 7131:                         }
 7132:                     }
 7133:                 }
 7134:             }
 7135:         }
 7136: 
 7137:         my $cid = $tdomain.'_'.$trest;
 7138:         unless ($firstaccchk{$cid}) {
 7139:             if (ref($coursetimerstarts{$cid}) eq 'HASH') {
 7140:                 foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
 7141:                     $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} = 
 7142:                         $coursetimerstarts{$cid}{$item}; 
 7143:                 }
 7144:             }
 7145:             $firstaccchk{$cid} = 1;
 7146:         }
 7147:         unless ($timerintchk{$cid}) {
 7148:             if (ref($coursetimerintervals{$cid}) eq 'HASH') {
 7149:                 foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
 7150:                     $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
 7151:                        $coursetimerintervals{$cid}{$item};
 7152:                 }
 7153:             }
 7154:             $timerintchk{$cid} = 1;
 7155:         }
 7156:     }
 7157: 
 7158:     @userroles{'user.author','user.adv','user.rar'} = &set_userprivs(\%userroles,
 7159:                                                           \%allroles, \%allgroups);
 7160:     $env{'user.adv'} = $userroles{'user.adv'};
 7161:     $env{'user.rar'} = $userroles{'user.rar'};
 7162: 
 7163:     return (\%userroles,\%firstaccenv,\%timerintenv,\%coauthorenv);
 7164: }
 7165: 
 7166: sub set_arearole {
 7167:     my ($trole,$area,$tstart,$tend,$domain,$username,$nolog) = @_;
 7168:     unless ($nolog) {
 7169: # log the associated role with the area
 7170:         &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
 7171:     }
 7172:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
 7173: }
 7174: 
 7175: sub custom_roleprivs {
 7176:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
 7177:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
 7178:     my $homsvr = &homeserver($rauthor,$rdomain);
 7179:     if (&hostname($homsvr) ne '') {
 7180:         my ($rdummy,$roledef)=
 7181:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
 7182:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
 7183:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
 7184:             if (defined($syspriv)) {
 7185:                 if ($trest =~ /^$match_community$/) {
 7186:                     $syspriv =~ s/bre\&S//; 
 7187:                 }
 7188:                 $$allroles{'cm./'}.=':'.$syspriv;
 7189:                 $$allroles{$spec.'./'}.=':'.$syspriv;
 7190:             }
 7191:             if ($tdomain ne '') {
 7192:                 if (defined($dompriv)) {
 7193:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
 7194:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
 7195:                 }
 7196:                 if (($trest ne '') && (defined($coursepriv))) {
 7197:                     if ($trole =~ m{^cr/$tdomain/$tdomain\Q-domainconfig\E/([^/]+)$}) {
 7198:                         my $rolename = $1;
 7199:                         $coursepriv = &course_adhocrole_privs($rolename,$tdomain,$trest,$coursepriv);
 7200:                     }
 7201:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
 7202:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
 7203:                 }
 7204:             }
 7205:         }
 7206:     }
 7207: }
 7208: 
 7209: sub course_adhocrole_privs {
 7210:     my ($rolename,$cdom,$cnum,$coursepriv) = @_;
 7211:     my %overrides = &get('environment',["internal.adhocpriv.$rolename"],$cdom,$cnum);
 7212:     if ($overrides{"internal.adhocpriv.$rolename"}) {
 7213:         my (%currprivs,%storeprivs);
 7214:         foreach my $item (split(/:/,$coursepriv)) {
 7215:             my ($priv,$restrict) = split(/\&/,$item);
 7216:             $currprivs{$priv} = $restrict;
 7217:         }
 7218:         my (%possadd,%possremove,%full);
 7219:         foreach my $item (split(/\:/,$Apache::lonnet::pr{'cr:c'})) {
 7220:             my ($priv,$restrict)=split(/\&/,$item);
 7221:             $full{$priv} = $restrict;
 7222:         }
 7223:         foreach my $item (split(/,/,$overrides{"internal.adhocpriv.$rolename"})) {
 7224:             next if ($item eq '');
 7225:             my ($rule,$rest) = split(/=/,$item);
 7226:             next unless (($rule eq 'off') || ($rule eq 'on'));
 7227:             foreach my $priv (split(/:/,$rest)) {
 7228:                 if ($priv ne '') {
 7229:                     if ($rule eq 'off') {
 7230:                         $possremove{$priv} = 1;
 7231:                     } else {
 7232:                         $possadd{$priv} = 1;
 7233:                     }
 7234:                 }
 7235:             }
 7236:         }
 7237:         foreach my $priv (sort(keys(%full))) {
 7238:             if (exists($currprivs{$priv})) {
 7239:                 unless (exists($possremove{$priv})) {
 7240:                     $storeprivs{$priv} = $currprivs{$priv};
 7241:                 }
 7242:             } elsif (exists($possadd{$priv})) {
 7243:                 $storeprivs{$priv} = $full{$priv};
 7244:             }
 7245:         }
 7246:         $coursepriv = ':'.join(':',map { $_.'&'.$storeprivs{$_}; } sort(keys(%storeprivs)));
 7247:     }
 7248:     return $coursepriv;
 7249: }
 7250: 
 7251: sub group_roleprivs {
 7252:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
 7253:     my $access = 1;
 7254:     my $now = time;
 7255:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
 7256:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
 7257:     if ($access) {
 7258:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
 7259:         $$allgroups{$course}{$group} .=':'.$group_privs;
 7260:     }
 7261: }
 7262: 
 7263: sub standard_roleprivs {
 7264:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
 7265:     if (defined($pr{$trole.':s'})) {
 7266:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
 7267:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
 7268:     }
 7269:     if ($tdomain ne '') {
 7270:         if (defined($pr{$trole.':d'})) {
 7271:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 7272:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 7273:         }
 7274:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
 7275:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
 7276:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
 7277:         }
 7278:     }
 7279: }
 7280: 
 7281: sub set_userprivs {
 7282:     my ($userroles,$allroles,$allgroups,$groups_roles) = @_; 
 7283:     my $author=0;
 7284:     my $adv=0;
 7285:     my $rar=0;
 7286:     my %grouproles = ();
 7287:     if (keys(%{$allgroups}) > 0) {
 7288:         my @groupkeys; 
 7289:         foreach my $role (keys(%{$allroles})) {
 7290:             push(@groupkeys,$role);
 7291:         }
 7292:         if (ref($groups_roles) eq 'HASH') {
 7293:             foreach my $key (keys(%{$groups_roles})) {
 7294:                 unless (grep(/^\Q$key\E$/,@groupkeys)) {
 7295:                     push(@groupkeys,$key);
 7296:                 }
 7297:             }
 7298:         }
 7299:         if (@groupkeys > 0) {
 7300:             foreach my $role (@groupkeys) {
 7301:                 my ($trole,$area,$sec,$extendedarea);
 7302:                 if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
 7303:                     $trole = $1;
 7304:                     $area = $2;
 7305:                     $sec = $3;
 7306:                     $extendedarea = $area.$sec;
 7307:                     if (exists($$allgroups{$area})) {
 7308:                         foreach my $group (keys(%{$$allgroups{$area}})) {
 7309:                             my $spec = $trole.'.'.$extendedarea;
 7310:                             $grouproles{$spec.'.'.$area.'/'.$group} = 
 7311:                                                 $$allgroups{$area}{$group};
 7312:                         }
 7313:                     }
 7314:                 }
 7315:             }
 7316:         }
 7317:     }
 7318:     foreach my $group (keys(%grouproles)) {
 7319:         $$allroles{$group} = $grouproles{$group};
 7320:     }
 7321:     foreach my $role (keys(%{$allroles})) {
 7322:         my %thesepriv;
 7323:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
 7324:         foreach my $item (split(/:/,$$allroles{$role})) {
 7325:             if ($item ne '') {
 7326:                 my ($privilege,$restrictions)=split(/&/,$item);
 7327:                 if ($restrictions eq '') {
 7328:                     $thesepriv{$privilege}='F';
 7329:                 } elsif ($thesepriv{$privilege} ne 'F') {
 7330:                     $thesepriv{$privilege}.=$restrictions;
 7331:                 }
 7332:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
 7333:                 if ($thesepriv{'rar'} eq 'F') { $rar=1; }
 7334:             }
 7335:         }
 7336:         my $thesestr='';
 7337:         foreach my $priv (sort(keys(%thesepriv))) {
 7338: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
 7339: 	}
 7340:         $userroles->{'user.priv.'.$role} = $thesestr;
 7341:     }
 7342:     return ($author,$adv,$rar);
 7343: }
 7344: 
 7345: sub role_status {
 7346:     my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
 7347:     if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
 7348:         my ($one,$two) = split(m{\./},$rolekey,2);
 7349:         (undef,undef,$$role) = split(/\./,$one,3);
 7350:         unless (!defined($$role) || $$role eq '') {
 7351:             $$where = '/'.$two;
 7352:             $$trolecode=$$role.'.'.$$where;
 7353:             ($$tstart,$$tend)=split(/\./,$env{$rolekey});
 7354:             $$tstatus='is';
 7355:             if ($$tstart && $$tstart>$update) {
 7356:                 $$tstatus='future';
 7357:                 if ($$tstart<$now) {
 7358:                     if ($$tstart && $$tstart>$refresh) {
 7359:                         if (($$where ne '') && ($$role ne '')) {
 7360:                             my (%allroles,%allgroups,$group_privs,
 7361:                                 %groups_roles,@rolecodes);
 7362:                             my %userroles = (
 7363:                                 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
 7364:                             );
 7365:                             @rolecodes = ('cm'); 
 7366:                             my $spec=$$role.'.'.$$where;
 7367:                             my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
 7368:                             if ($$role =~ /^cr\//) {
 7369:                                 &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
 7370:                                 push(@rolecodes,'cr');
 7371:                             } elsif ($$role eq 'gr') {
 7372:                                 push(@rolecodes,$$role);
 7373:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
 7374:                                                     $env{'user.name'});
 7375:                                 my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
 7376:                                 (undef,my $group_privs) = split(/\//,$trole);
 7377:                                 $group_privs = &unescape($group_privs);
 7378:                                 &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
 7379:                                 my %course_roles = &get_my_roles($env{'user.name'},$env{'user.domain'},'userroles',['active'],['cc','co','in','ta','ep','ad','st','cr'],[$tdomain],1);
 7380:                                 &get_groups_roles($tdomain,$trest,
 7381:                                                   \%course_roles,\@rolecodes,
 7382:                                                   \%groups_roles);
 7383:                             } else {
 7384:                                 push(@rolecodes,$$role);
 7385:                                 &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
 7386:                             }
 7387:                             my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%allroles,\%allgroups,
 7388:                                                                    \%groups_roles);
 7389:                             &appenv(\%userroles,\@rolecodes);
 7390:                             &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
 7391:                         }
 7392:                     }
 7393:                     $$tstatus = 'is';
 7394:                 }
 7395:             }
 7396:             if ($$tend) {
 7397:                 if ($$tend<$update) {
 7398:                     $$tstatus='expired';
 7399:                 } elsif ($$tend<$now) {
 7400:                     $$tstatus='will_not';
 7401:                 }
 7402:             }
 7403:         }
 7404:     }
 7405: }
 7406: 
 7407: sub get_groups_roles {
 7408:     my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
 7409:     return unless((ref($cdom_courseroles) eq 'HASH') && 
 7410:                   (ref($rolecodes) eq 'ARRAY') && 
 7411:                   (ref($groups_roles) eq 'HASH')); 
 7412:     if (keys(%{$cdom_courseroles}) > 0) {
 7413:         my ($cnum) = ($rest =~ /^($match_courseid)/);
 7414:         if ($cdom ne '' && $cnum ne '') {
 7415:             foreach my $key (keys(%{$cdom_courseroles})) {
 7416:                 if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
 7417:                     my $crsrole = $1;
 7418:                     my $crssec = $2;
 7419:                     if ($crsrole =~ /^cr/) {
 7420:                         unless (grep(/^cr$/,@{$rolecodes})) {
 7421:                             push(@{$rolecodes},'cr');
 7422:                         }
 7423:                     } else {
 7424:                         unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
 7425:                             push(@{$rolecodes},$crsrole);
 7426:                         }
 7427:                     }
 7428:                     my $rolekey = "$crsrole./$cdom/$cnum";
 7429:                     if ($crssec ne '') {
 7430:                         $rolekey .= "/$crssec";
 7431:                     }
 7432:                     $rolekey .= './';
 7433:                     $groups_roles->{$rolekey} = $rolecodes;
 7434:                 }
 7435:             }
 7436:         }
 7437:     }
 7438:     return;
 7439: }
 7440: 
 7441: sub delete_env_groupprivs {
 7442:     my ($where,$courseroles,$possroles) = @_;
 7443:     return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
 7444:     my ($dummy,$udom,$uname,$group) = split(/\//,$where);
 7445:     unless (ref($courseroles->{$udom}) eq 'HASH') {
 7446:         %{$courseroles->{$udom}} =
 7447:             &get_my_roles('','','userroles',['active'],
 7448:                           $possroles,[$udom],1);
 7449:     }
 7450:     if (ref($courseroles->{$udom}) eq 'HASH') {
 7451:         foreach my $item (keys(%{$courseroles->{$udom}})) {
 7452:             my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
 7453:             my $area = '/'.$cdom.'/'.$cnum;
 7454:             my $privkey = "user.priv.$crsrole.$area";
 7455:             if ($crssec ne '') {
 7456:                 $privkey .= '/'.$crssec;
 7457:             }
 7458:             $privkey .= ".$area/$group";
 7459:             &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
 7460:         }
 7461:     }
 7462:     return;
 7463: }
 7464: 
 7465: sub check_adhoc_privs {
 7466:     my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller,$sec) = @_;
 7467:     my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
 7468:     if ($sec) {
 7469:         $cckey .= '/'.$sec;
 7470:     } 
 7471:     my $setprivs;
 7472:     if ($env{$cckey}) {
 7473:         my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
 7474:         &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
 7475:         unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
 7476:             &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
 7477:             $setprivs = 1;
 7478:         }
 7479:     } else {
 7480:         &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
 7481:         $setprivs = 1;
 7482:     }
 7483:     return $setprivs;
 7484: }
 7485: 
 7486: sub set_adhoc_privileges {
 7487: # role can be cc, ca, or cr/<dom>/<dom>-domainconfig/role
 7488:     my ($dcdom,$pickedcourse,$role,$caller,$sec) = @_;
 7489:     my $area = '/'.$dcdom.'/'.$pickedcourse;
 7490:     if ($sec ne '') {
 7491:         $area .= '/'.$sec;
 7492:     }
 7493:     my $spec = $role.'.'.$area;
 7494:     my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
 7495:                                   $env{'user.name'},1);
 7496:     my %rolehash = ();
 7497:     if ($role =~ m{^\Qcr/$dcdom/$dcdom\E\-domainconfig/(\w+)$}) {
 7498:         my $rolename = $1;
 7499:         &custom_roleprivs(\%rolehash,$role,$dcdom,$pickedcourse,$spec,$area);
 7500:         my %domdef = &get_domain_defaults($dcdom);
 7501:         if (ref($domdef{'adhocroles'}) eq 'HASH') {
 7502:             if (ref($domdef{'adhocroles'}{$rolename}) eq 'HASH') {
 7503:                 &appenv({'request.role.desc' => $domdef{'adhocroles'}{$rolename}{'desc'},});
 7504:             }
 7505:         }
 7506:     } else {
 7507:         &standard_roleprivs(\%rolehash,$role,$dcdom,$spec,$pickedcourse,$area);
 7508:     }
 7509:     my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%rolehash);
 7510:     &appenv(\%userroles,[$role,'cm']);
 7511:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
 7512:     unless (($caller eq 'constructaccess' && $env{'request.course.id'}) ||
 7513:             ($caller eq 'tiny')) {
 7514:         &appenv( {'request.role'        => $spec,
 7515:                   'request.role.domain' => $dcdom,
 7516:                   'request.course.sec'  => $sec,
 7517:                  }
 7518:                );
 7519:         my $tadv=0;
 7520:         if (&allowed('adv') eq 'F') { $tadv=1; }
 7521:         &appenv({'request.role.adv'    => $tadv});
 7522:     }
 7523: }
 7524: 
 7525: # --------------------------------------------------------------- get interface
 7526: 
 7527: sub get {
 7528:    my ($namespace,$storearr,$udomain,$uname)=@_;
 7529:    my $items='';
 7530:    foreach my $item (@$storearr) {
 7531:        $items.=&escape($item).'&';
 7532:    }
 7533:    $items=~s/\&$//;
 7534:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 7535:    if (!$uname) { $uname=$env{'user.name'}; }
 7536:    my $uhome=&homeserver($uname,$udomain);
 7537: 
 7538:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
 7539:    my @pairs=split(/\&/,$rep);
 7540:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
 7541:      return @pairs;
 7542:    }
 7543:    my %returnhash=();
 7544:    my $i=0;
 7545:    foreach my $item (@$storearr) {
 7546:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 7547:       $i++;
 7548:    }
 7549:    return %returnhash;
 7550: }
 7551: 
 7552: # --------------------------------------------------------------- del interface
 7553: 
 7554: sub del {
 7555:    my ($namespace,$storearr,$udomain,$uname)=@_;
 7556:    my $items='';
 7557:    foreach my $item (@$storearr) {
 7558:        $items.=&escape($item).'&';
 7559:    }
 7560: 
 7561:    $items=~s/\&$//;
 7562:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 7563:    if (!$uname) { $uname=$env{'user.name'}; }
 7564:    my $uhome=&homeserver($uname,$udomain);
 7565:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
 7566: }
 7567: 
 7568: # -------------------------------------------------------------- dump interface
 7569: 
 7570: sub unserialize {
 7571:     my ($rep, $escapedkeys) = @_;
 7572: 
 7573:     return {} if $rep =~ /^error/;
 7574: 
 7575:     my %returnhash=();
 7576: 	foreach my $item (split(/\&/,$rep)) {
 7577: 	    my ($key, $value) = split(/=/, $item, 2);
 7578: 	    $key = unescape($key) unless $escapedkeys;
 7579: 	    next if $key =~ /^error: 2 /;
 7580: 	    $returnhash{$key} = &thaw_unescape($value);
 7581: 	}
 7582:     #return %returnhash;
 7583:     return \%returnhash;
 7584: }        
 7585: 
 7586: # see Lond::dump_with_regexp
 7587: # if $escapedkeys hash keys won't get unescaped.
 7588: sub dump {
 7589:     my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys,$encrypt)=@_;
 7590:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 7591:     if (!$uname) { $uname=$env{'user.name'}; }
 7592:     my $uhome=&homeserver($uname,$udomain);
 7593: 
 7594:     if ($regexp) {
 7595:         $regexp=&escape($regexp);
 7596:     } else {
 7597:         $regexp='.';
 7598:     }
 7599:     if (grep { $_ eq $uhome } current_machine_ids()) {
 7600:         # user is hosted on this machine
 7601:         my $reply = LONCAPA::Lond::dump_with_regexp(join(":", ($udomain,
 7602:                     $uname, $namespace, $regexp, $range)), $perlvar{'lonVersion'});
 7603:         return %{unserialize($reply, $escapedkeys)};
 7604:     }
 7605:     my $rep;
 7606:     if ($encrypt) {
 7607:         $rep=&reply("encrypt:edump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
 7608:     } else {
 7609:         $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
 7610:     }
 7611:     my @pairs=split(/\&/,$rep);
 7612:     my %returnhash=();
 7613:     if (!($rep =~ /^error/ )) {
 7614: 	foreach my $item (@pairs) {
 7615: 	    my ($key,$value)=split(/=/,$item,2);
 7616:         $key = unescape($key) unless $escapedkeys;
 7617:         #$key = &unescape($key);
 7618: 	    next if ($key =~ /^error: 2 /);
 7619: 	    $returnhash{$key}=&thaw_unescape($value);
 7620: 	}
 7621:     }
 7622:     return %returnhash;
 7623: }
 7624: 
 7625: 
 7626: # --------------------------------------------------------- dumpstore interface
 7627: 
 7628: sub dumpstore {
 7629:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
 7630:    # same as dump but keys must be escaped. They may contain colon separated
 7631:    # lists of values that may themself contain colons (e.g. symbs).
 7632:    return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
 7633: }
 7634: 
 7635: # -------------------------------------------------------------- keys interface
 7636: 
 7637: sub getkeys {
 7638:    my ($namespace,$udomain,$uname)=@_;
 7639:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 7640:    if (!$uname) { $uname=$env{'user.name'}; }
 7641:    my $uhome=&homeserver($uname,$udomain);
 7642:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
 7643:    my @keyarray=();
 7644:    foreach my $key (split(/\&/,$rep)) {
 7645:       next if ($key =~ /^error: 2 /);
 7646:       push(@keyarray,&unescape($key));
 7647:    }
 7648:    return @keyarray;
 7649: }
 7650: 
 7651: # --------------------------------------------------------------- currentdump
 7652: sub currentdump {
 7653:    my ($courseid,$sdom,$sname)=@_;
 7654:    $courseid = $env{'request.course.id'} if (! defined($courseid));
 7655:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
 7656:    $sname    = $env{'user.name'}         if (! defined($sname));
 7657:    my $uhome = &homeserver($sname,$sdom);
 7658:    my $rep;
 7659: 
 7660:    if (grep { $_ eq $uhome } current_machine_ids()) {
 7661:        $rep = LONCAPA::Lond::dump_profile_database(join(":", ($sdom, $sname, 
 7662:                    $courseid)));
 7663:    } else {
 7664:        $rep = reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
 7665:    }
 7666: 
 7667:    return if ($rep =~ /^(error:|no_such_host)/);
 7668:    #
 7669:    my %returnhash=();
 7670:    #
 7671:    if ($rep eq 'unknown_cmd') {
 7672:        # an old lond will not know currentdump
 7673:        # Do a dump and make it look like a currentdump
 7674:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
 7675:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
 7676:        my %hash = @tmp;
 7677:        @tmp=();
 7678:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
 7679:    } else {
 7680:        my @pairs=split(/\&/,$rep);
 7681:        foreach my $pair (@pairs) {
 7682:            my ($key,$value)=split(/=/,$pair,2);
 7683:            my ($symb,$param) = split(/:/,$key);
 7684:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
 7685:                                                         &thaw_unescape($value);
 7686:        }
 7687:    }
 7688:    return %returnhash;
 7689: }
 7690: 
 7691: sub convert_dump_to_currentdump{
 7692:     my %hash = %{shift()};
 7693:     my %returnhash;
 7694:     # Code ripped from lond, essentially.  The only difference
 7695:     # here is the unescaping done by lonnet::dump().  Conceivably
 7696:     # we might run in to problems with parameter names =~ /^v\./
 7697:     while (my ($key,$value) = each(%hash)) {
 7698:         my ($v,$symb,$param) = split(/:/,$key);
 7699: 	$symb  = &unescape($symb);
 7700: 	$param = &unescape($param);
 7701:         next if ($v eq 'version' || $symb eq 'keys');
 7702:         next if (exists($returnhash{$symb}) &&
 7703:                  exists($returnhash{$symb}->{$param}) &&
 7704:                  $returnhash{$symb}->{'v.'.$param} > $v);
 7705:         $returnhash{$symb}->{$param}=$value;
 7706:         $returnhash{$symb}->{'v.'.$param}=$v;
 7707:     }
 7708:     #
 7709:     # Remove all of the keys in the hashes which keep track of
 7710:     # the version of the parameter.
 7711:     while (my ($symb,$param_hash) = each(%returnhash)) {
 7712:         # use a foreach because we are going to delete from the hash.
 7713:         foreach my $key (keys(%$param_hash)) {
 7714:             delete($param_hash->{$key}) if ($key =~ /^v\./);
 7715:         }
 7716:     }
 7717:     return \%returnhash;
 7718: }
 7719: 
 7720: # ------------------------------------------------------ critical inc interface
 7721: 
 7722: sub cinc {
 7723:     return &inc(@_,'critical');
 7724: }
 7725: 
 7726: # --------------------------------------------------------------- inc interface
 7727: 
 7728: sub inc {
 7729:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
 7730:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 7731:     if (!$uname) { $uname=$env{'user.name'}; }
 7732:     my $uhome=&homeserver($uname,$udomain);
 7733:     my $items='';
 7734:     if (! ref($store)) {
 7735:         # got a single value, so use that instead
 7736:         $items = &escape($store).'=&';
 7737:     } elsif (ref($store) eq 'SCALAR') {
 7738:         $items = &escape($$store).'=&';        
 7739:     } elsif (ref($store) eq 'ARRAY') {
 7740:         $items = join('=&',map {&escape($_);} @{$store});
 7741:     } elsif (ref($store) eq 'HASH') {
 7742:         while (my($key,$value) = each(%{$store})) {
 7743:             $items.= &escape($key).'='.&escape($value).'&';
 7744:         }
 7745:     }
 7746:     $items=~s/\&$//;
 7747:     if ($critical) {
 7748: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
 7749:     } else {
 7750: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
 7751:     }
 7752: }
 7753: 
 7754: # --------------------------------------------------------------- put interface
 7755: 
 7756: sub put {
 7757:    my ($namespace,$storehash,$udomain,$uname,$encrypt)=@_;
 7758:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 7759:    if (!$uname) { $uname=$env{'user.name'}; }
 7760:    my $uhome=&homeserver($uname,$udomain);
 7761:    my $items='';
 7762:    foreach my $item (keys(%$storehash)) {
 7763:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 7764:    }
 7765:    $items=~s/\&$//;
 7766:    if ($encrypt) {
 7767:        return &reply("encrypt:put:$udomain:$uname:$namespace:$items",$uhome);
 7768:    } else {
 7769:        return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 7770:    }
 7771: }
 7772: 
 7773: # ------------------------------------------------------------ newput interface
 7774: 
 7775: sub newput {
 7776:    my ($namespace,$storehash,$udomain,$uname)=@_;
 7777:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 7778:    if (!$uname) { $uname=$env{'user.name'}; }
 7779:    my $uhome=&homeserver($uname,$udomain);
 7780:    my $items='';
 7781:    foreach my $key (keys(%$storehash)) {
 7782:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 7783:    }
 7784:    $items=~s/\&$//;
 7785:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
 7786: }
 7787: 
 7788: # ---------------------------------------------------------  putstore interface
 7789: 
 7790: sub putstore {
 7791:    my ($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog)=@_;
 7792:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 7793:    if (!$uname) { $uname=$env{'user.name'}; }
 7794:    my $uhome=&homeserver($uname,$udomain);
 7795:    my $items='';
 7796:    foreach my $key (keys(%$storehash)) {
 7797:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
 7798:    }
 7799:    $items=~s/\&$//;
 7800:    my $esc_symb=&escape($symb);
 7801:    my $esc_v=&escape($version);
 7802:    my $reply =
 7803:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
 7804: 	      $uhome);
 7805:    if (($tolog) && ($reply eq 'ok')) {
 7806:        my $namevalue='';
 7807:        foreach my $key (keys(%{$storehash})) {
 7808:            $namevalue.=&escape($key).'='.&freeze_escape($storehash->{$key}).'&';
 7809:        }
 7810:        my $ip = &get_requestor_ip();
 7811:        $namevalue .= 'ip='.&escape($ip).
 7812:                      '&host='.&escape($perlvar{'lonHostID'}).
 7813:                      '&version='.$esc_v.
 7814:                      '&by='.&escape($env{'user.name'}.':'.$env{'user.domain'});
 7815:        &courselog($symb.':'.$uname.':'.$udomain.':PUTSTORE:'.$namevalue);
 7816:    }
 7817:    if ($reply eq 'unknown_cmd') {
 7818:        # gfall back to way things use to be done
 7819:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
 7820: 			    $uname);
 7821:    }
 7822:    return $reply;
 7823: }
 7824: 
 7825: sub old_putstore {
 7826:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
 7827:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 7828:     if (!$uname) { $uname=$env{'user.name'}; }
 7829:     my $uhome=&homeserver($uname,$udomain);
 7830:     my %newstorehash;
 7831:     foreach my $item (keys(%$storehash)) {
 7832: 	my $key = $version.':'.&escape($symb).':'.$item;
 7833: 	$newstorehash{$key} = $storehash->{$item};
 7834:     }
 7835:     my $items='';
 7836:     my %allitems = ();
 7837:     foreach my $item (keys(%newstorehash)) {
 7838: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
 7839: 	    my $key = $1.':keys:'.$2;
 7840: 	    $allitems{$key} .= $3.':';
 7841: 	}
 7842: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
 7843:     }
 7844:     foreach my $item (keys(%allitems)) {
 7845: 	$allitems{$item} =~ s/\:$//;
 7846: 	$items.= $item.'='.$allitems{$item}.'&';
 7847:     }
 7848:     $items=~s/\&$//;
 7849:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 7850: }
 7851: 
 7852: # ------------------------------------------------------ critical put interface
 7853: 
 7854: sub cput {
 7855:    my ($namespace,$storehash,$udomain,$uname)=@_;
 7856:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 7857:    if (!$uname) { $uname=$env{'user.name'}; }
 7858:    my $uhome=&homeserver($uname,$udomain);
 7859:    my $items='';
 7860:    foreach my $item (keys(%$storehash)) {
 7861:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 7862:    }
 7863:    $items=~s/\&$//;
 7864:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
 7865: }
 7866: 
 7867: # -------------------------------------------------------------- eget interface
 7868: 
 7869: sub eget {
 7870:    my ($namespace,$storearr,$udomain,$uname)=@_;
 7871:    my $items='';
 7872:    foreach my $item (@$storearr) {
 7873:        $items.=&escape($item).'&';
 7874:    }
 7875:    $items=~s/\&$//;
 7876:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 7877:    if (!$uname) { $uname=$env{'user.name'}; }
 7878:    my $uhome=&homeserver($uname,$udomain);
 7879:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
 7880:    my @pairs=split(/\&/,$rep);
 7881:    my %returnhash=();
 7882:    my $i=0;
 7883:    foreach my $item (@$storearr) {
 7884:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 7885:       $i++;
 7886:    }
 7887:    return %returnhash;
 7888: }
 7889: 
 7890: # ------------------------------------------------------------ tmpput interface
 7891: sub tmpput {
 7892:     my ($storehash,$server,$context)=@_;
 7893:     my $items='';
 7894:     foreach my $item (keys(%$storehash)) {
 7895: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 7896:     }
 7897:     $items=~s/\&$//;
 7898:     if (defined($context)) {
 7899:         $items .= ':'.&escape($context);
 7900:     }
 7901:     return &reply("tmpput:$items",$server);
 7902: }
 7903: 
 7904: # ------------------------------------------------------------ tmpget interface
 7905: sub tmpget {
 7906:     my ($token,$server)=@_;
 7907:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 7908:     my $rep=&reply("tmpget:$token",$server);
 7909:     my %returnhash;
 7910:     if ($rep =~ /^(con_lost|error|no_such_host)/i) {
 7911:         return %returnhash;
 7912:     }
 7913:     foreach my $item (split(/\&/,$rep)) {
 7914: 	my ($key,$value)=split(/=/,$item);
 7915: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
 7916:     }
 7917:     return %returnhash;
 7918: }
 7919: 
 7920: # ------------------------------------------------------------ tmpdel interface
 7921: sub tmpdel {
 7922:     my ($token,$server)=@_;
 7923:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 7924:     return &reply("tmpdel:$token",$server);
 7925: }
 7926: 
 7927: # ------------------------------------------------------------ get_timebased_id 
 7928: 
 7929: sub get_timebased_id {
 7930:     my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
 7931:         $maxtries) = @_;
 7932:     my ($newid,$error,$dellock);
 7933:     unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {  
 7934:         return ('','ok','invalid call to get suffix');
 7935:     }
 7936: 
 7937: # set defaults for any optional args for which values were not supplied
 7938:     if ($who eq '') {
 7939:         $who = $env{'user.name'}.':'.$env{'user.domain'};
 7940:     }
 7941:     if (!$locktries) {
 7942:         $locktries = 3;
 7943:     }
 7944:     if (!$maxtries) {
 7945:         $maxtries = 10;
 7946:     }
 7947:     
 7948:     if (($cdom eq '') || ($cnum eq '')) {
 7949:         if ($env{'request.course.id'}) {
 7950:             $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 7951:             $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 7952:         }
 7953:         if (($cdom eq '') || ($cnum eq '')) {
 7954:             return ('','ok','call to get suffix not in course context');
 7955:         }
 7956:     }
 7957: 
 7958: # construct locking item
 7959:     my $lockhash = {
 7960:                       $prefix."\0".'locked_'.$keyid => $who,
 7961:                    };
 7962:     my $tries = 0;
 7963: 
 7964: # attempt to get lock on nohist_$namespace file
 7965:     my $gotlock = &newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
 7966:     while (($gotlock ne 'ok') && $tries <$locktries) {
 7967:         $tries ++;
 7968:         sleep 1;
 7969:         $gotlock = &newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
 7970:     }
 7971: 
 7972: # attempt to get unique identifier, based on current timestamp
 7973:     if ($gotlock eq 'ok') {
 7974:         my %inuse = &dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
 7975:         my $id = time;
 7976:         $newid = $id;
 7977:         if ($idtype eq 'addcode') {
 7978:             $newid .= &sixnum_code();
 7979:         }
 7980:         my $idtries = 0;
 7981:         while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
 7982:             if ($idtype eq 'concat') {
 7983:                 $newid = $id.$idtries;
 7984:             } elsif ($idtype eq 'addcode') {
 7985:                 $newid = $newid.&sixnum_code();
 7986:             } else {
 7987:                 $newid ++;
 7988:             }
 7989:             $idtries ++;
 7990:         }
 7991:         if (!exists($inuse{$prefix."\0".$newid})) {
 7992:             my %new_item =  (
 7993:                               $prefix."\0".$newid => $who,
 7994:                             );
 7995:             my $putresult = &put('nohist_'.$namespace,\%new_item,
 7996:                                                  $cdom,$cnum);
 7997:             if ($putresult ne 'ok') {
 7998:                 undef($newid);
 7999:                 $error = 'error saving new item: '.$putresult;
 8000:             }
 8001:         } else {
 8002:              undef($newid);
 8003:              $error = ('error: no unique suffix available for the new item ');
 8004:         }
 8005: #  remove lock
 8006:         my @del_lock = ($prefix."\0".'locked_'.$keyid);
 8007:         $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
 8008:     } else {
 8009:         $error = "error: could not obtain lockfile\n";
 8010:         $dellock = 'ok';
 8011:         if (($prefix eq 'paste') && ($namespace eq 'courseeditor') && ($keyid eq 'num')) {
 8012:             $dellock = 'nolock';
 8013:         }
 8014:     }
 8015:     return ($newid,$dellock,$error);
 8016: }
 8017: 
 8018: sub sixnum_code {
 8019:     my $code;
 8020:     for (0..6) {
 8021:         $code .= int( rand(9) );
 8022:     }
 8023:     return $code;
 8024: }
 8025: 
 8026: # -------------------------------------------------- portfolio access checking
 8027: 
 8028: sub portfolio_access {
 8029:     my ($requrl,$clientip) = @_;
 8030:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
 8031:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group,$clientip);
 8032:     if ($result) {
 8033:         my %setters;
 8034:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 8035:             my ($startblock,$endblock,$triggerblock,$by_ip,$blockdom) =
 8036:                 &Apache::loncommon::blockcheck(\%setters,'port',$clientip,$unum,$udom);
 8037:             if (($startblock && $endblock) || ($by_ip)) {
 8038:                 return 'B';
 8039:             }
 8040:         } else {
 8041:             my ($startblock,$endblock,$triggerblock,$by_ip,$blockdom) =
 8042:                 &Apache::loncommon::blockcheck(\%setters,'port',$clientip);
 8043:             if (($startblock && $endblock) || ($by_ip)) {
 8044:                 return 'B';
 8045:             }
 8046:         }
 8047:     }
 8048:     if ($result eq 'ok') {
 8049:        return 'F';
 8050:     } elsif ($result =~ /^[^:]+:guest_/) {
 8051:        return 'A';
 8052:     }
 8053:     return '';
 8054: }
 8055: 
 8056: sub get_portfolio_access {
 8057:     my ($udom,$unum,$file_name,$group,$clientip,$access_hash,$portaccessref) = @_;
 8058: 
 8059:     if (!ref($access_hash)) {
 8060: 	my $current_perms = &get_portfile_permissions($udom,$unum);
 8061: 	my %access_controls = &get_access_controls($current_perms,$group,
 8062: 						   $file_name);
 8063: 	$access_hash = $access_controls{$file_name};
 8064:     }
 8065: 
 8066:     my $portaccess;
 8067:     if (ref($portaccess) eq 'SCALAR') {
 8068:         $portaccess = $$portaccessref;
 8069:     } else {
 8070:         $portaccess = &usertools_access($unum,$udom,'portaccess',undef,'tools');
 8071:     }
 8072: 
 8073:     my ($public,$guest,@domains,@users,@courses,@groups,@ips,@userips);
 8074:     my $now = time;
 8075:     if (ref($access_hash) eq 'HASH') {
 8076:         foreach my $key (keys(%{$access_hash})) {
 8077:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
 8078:             next if (($scope ne 'ip') && ($portaccess == 0));
 8079:             if ($start > $now) {
 8080:                 next;
 8081:             }
 8082:             if ($end && $end<$now) {
 8083:                 next;
 8084:             }
 8085:             if ($scope eq 'public') {
 8086:                 $public = $key;
 8087:                 last;
 8088:             } elsif ($scope eq 'guest') {
 8089:                 $guest = $key;
 8090:             } elsif ($scope eq 'domains') {
 8091:                 push(@domains,$key);
 8092:             } elsif ($scope eq 'users') {
 8093:                 push(@users,$key);
 8094:             } elsif ($scope eq 'course') {
 8095:                 push(@courses,$key);
 8096:             } elsif ($scope eq 'group') {
 8097:                 push(@groups,$key);
 8098:             } elsif ($scope eq 'ip') {
 8099:                 push(@ips,$key);
 8100:             } elsif ($scope eq 'userip') {
 8101:                 push(@userips,$key);
 8102:             }
 8103:         }
 8104:         if ($public) {
 8105:             return 'ok';
 8106:         } elsif (@ips > 0) {
 8107:             my $allowed;
 8108:             foreach my $ipkey (@ips) {
 8109:                 if (ref($access_hash->{$ipkey}{'ip'}) eq 'ARRAY') {
 8110:                     if (&Apache::loncommon::check_ip_acc(join(',',@{$access_hash->{$ipkey}{'ip'}}),$clientip)) {
 8111:                         $allowed = 1;
 8112:                         last; 
 8113:                     }
 8114:                 }
 8115:             }
 8116:             if ($allowed) {
 8117:                 return 'ok';
 8118:             }
 8119:         } elsif (@userips > 0) {
 8120:             my $allowed;
 8121:             foreach my $useripkey (@userips) {
 8122:                 if (ref($access_hash->{$useripkey}{'ip'}) eq 'ARRAY') {
 8123:                     if (&Apache::loncommon::check_ip_acc(join(',',@{$access_hash->{$useripkey}{'ip'}}),$clientip)) {
 8124:                         $allowed = 1;
 8125:                         last;
 8126:                     }
 8127:                 }
 8128:             }
 8129:             if ($allowed) {
 8130:                 return 'ok';
 8131:             }
 8132:         }
 8133:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 8134:             if ($guest) {
 8135:                 return $guest;
 8136:             }
 8137:         } else {
 8138:             if (@domains > 0) {
 8139:                 foreach my $domkey (@domains) {
 8140:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
 8141:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
 8142:                             return 'ok';
 8143:                         }
 8144:                     }
 8145:                 }
 8146:             }
 8147:             if (@users > 0) {
 8148:                 foreach my $userkey (@users) {
 8149:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
 8150:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
 8151:                             if (ref($item) eq 'HASH') {
 8152:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
 8153:                                     ($item->{'udom'} eq $env{'user.domain'})) {
 8154:                                     return 'ok';
 8155:                                 }
 8156:                             }
 8157:                         }
 8158:                     } 
 8159:                 }
 8160:             }
 8161:             my %roleshash;
 8162:             my @courses_and_groups = @courses;
 8163:             push(@courses_and_groups,@groups); 
 8164:             if (@courses_and_groups > 0) {
 8165:                 my (%allgroups,%allroles); 
 8166:                 my ($start,$end,$role,$sec,$group);
 8167:                 foreach my $envkey (%env) {
 8168:                     if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
 8169:                         my $cid = $2.'_'.$3; 
 8170:                         if ($1 eq 'gr') {
 8171:                             $group = $4;
 8172:                             $allgroups{$cid}{$group} = $env{$envkey};
 8173:                         } else {
 8174:                             if ($4 eq '') {
 8175:                                 $sec = 'none';
 8176:                             } else {
 8177:                                 $sec = $4;
 8178:                             }
 8179:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
 8180:                         }
 8181:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
 8182:                         my $cid = $2.'_'.$3;
 8183:                         if ($4 eq '') {
 8184:                             $sec = 'none';
 8185:                         } else {
 8186:                             $sec = $4;
 8187:                         }
 8188:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
 8189:                     }
 8190:                 }
 8191:                 if (keys(%allroles) == 0) {
 8192:                     return;
 8193:                 }
 8194:                 foreach my $key (@courses_and_groups) {
 8195:                     my %content = %{$$access_hash{$key}};
 8196:                     my $cnum = $content{'number'};
 8197:                     my $cdom = $content{'domain'};
 8198:                     my $cid = $cdom.'_'.$cnum;
 8199:                     if (!exists($allroles{$cid})) {
 8200:                         next;
 8201:                     }    
 8202:                     foreach my $role_id (keys(%{$content{'roles'}})) {
 8203:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
 8204:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
 8205:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
 8206:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
 8207:                         foreach my $role (keys(%{$allroles{$cid}})) {
 8208:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
 8209:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
 8210:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
 8211:                                         if (grep/^all$/,@sections) {
 8212:                                             return 'ok';
 8213:                                         } else {
 8214:                                             if (grep/^$sec$/,@sections) {
 8215:                                                 return 'ok';
 8216:                                             }
 8217:                                         }
 8218:                                     }
 8219:                                 }
 8220:                                 if (keys(%{$allgroups{$cid}}) == 0) {
 8221:                                     if (grep/^none$/,@groups) {
 8222:                                         return 'ok';
 8223:                                     }
 8224:                                 } else {
 8225:                                     if (grep/^all$/,@groups) {
 8226:                                         return 'ok';
 8227:                                     } 
 8228:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
 8229:                                         if (grep/^$group$/,@groups) {
 8230:                                             return 'ok';
 8231:                                         }
 8232:                                     }
 8233:                                 } 
 8234:                             }
 8235:                         }
 8236:                     }
 8237:                 }
 8238:             }
 8239:             if ($guest) {
 8240:                 return $guest;
 8241:             }
 8242:         }
 8243:     }
 8244:     return;
 8245: }
 8246: 
 8247: sub course_group_datechecker {
 8248:     my ($dates,$now,$status) = @_;
 8249:     my ($start,$end) = split(/\./,$dates);
 8250:     if (!$start && !$end) {
 8251:         return 'ok';
 8252:     }
 8253:     if (grep/^active$/,@{$status}) {
 8254:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
 8255:             return 'ok';
 8256:         }
 8257:     }
 8258:     if (grep/^previous$/,@{$status}) {
 8259:         if ($end > $now ) {
 8260:             return 'ok';
 8261:         }
 8262:     }
 8263:     if (grep/^future$/,@{$status}) {
 8264:         if ($start > $now) {
 8265:             return 'ok';
 8266:         }
 8267:     }
 8268:     return; 
 8269: }
 8270: 
 8271: sub parse_portfolio_url {
 8272:     my ($url) = @_;
 8273: 
 8274:     my ($type,$udom,$unum,$group,$file_name);
 8275:     
 8276:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
 8277: 	$type = 1;
 8278:         $udom = $1;
 8279:         $unum = $2;
 8280:         $file_name = $3;
 8281:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
 8282: 	$type = 2;
 8283:         $udom = $1;
 8284:         $unum = $2;
 8285:         $group = $3;
 8286:         $file_name = $3.'/'.$4;
 8287:     }
 8288:     if (wantarray) {
 8289: 	return ($type,$udom,$unum,$file_name,$group);
 8290:     }
 8291:     return $type;
 8292: }
 8293: 
 8294: sub is_portfolio_url {
 8295:     my ($url) = @_;
 8296:     return scalar(&parse_portfolio_url($url));
 8297: }
 8298: 
 8299: sub is_portfolio_file {
 8300:     my ($file) = @_;
 8301:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
 8302:         return 1;
 8303:     }
 8304:     return;
 8305: }
 8306: 
 8307: sub is_coursetool_logo {
 8308:     my ($uri) = @_;
 8309:     if ($env{'request.course.id'}) {
 8310:         my $courseurl = &courseid_to_courseurl($env{'request.course.id'});
 8311:         if ($uri =~ m{^/*uploaded\Q$courseurl\E/toollogo/\d+/[^/]+$}) {
 8312:             return 1;
 8313:         }
 8314:     }
 8315:     return;
 8316: }
 8317: 
 8318: sub usertools_access {
 8319:     my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
 8320:     my ($access,%tools);
 8321:     if ($context eq '') {
 8322:         $context = 'tools';
 8323:     }
 8324:     if ($context eq 'requestcourses') {
 8325:         %tools = (
 8326:                       official   => 1,
 8327:                       unofficial => 1,
 8328:                       community  => 1,
 8329:                       textbook   => 1,
 8330:                       placement  => 1,
 8331:                       lti        => 1,
 8332:                  );
 8333:     } elsif ($context eq 'requestauthor') {
 8334:         %tools = (
 8335:                       requestauthor => 1,
 8336:                  );
 8337:     } elsif ($context eq 'authordefaults') {
 8338:         %tools = (
 8339:                       webdav    => 1,
 8340:                  );
 8341:     } else {
 8342:         %tools = (
 8343:                       aboutme   => 1,
 8344:                       blog      => 1,
 8345:                       webdav    => 1,
 8346:                       portfolio => 1,
 8347:                       portaccess => 1,
 8348:                       timezone  => 1,
 8349:                  );
 8350:     }
 8351:     return if (!defined($tools{$tool}));
 8352: 
 8353:     if (($udom eq '') || ($uname eq '')) {
 8354:         $udom = $env{'user.domain'};
 8355:         $uname = $env{'user.name'};
 8356:     }
 8357: 
 8358:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 8359:         if ($action ne 'reload') {
 8360:             if ($context eq 'requestcourses') {
 8361:                 return $env{'environment.canrequest.'.$tool};
 8362:             } elsif ($context eq 'requestauthor') {
 8363:                 return $env{'environment.canrequest.author'};
 8364:             } elsif ($context eq 'authordefaults') {
 8365:                 if ($tool eq 'webdav') {
 8366:                     return $env{'environment.availabletools.'.$tool};
 8367:                 }
 8368:             } else {
 8369:                 return $env{'environment.availabletools.'.$tool};
 8370:             }
 8371:         }
 8372:     }
 8373: 
 8374:     my ($toolstatus,$inststatus,$envkey);
 8375:     if ($context eq 'requestauthor') {
 8376:         $envkey = $context;
 8377:     } elsif ($context eq 'authordefaults') {
 8378:         if ($tool eq 'webdav') {
 8379:             $envkey = 'tools.'.$tool;
 8380:         }
 8381:     } else {
 8382:         $envkey = $context.'.'.$tool;
 8383:     }
 8384: 
 8385:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
 8386:          ($action ne 'reload')) {
 8387:         $toolstatus = $env{'environment.'.$envkey};
 8388:         $inststatus = $env{'environment.inststatus'};
 8389:     } else {
 8390:         if (ref($userenvref) eq 'HASH') {
 8391:             $toolstatus = $userenvref->{$envkey};
 8392:             $inststatus = $userenvref->{'inststatus'};
 8393:         } else {
 8394:             my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
 8395:             $toolstatus = $userenv{$envkey};
 8396:             $inststatus = $userenv{'inststatus'};
 8397:         }
 8398:     }
 8399: 
 8400:     if ($toolstatus ne '') {
 8401:         if ($toolstatus) {
 8402:             $access = 1;
 8403:         } else {
 8404:             $access = 0;
 8405:         }
 8406:         return $access;
 8407:     }
 8408: 
 8409:     my ($is_adv,%domdef);
 8410:     if (ref($is_advref) eq 'HASH') {
 8411:         $is_adv = $is_advref->{'is_adv'};
 8412:     } else {
 8413:         $is_adv = &is_advanced_user($udom,$uname);
 8414:     }
 8415:     if (ref($domdefref) eq 'HASH') {
 8416:         %domdef = %{$domdefref};
 8417:     } else {
 8418:         %domdef = &get_domain_defaults($udom);
 8419:     }
 8420:     if (ref($domdef{$tool}) eq 'HASH') {
 8421:         if ($is_adv) {
 8422:             if ($domdef{$tool}{'_LC_adv'} ne '') {
 8423:                 if ($domdef{$tool}{'_LC_adv'}) { 
 8424:                     $access = 1;
 8425:                 } else {
 8426:                     $access = 0;
 8427:                 }
 8428:                 return $access;
 8429:             }
 8430:         }
 8431:         if ($inststatus ne '') {
 8432:             my ($hasaccess,$hasnoaccess);
 8433:             foreach my $affiliation (split(/:/,$inststatus)) {
 8434:                 if ($domdef{$tool}{$affiliation} ne '') { 
 8435:                     if ($domdef{$tool}{$affiliation}) {
 8436:                         $hasaccess = 1;
 8437:                     } else {
 8438:                         $hasnoaccess = 1;
 8439:                     }
 8440:                 }
 8441:             }
 8442:             if ($hasaccess || $hasnoaccess) {
 8443:                 if ($hasaccess) {
 8444:                     $access = 1;
 8445:                 } elsif ($hasnoaccess) {
 8446:                     $access = 0; 
 8447:                 }
 8448:                 return $access;
 8449:             }
 8450:         } else {
 8451:             if ($domdef{$tool}{'default'} ne '') {
 8452:                 if ($domdef{$tool}{'default'}) {
 8453:                     $access = 1;
 8454:                 } elsif ($domdef{$tool}{'default'} == 0) {
 8455:                     $access = 0;
 8456:                 }
 8457:                 return $access;
 8458:             }
 8459:         }
 8460:     } else {
 8461:         if (($context eq 'tools') && ($tool ne 'webdav')) {
 8462:             $access = 1;
 8463:         } else {
 8464:             $access = 0;
 8465:         }
 8466:         return $access;
 8467:     }
 8468: }
 8469: 
 8470: sub is_course_owner {
 8471:     my ($cdom,$cnum,$udom,$uname) = @_;
 8472:     if (($udom eq '') || ($uname eq '')) {
 8473:         $udom = $env{'user.domain'};
 8474:         $uname = $env{'user.name'};
 8475:     }
 8476:     unless (($udom eq '') || ($uname eq '')) {
 8477:         if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
 8478:             if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
 8479:                 return 1;
 8480:             } else {
 8481:                 my %courseinfo = &coursedescription($cdom.'/'.$cnum);
 8482:                 if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
 8483:                     return 1;
 8484:                 }
 8485:             }
 8486:         }
 8487:     }
 8488:     return;
 8489: }
 8490: 
 8491: sub is_advanced_user {
 8492:     my ($udom,$uname,$nocache) = @_;
 8493:     my ($is_adv,$is_author,$use_cache,$hashid);
 8494:     if ($udom ne '' && $uname ne '') {
 8495:         if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 8496:             if (wantarray) {
 8497:                 return ($env{'user.adv'},$env{'user.author'});
 8498:             } else {
 8499:                 return $env{'user.adv'};
 8500:             }
 8501:         } elsif (!$nocache) {
 8502:             $use_cache = 1;
 8503:             $hashid = "$udom:$uname";  
 8504:             my ($info,$cached)=&is_cached_new('isadvau',$hashid);
 8505:             if ($cached) {
 8506:                 ($is_adv,$is_author) = split(/:/,$info);
 8507:                 if (wantarray) {
 8508:                     return ($is_adv,$is_author);
 8509:                 }
 8510:                 return $is_adv; 
 8511:             }
 8512:         }
 8513:     }
 8514:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
 8515:     my %allroles;
 8516:     foreach my $role (keys(%roleshash)) {
 8517:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
 8518:         my $area = '/'.$tdomain.'/'.$trest;
 8519:         if ($sec ne '') {
 8520:             $area .= '/'.$sec;
 8521:         }
 8522:         if (($area ne '') && ($trole ne '')) {
 8523:             my $spec=$trole.'.'.$area;
 8524:             if ($trole =~ /^cr\//) {
 8525:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
 8526:             } elsif ($trole ne 'gr') {
 8527:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
 8528:             }
 8529:             if ($trole eq 'au') {
 8530:                 $is_author = 1;
 8531:             }
 8532:         }
 8533:     }
 8534:     foreach my $role (keys(%allroles)) {
 8535:         last if ($is_adv);
 8536:         foreach my $item (split(/:/,$allroles{$role})) {
 8537:             if ($item ne '') {
 8538:                 my ($privilege,$restrictions)=split(/&/,$item);
 8539:                 if ($privilege eq 'adv') {
 8540:                     $is_adv = 1;
 8541:                     last;
 8542:                 }
 8543:             }
 8544:         }
 8545:     }
 8546:     if ($use_cache) {
 8547:         my $cachetime = 600;
 8548:         &do_cache_new('isadvau',$hashid,$is_adv.':'.$is_author,$cachetime);
 8549:     }
 8550:     if (wantarray) {
 8551:         return ($is_adv,$is_author);
 8552:     }
 8553:     return $is_adv;
 8554: }
 8555: 
 8556: sub check_can_request {
 8557:     my ($dom,$can_request,$request_domains,$uname,$udom) = @_;
 8558:     my $canreq = 0;
 8559:     if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
 8560:         $uname = $env{'user.name'};
 8561:         $udom = $env{'user.domain'};
 8562:     }
 8563:     my ($types,$typename) = &Apache::loncommon::course_types();
 8564:     my @options = ('approval','validate','autolimit');
 8565:     my $optregex = join('|',@options);
 8566:     if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
 8567:         my %willtrust;
 8568:         foreach my $type (@{$types}) {
 8569:             if (&usertools_access($uname,$udom,$type,undef,
 8570:                                   'requestcourses')) {
 8571:                 $canreq ++;
 8572:                 if (ref($request_domains) eq 'HASH') {
 8573:                     push(@{$request_domains->{$type}},$udom);
 8574:                 }
 8575:                 if ($dom eq $udom) {
 8576:                     $can_request->{$type} = 1;
 8577:                 }
 8578:             }
 8579:             if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '') &&
 8580:                 ($env{'environment.reqcrsotherdom.'.$type} ne '')) {
 8581:                 my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
 8582:                 if (@curr > 0) {
 8583:                     foreach my $item (@curr) {
 8584:                         if (ref($request_domains) eq 'HASH') {
 8585:                             my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
 8586:                             if ($otherdom ne '') {
 8587:                                 unless (exists($willtrust{$otherdom})) {
 8588:                                     $willtrust{$otherdom} = &will_trust('reqcrs',$env{'user.domain'},$otherdom);
 8589:                                 }
 8590:                                 if ($willtrust{$otherdom}) {
 8591:                                     if (ref($request_domains->{$type}) eq 'ARRAY') {
 8592:                                         unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
 8593:                                             push(@{$request_domains->{$type}},$otherdom);
 8594:                                         }
 8595:                                     } else {
 8596:                                         push(@{$request_domains->{$type}},$otherdom);
 8597:                                     }
 8598:                                 }
 8599:                             }
 8600:                         }
 8601:                     }
 8602:                     unless ($dom eq $env{'user.domain'}) {
 8603:                         $canreq ++;
 8604:                         if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
 8605:                             $can_request->{$type} = 1;
 8606:                         }
 8607:                     }
 8608:                 }
 8609:             }
 8610:         }
 8611:     }
 8612:     return $canreq;
 8613: }
 8614: 
 8615: # ---------------------------------------------- Custom access rule evaluation
 8616: 
 8617: sub customaccess {
 8618:     my ($priv,$uri)=@_;
 8619:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
 8620:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
 8621:     $udom = &LONCAPA::clean_domain($udom);
 8622:     $ucrs = &LONCAPA::clean_username($ucrs);
 8623:     my $access=0;
 8624:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
 8625: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
 8626: 	if ($type eq 'user') {
 8627: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
 8628: 		my ($tdom,$tuname)=split(m{/},$scope);
 8629: 		if ($tdom) {
 8630: 		    if ($tdom ne $env{'user.domain'}) { next; }
 8631: 		}
 8632: 		if ($tuname) {
 8633: 		    if ($tuname ne $env{'user.name'}) { next; }
 8634: 		}
 8635: 		$access=($effect eq 'allow');
 8636: 		last;
 8637: 	    }
 8638: 	} else {
 8639: 	    if ($role) {
 8640: 		if ($role ne $urole) { next; }
 8641: 	    }
 8642: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
 8643: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
 8644: 		if ($tdom) {
 8645: 		    if ($tdom ne $udom) { next; }
 8646: 		}
 8647: 		if ($tcrs) {
 8648: 		    if ($tcrs ne $ucrs) { next; }
 8649: 		}
 8650: 		if ($tsec) {
 8651: 		    if ($tsec ne $usec) { next; }
 8652: 		}
 8653: 		$access=($effect eq 'allow');
 8654: 		last;
 8655: 	    }
 8656: 	    if ($realm eq '' && $role eq '') {
 8657: 		$access=($effect eq 'allow');
 8658: 	    }
 8659: 	}
 8660:     }
 8661:     return $access;
 8662: }
 8663: 
 8664: # ------------------------------------------------- Check for a user privilege
 8665: 
 8666: sub allowed {
 8667:     my ($priv,$uri,$symb,$role,$clientip,$noblockcheck,$ignorecache,$nodeeplinkcheck,$nodeeplinkout)=@_;
 8668:     my $ver_orguri=$uri;
 8669:     $uri=&deversion($uri);
 8670:     my $orguri=$uri;
 8671:     $uri=&declutter($uri);
 8672: 
 8673:     if ($priv eq 'evb') {
 8674: # Evade communication block restrictions for specified role in a course or domain
 8675:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
 8676:             return $1;
 8677:         } else {
 8678:             return;
 8679:         }
 8680:     }
 8681: 
 8682:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
 8683: # Free bre access to adm and meta resources
 8684:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard|viewclasslist|aboutme|ext\.tool)$})) 
 8685: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
 8686: 	&& ($priv eq 'bre')) {
 8687: 	return 'F';
 8688:     }
 8689: 
 8690: # Free bre access to user's own portfolio contents
 8691:     my ($space,$domain,$name,@dir)=split('/',$uri);
 8692:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
 8693: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
 8694:         my %setters;
 8695:         my ($startblock,$endblock,$triggerblock,$by_ip,$blockdom) = 
 8696:             &Apache::loncommon::blockcheck(\%setters,'port',$clientip);
 8697:         if (($startblock && $endblock) || ($by_ip)) {
 8698:             return 'B';
 8699:         } else {
 8700:             return 'F';
 8701:         }
 8702:     }
 8703: 
 8704: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
 8705:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
 8706:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
 8707:         if (exists($env{'request.course.id'})) {
 8708:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 8709:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 8710:             if (($domain eq $cdom) && ($name eq $cnum)) {
 8711:                 my $courseprivid=$env{'request.course.id'};
 8712:                 $courseprivid=~s/\_/\//;
 8713:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
 8714:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
 8715:                     return $1; 
 8716:                 } else {
 8717:                     if ($env{'request.course.sec'}) {
 8718:                         $courseprivid.='/'.$env{'request.course.sec'};
 8719:                     }
 8720:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
 8721:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
 8722:                         return $2;
 8723:                     }
 8724:                 }
 8725:             }
 8726:         }
 8727:     }
 8728: 
 8729: # Free bre to public access
 8730: 
 8731:     if ($priv eq 'bre') {
 8732:         my $copyright;
 8733:         unless ($uri =~ /ext\.tool/) {
 8734:             $copyright=&metadata($uri,'copyright');
 8735:         }
 8736: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
 8737:            return 'F'; 
 8738:         }
 8739:         if ($copyright eq 'priv') {
 8740:             $uri=~/([^\/]+)\/([^\/]+)\//;
 8741: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
 8742: 		return '';
 8743:             }
 8744:         }
 8745:         if ($copyright eq 'domain') {
 8746:             $uri=~/([^\/]+)\/([^\/]+)\//;
 8747: 	    unless (($env{'user.domain'} eq $1) ||
 8748:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
 8749: 		return '';
 8750:             }
 8751:         }
 8752:         if ($env{'request.role'}=~ /li\.\//) {
 8753:             # Library role, so allow browsing of resources in this domain.
 8754:             return 'F';
 8755:         }
 8756:         if ($copyright eq 'custom') {
 8757: 	    unless (&customaccess($priv,$uri)) { return ''; }
 8758:         }
 8759:     }
 8760:     # Domain coordinator is trying to create a course
 8761:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
 8762:         # uri is the requested domain in this case.
 8763:         # comparison to 'request.role.domain' shows if the user has selected
 8764:         # a role of dc for the domain in question.
 8765:         return 'F' if ($uri eq $env{'request.role.domain'});
 8766:     }
 8767: 
 8768:     my $thisallowed='';
 8769:     my $statecond=0;
 8770:     my $courseprivid='';
 8771: 
 8772:     my $ownaccess;
 8773:     # Community Coordinator or Assistant Co-author browsing resource space.
 8774:     if (($priv eq 'bro') && ($env{'user.author'})) {
 8775:         if ($uri eq '') {
 8776:             $ownaccess = 1;
 8777:         } else {
 8778:             if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
 8779:                 my $udom = $env{'user.domain'};
 8780:                 my $uname = $env{'user.name'};
 8781:                 if ($uri =~ m{^\Q$udom\E/?$}) {
 8782:                     $ownaccess = 1;
 8783:                 } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
 8784:                     unless ($uri =~ m{\.\./}) {
 8785:                         $ownaccess = 1;
 8786:                     }
 8787:                 } elsif (($udom ne 'public') && ($uname ne 'public')) {
 8788:                     my $now = time;
 8789:                     if ($uri =~ m{^([^/]+)/?$}) {
 8790:                         my $adom = $1;
 8791:                         foreach my $key (keys(%env)) {
 8792:                             if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
 8793:                                 my ($start,$end) = split(/\./,$env{$key});
 8794:                                 if (($now >= $start) && (!$end || $end > $now)) {
 8795:                                     $ownaccess = 1;
 8796:                                     last;
 8797:                                 }
 8798:                             }
 8799:                         }
 8800:                     } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
 8801:                         my $adom = $1;
 8802:                         my $aname = $2;
 8803:                         foreach my $role ('ca','aa') { 
 8804:                             if ($env{"user.role.$role./$adom/$aname"}) {
 8805:                                 my ($start,$end) =
 8806:                                     split(/\./,$env{"user.role.$role./$adom/$aname"});
 8807:                                 if (($now >= $start) && (!$end || $end > $now)) {
 8808:                                     $ownaccess = 1;
 8809:                                     last;
 8810:                                 }
 8811:                             }
 8812:                         }
 8813:                     }
 8814:                 }
 8815:             }
 8816:         }
 8817:     }
 8818: 
 8819: # Course
 8820: 
 8821:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
 8822:         unless (($priv eq 'bro') && (!$ownaccess)) {
 8823:             $thisallowed.=$1;
 8824:         }
 8825:     }
 8826: 
 8827: # Domain
 8828: 
 8829:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
 8830:        =~/\Q$priv\E\&([^\:]*)/) {
 8831:         unless (($priv eq 'bro') && (!$ownaccess)) {
 8832:             $thisallowed.=$1;
 8833:         }
 8834:     }
 8835: 
 8836: # User who is not author or co-author might still be able to edit
 8837: # resource of an author in the domain (e.g., if Domain Coordinator).
 8838:     if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
 8839:         (&allowed('mdc',$env{'request.course.id'}))) {
 8840:         if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
 8841:             $thisallowed.=$1;
 8842:         }
 8843:     }
 8844: 
 8845: # Course: uri itself is a course
 8846:     my $courseuri=$uri;
 8847:     $courseuri=~s/\_(\d)/\/$1/;
 8848:     $courseuri=~s/^([^\/])/\/$1/;
 8849: 
 8850:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
 8851:        =~/\Q$priv\E\&([^\:]*)/) {
 8852:         if ($priv eq 'mip') {
 8853:             my $rem = $1;
 8854:             if (($uri ne '') && ($env{'request.course.id'} eq $uri) &&
 8855:                 ($env{'course.'.$env{'request.course.id'}.'.internal.courseowner'} eq $env{'user.name'}.':'.$env{'user.domain'})) {
 8856:                 my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 8857:                 if ($cdom ne '') {
 8858:                     my %passwdconf = &get_passwdconf($cdom);
 8859:                     if (ref($passwdconf{'crsownerchg'}) eq 'HASH') {
 8860:                         if (ref($passwdconf{'crsownerchg'}{'by'}) eq 'ARRAY') {
 8861:                             if (@{$passwdconf{'crsownerchg'}{'by'}}) {
 8862:                                 my @inststatuses = split(':',$env{'environment.inststatus'});
 8863:                                 unless (@inststatuses) {
 8864:                                     @inststatuses = ('default');
 8865:                                 }
 8866:                                 foreach my $status (@inststatuses) {
 8867:                                     if (grep(/^\Q$status\E$/,@{$passwdconf{'crsownerchg'}{'by'}})) {
 8868:                                         $thisallowed.=$rem;
 8869:                                     }
 8870:                                 }
 8871:                             }
 8872:                         }
 8873:                     }
 8874:                 }
 8875:             }
 8876:         } else {
 8877:             unless (($priv eq 'bro') && (!$ownaccess)) {
 8878:                 $thisallowed.=$1;
 8879:             }
 8880:         }
 8881:     }
 8882: 
 8883: # URI is an uploaded document for this course, default permissions don't matter
 8884: # not allowing 'edit' access (editupload) to uploaded course docs
 8885:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
 8886: 	$thisallowed='';
 8887:         my ($match)=&is_on_map($uri);
 8888:         if ($match) {
 8889:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
 8890:                   =~/\Q$priv\E\&([^\:]*)/) {
 8891:                 my $value = $1;
 8892:                 my $deeplinkblock;
 8893:                 unless ($nodeeplinkcheck) {
 8894:                     $deeplinkblock = &deeplink_check($priv,$symb,$uri);
 8895:                 }
 8896:                 if ($deeplinkblock) {
 8897:                     $thisallowed='D';
 8898:                 } elsif ($noblockcheck) {
 8899:                     $thisallowed.=$value;
 8900:                 } else {
 8901:                     my @blockers = &has_comm_blocking($priv,$symb,$uri,$ignorecache);
 8902:                     if (@blockers > 0) {
 8903:                         $thisallowed = 'B';
 8904:                     } else {
 8905:                         $thisallowed.=$value;
 8906:                     }
 8907:                 }
 8908:             }
 8909:         } else {
 8910:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
 8911:             if ($refuri) {
 8912:                 if ($refuri =~ m|^/adm/|) {
 8913:                     $thisallowed='F';
 8914:                 } else {
 8915:                     $refuri=&declutter($refuri);
 8916:                     my ($match) = &is_on_map($refuri);
 8917:                     if ($match) {
 8918:                         my $deeplinkblock;
 8919:                         unless ($nodeeplinkcheck) {
 8920:                             $deeplinkblock = &deeplink_check($priv,$symb,$refuri);
 8921:                         }
 8922:                         if ($deeplinkblock) {
 8923:                             $thisallowed='D';
 8924:                         } elsif ($noblockcheck) {
 8925:                             $thisallowed='F';
 8926:                         } else {
 8927:                             my @blockers = &has_comm_blocking($priv,'',$refuri,'',1);
 8928:                             if (@blockers > 0) {
 8929:                                 $thisallowed = 'B';
 8930:                             } else {
 8931:                                 $thisallowed='F';
 8932:                             }
 8933:                         }
 8934:                     }
 8935:                 }
 8936:             }
 8937:         }
 8938:     }
 8939: 
 8940:     if ($priv eq 'bre'
 8941: 	&& $thisallowed ne 'F' 
 8942: 	&& $thisallowed ne '2'
 8943: 	&& &is_portfolio_url($uri)) {
 8944: 	$thisallowed = &portfolio_access($uri,$clientip);
 8945:     }
 8946: 
 8947: # Full access at system, domain or course-wide level? Exit.
 8948:     if ($thisallowed=~/F/) {
 8949: 	return 'F';
 8950:     }
 8951: 
 8952: # If this is generating or modifying users, exit with special codes
 8953: 
 8954:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:vca:vaa:'=~/\:\Q$priv\E\:/) {
 8955: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
 8956: 	    my ($audom,$auname)=split('/',$uri);
 8957: # no author name given, so this just checks on the general right to make a co-author in this domain
 8958: 	    unless ($auname) { return $thisallowed; }
 8959: # an author name is given, so we are about to actually make a co-author for a certain account
 8960: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
 8961: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
 8962: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
 8963: 	} elsif (($priv eq 'vca') || ($priv eq 'vaa')) {
 8964:             my ($audom,$auname)=split('/',$uri);
 8965:             unless ($auname) { return $thisallowed; }
 8966:             unless (($env{'request.role'} eq "dc./$audom") ||
 8967:                     ($env{'request.role'} eq "ca./$uri")) {
 8968:                 return '';
 8969:             }
 8970: 	}
 8971: 	return $thisallowed;
 8972:     }
 8973: #
 8974: # Gathered so far: system, domain and course wide privileges
 8975: #
 8976: # Course: See if uri or referer is an individual resource that is part of 
 8977: # the course
 8978: 
 8979:     if ($env{'request.course.id'}) {
 8980: 
 8981:         if ($priv eq 'bre') {
 8982:             if (&is_coursetool_logo($uri)) {
 8983:                 return 'F';
 8984:             }
 8985:         }
 8986: 
 8987: # If this is modifying password (internal auth) domains must match for user and user's role.
 8988: 
 8989:         if ($priv eq 'mip') {
 8990:             if ($env{'user.domain'} eq $env{'request.role.domain'}) {
 8991:                 return $thisallowed;
 8992:             } else {
 8993:                 return '';
 8994:             }
 8995:         }
 8996: 
 8997:        $courseprivid=$env{'request.course.id'};
 8998:        if ($env{'request.course.sec'}) {
 8999:           $courseprivid.='/'.$env{'request.course.sec'};
 9000:        }
 9001:        $courseprivid=~s/\_/\//;
 9002:        my $checkreferer=1;
 9003:        my ($match,$cond)=&is_on_map($uri);
 9004:        if ($match) {
 9005:            $statecond=$cond;
 9006:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 9007:                =~/\Q$priv\E\&([^\:]*)/) {
 9008:                my $value = $1;
 9009:                if ($priv eq 'bre') {
 9010:                    my $deeplinkblock;
 9011:                    unless ($nodeeplinkcheck) {
 9012:                        $deeplinkblock = &deeplink_check($priv,$symb,$uri);
 9013:                    }
 9014:                    if ($deeplinkblock) {
 9015:                        $thisallowed = 'D';
 9016:                    } elsif ($noblockcheck) {
 9017:                        $thisallowed.=$value;
 9018:                    } else {
 9019:                        my @blockers = &has_comm_blocking($priv,$symb,$uri,$ignorecache);
 9020:                        if (@blockers > 0) {
 9021:                            $thisallowed = 'B';
 9022:                        } else {
 9023:                            $thisallowed.=$value;
 9024:                        }
 9025:                    }
 9026:                } else {
 9027:                    $thisallowed.=$value;
 9028:                }
 9029:                $checkreferer=0;
 9030:            }
 9031:        }
 9032: 
 9033:        if ($checkreferer) {
 9034: 	  my $refuri=$env{'httpref.'.$orguri};
 9035:             unless ($refuri) {
 9036:                 foreach my $key (keys(%env)) {
 9037: 		    if ($key=~/^httpref\..*\*/) {
 9038: 			my $pattern=$key;
 9039:                         $pattern=~s/^httpref\.\/res\///;
 9040:                         $pattern=~s/\*/\[\^\/\]\+/g;
 9041:                         $pattern=~s/\//\\\//g;
 9042:                         if ($orguri=~/$pattern/) {
 9043: 			    $refuri=$env{$key};
 9044:                         }
 9045:                     }
 9046:                 }
 9047:             }
 9048: 
 9049:          if ($refuri) { 
 9050: 	  $refuri=&declutter($refuri);
 9051:           my ($match,$cond)=&is_on_map($refuri);
 9052:             if ($match) {
 9053:               my $refstatecond=$cond;
 9054:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 9055:                   =~/\Q$priv\E\&([^\:]*)/) {
 9056:                   my $value = $1;
 9057:                   if ($priv eq 'bre') {
 9058:                       my $deeplinkblock;
 9059:                       unless ($nodeeplinkcheck) {
 9060:                           $deeplinkblock = &deeplink_check($priv,$symb,$refuri);
 9061:                       }
 9062:                       if ($deeplinkblock) {
 9063:                           $thisallowed = 'D';
 9064:                       } elsif ($noblockcheck) {
 9065:                           $thisallowed.=$value;
 9066:                       } else {
 9067:                           my @blockers = &has_comm_blocking($priv,'',$refuri,'',1);
 9068:                           if (@blockers > 0) {
 9069:                               $thisallowed = 'B';
 9070:                           } else {
 9071:                               $thisallowed.=$value;
 9072:                           }
 9073:                       }
 9074:                   } else {
 9075:                       $thisallowed.=$value;
 9076:                   }
 9077:                   $uri=$refuri;
 9078:                   $statecond=$refstatecond;
 9079:               }
 9080:           }
 9081:         }
 9082:        }
 9083:    }
 9084: 
 9085: #
 9086: # Gathered now: all privileges that could apply, and condition number
 9087: # 
 9088: #
 9089: # Full or no access?
 9090: #
 9091: 
 9092:     if ($thisallowed=~/F/) {
 9093: 	return 'F';
 9094:     }
 9095: 
 9096:     unless ($thisallowed) {
 9097:         return '';
 9098:     }
 9099: 
 9100: # Restrictions exist, deal with them
 9101: #
 9102: #   C:according to course preferences
 9103: #   R:according to resource settings
 9104: #   L:unless locked
 9105: #   X:according to user session state
 9106: #
 9107: 
 9108: # Possibly locked functionality, check all courses
 9109: # In roles.tab, L (unless locked) available for bre, pch, plc, pac and sma.
 9110: # Locks might take effect only after 10 minutes cache expiration for other
 9111: # courses, and 2 minutes for current course, in which user has st or ta role
 9112: # which is neither expired nor a future role (unless current course).
 9113: 
 9114:     my ($needlockcheck,$now,$crsonly);
 9115:     if ($thisallowed=~/L/) {
 9116:         $now = time;
 9117:         if ($priv eq 'bre') {
 9118:             if ($uri ne '') {
 9119:                 if ($orguri =~ m{^/+res/}) {
 9120:                     if ($uri =~ m{^lib/templates/}) {
 9121:                         if ($env{'request.course.id'}) {
 9122:                             $crsonly = 1;
 9123:                             $needlockcheck = 1;
 9124:                         }
 9125:                     } else {
 9126:                         $needlockcheck = 1;
 9127:                     }
 9128:                 } elsif ($env{'request.course.id'}) {
 9129:                     my ($crsdom,$crsnum) = split('_',$env{'request.course.id'});
 9130:                     if (($uri =~ m{^(adm|uploaded|public)/$crsdom/$crsnum/}) ||
 9131:                         ($uri =~ m{^adm/$match_domain/$match_username/\d+/(smppg|bulletinboard)$})) {
 9132:                         $crsonly = 1;
 9133:                     }
 9134:                     $needlockcheck = 1;
 9135:                 }
 9136:             }
 9137:         } elsif (($priv eq 'pch') || ($priv eq 'plc') || ($priv eq 'pac') || ($priv eq 'sma')) {
 9138:             $needlockcheck = 1;
 9139:         }
 9140:     }
 9141:     if ($needlockcheck) {
 9142:         foreach my $envkey (keys(%env)) {
 9143:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
 9144:                my $courseid=$2;
 9145:                my $roleid=$1.'.'.$2;
 9146:                $courseid=~s/^\///;
 9147:                unless ($env{'request.role'} eq $roleid) {
 9148:                    my ($start,$end) = split(/\./,$env{$envkey});
 9149:                    next unless (($now >= $start) && (!$end || $end > $now));
 9150:                }
 9151:                my $expiretime=600;
 9152:                if ($env{'request.role'} eq $roleid) {
 9153: 		  $expiretime=120;
 9154:                }
 9155: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
 9156:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
 9157:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
 9158: 		   &coursedescription($courseid,{'freshen_cache' => 1});
 9159:                }
 9160:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
 9161:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
 9162: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
 9163:                        &log($env{'user.domain'},$env{'user.name'},
 9164:                             $env{'user.home'},
 9165:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
 9166:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 9167:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 9168: 		       return '';
 9169:                    }
 9170:                }
 9171:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
 9172:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
 9173: 		   if ($env{$prefix.'priv.'.$priv.'.lock.expire'}>time) {
 9174:                        &log($env{'user.domain'},$env{'user.name'},
 9175:                             $env{'user.home'},
 9176:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
 9177:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 9178:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 9179: 		       return '';
 9180:                    }
 9181:                }
 9182: 	   }
 9183:        }
 9184:     }
 9185: 
 9186: #
 9187: # Rest of the restrictions depend on selected course
 9188: #
 9189: 
 9190:     unless ($env{'request.course.id'}) {
 9191: 	if ($thisallowed eq 'A') {
 9192: 	    return 'A';
 9193:         } elsif ($thisallowed eq 'B') {
 9194:             return 'B';
 9195: 	} else {
 9196: 	    return '1';
 9197: 	}
 9198:     }
 9199: 
 9200: #
 9201: # Now user is definitely in a course
 9202: #
 9203: 
 9204: 
 9205: # Course preferences
 9206: 
 9207:    if ($thisallowed=~/C/) {
 9208:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 9209:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
 9210:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
 9211: 	   =~/\Q$rolecode\E/) {
 9212: 	   if (($priv ne 'pch') && ($priv ne 'plc') && ($priv ne 'pac')) {
 9213: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 9214: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
 9215: 			$env{'request.course.id'});
 9216: 	   }
 9217:            return '';
 9218:        }
 9219: 
 9220:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
 9221: 	   =~/\Q$unamedom\E/) {
 9222: 	   if (($priv ne 'pch') && ($priv ne 'plc') && ($priv ne 'pac')) {
 9223: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
 9224: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
 9225: 			$env{'request.course.id'});
 9226: 	   }
 9227:            return '';
 9228:        }
 9229:    }
 9230: 
 9231: # Resource preferences
 9232: 
 9233:    if ($thisallowed=~/R/) {
 9234:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 9235:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
 9236: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
 9237: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 9238: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
 9239: 	   }
 9240: 	   return '';
 9241:        }
 9242:    }
 9243: 
 9244: # Restricted for deeplinked session?
 9245: 
 9246:     if ($env{'request.deeplink.login'}) {
 9247:         if ($env{'acc.deeplinkout'} && !$nodeeplinkout) {
 9248:             if (!$symb) { $symb=&symbread($uri,1); }
 9249:             if (($symb) && ($env{'acc.deeplinkout'}=~/\&\Q$symb\E\&/)) {
 9250:                 return '';
 9251:             }
 9252:         }
 9253:     }
 9254: 
 9255: # Restricted by state or randomout?
 9256: 
 9257:    if ($thisallowed=~/X/) {
 9258:       if ($env{'acc.randomout'}) {
 9259: 	 if (!$symb) { $symb=&symbread($uri,1); }
 9260:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
 9261:             return ''; 
 9262:          }
 9263:       }
 9264:       if (&condval($statecond)) {
 9265: 	 return '2';
 9266:       } else {
 9267:          return '';
 9268:       }
 9269:    }
 9270: 
 9271:     if ($thisallowed eq 'A') {
 9272: 	return 'A';
 9273:     } elsif ($thisallowed eq 'B') {
 9274:         return 'B';
 9275:     } elsif ($thisallowed eq 'D') {
 9276:         return 'D';
 9277:     }
 9278:    return 'F';
 9279: }
 9280: 
 9281: # ------------------------------------------- Check construction space access
 9282: 
 9283: sub constructaccess {
 9284:     my ($url,$setpriv)=@_;
 9285: 
 9286: # We do not allow editing of previous versions of files
 9287:     if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
 9288: 
 9289: # Get username and domain from URL
 9290:     my ($ownername,$ownerdomain,$ownerhome);
 9291: 
 9292:     ($ownerdomain,$ownername) =
 9293:         ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)(?:/daxepage|/daxeopen)?/priv/($match_domain)/($match_username)(?:/|$)});
 9294: 
 9295: # The URL does not really point to any authorspace, forget it
 9296:     unless (($ownername) && ($ownerdomain)) { return ''; }
 9297: 
 9298: # Now we need to see if the user has access to the authorspace of
 9299: # $ownername at $ownerdomain
 9300: 
 9301:     if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
 9302: # Real author for this?
 9303:        $ownerhome = $env{'user.home'};
 9304:        if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
 9305:           return ($ownername,$ownerdomain,$ownerhome);
 9306:        }
 9307:     } elsif (&is_course($ownerdomain,$ownername)) {
 9308: # Course Authoring Space?
 9309:         if ($env{'request.course.id'}) {
 9310:             if (($ownername eq $env{'course.'.$env{'request.course.id'}.'.num'}) &&
 9311:                 ($ownerdomain eq $env{'course.'.$env{'request.course.id'}.'.domain'})) {
 9312:                 if (&allowed('mdc',$env{'request.course.id'})) {
 9313:                     return if ($env{'course.'.$env{'request.course.id'}.'.internal.crsauthor'} eq '0');
 9314:                     unless ($env{'course.'.$env{'request.course.id'}.'.internal.crsauthor'}) {
 9315:                         my %domdefs = &get_domain_defaults($ownerdomain);
 9316:                         my $type = lc($env{'course.'.$env{'request.course.id'}.'.type'});
 9317:                         unless (($type eq 'community') || ($type eq 'placement')) {
 9318:                             $type = 'unofficial';
 9319:                             if ($env{'course.'.$env{'request.course.id'}.'internal.coursecode'} ne '') {
 9320:                                 $type = 'official';
 9321:                             } elsif ($env{'course.'.$env{'request.course.id'}.'internal.textbook'} ne '') {
 9322:                                 $type = 'textbook';
 9323:                             } else {
 9324:                                 $type = 'unofficial';
 9325:                             }
 9326:                         }
 9327:                         return if ($domdefs{$type.'crsauthor'} eq '0');
 9328:                     }
 9329:                     $ownerhome = $env{'course.'.$env{'request.course.id'}.'.home'};
 9330:                     return ($ownername,$ownerdomain,$ownerhome);
 9331:                 }
 9332:             }
 9333:         }
 9334:         return '';
 9335:     } else {
 9336: # Co-author for this?
 9337:         if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
 9338:             exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
 9339:             $ownerhome = &homeserver($ownername,$ownerdomain);
 9340:             return ($ownername,$ownerdomain,$ownerhome);
 9341:         }
 9342:     }
 9343: 
 9344: # We don't have any access right now. If we are not possibly going to do anything about this,
 9345: # we might as well leave
 9346:    unless ($setpriv) { return ''; }
 9347: 
 9348: # Backdoor access?
 9349:     my $allowed=&allowed('eco',$ownerdomain);
 9350: # Nope
 9351:     unless ($allowed) { return ''; }
 9352: # Looks like we may have access, but could be locked by the owner of the construction space
 9353:     if ($allowed eq 'U') {
 9354:         my %blocked=&get('environment',['domcoord.author'],
 9355:                          $ownerdomain,$ownername);
 9356: # Is blocked by owner
 9357:         if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
 9358:     }
 9359:     if (($allowed eq 'F') || ($allowed eq 'U')) {
 9360: # Grant temporary access
 9361:         my $then=$env{'user.login.time'};
 9362:         my $update=$env{'user.update.time'};
 9363:         if (!$update) { $update = $then; }
 9364:         my $refresh=$env{'user.refresh.time'};
 9365:         if (!$refresh) { $refresh = $update; }
 9366:         my $now = time;
 9367:         &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
 9368:                            $now,'ca','constructaccess');
 9369:         $ownerhome = &homeserver($ownername,$ownerdomain);
 9370:         return($ownername,$ownerdomain,$ownerhome);
 9371:     }
 9372: # No business here
 9373:     return '';
 9374: }
 9375: 
 9376: # ----------------------------------------------------------- Content Blocking
 9377: 
 9378: {
 9379: # Caches for faster Course Contents display where content blocking
 9380: # is in operation (i.e., interval param set) for timed quiz.
 9381: #
 9382: # User for whom data are being temporarily cached.
 9383: my $cacheduser='';
 9384: # Course for which data are being temporarily cached.
 9385: my $cachedcid='';
 9386: # Cached blockers for this user (a hash of blocking items). 
 9387: my %cachedblockers=();
 9388: # When the data were last cached.
 9389: my $cachedlast='';
 9390: 
 9391: sub load_all_blockers {
 9392:     my ($uname,$udom)=@_;
 9393:     if (($uname ne '') && ($udom ne '')) { 
 9394:         if (($cacheduser eq $uname.':'.$udom) &&
 9395:             ($cachedcid eq $env{'request.course.id'}) &&
 9396:             (abs($cachedlast-time)<5)) {
 9397:             return;
 9398:         }
 9399:     }
 9400:     $cachedlast=time;
 9401:     $cacheduser=$uname.':'.$udom;
 9402:     $cachedcid=$env{'request.course.id'};
 9403:     %cachedblockers = &get_commblock_resources();
 9404:     return;
 9405: }
 9406: 
 9407: sub get_comm_blocks {
 9408:     my ($cdom,$cnum) = @_;
 9409:     if ($cdom eq '' || $cnum eq '') {
 9410:         return unless ($env{'request.course.id'});
 9411:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 9412:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 9413:     }
 9414:     my %commblocks;
 9415:     my $hashid=$cdom.'_'.$cnum;
 9416:     my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
 9417:     if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
 9418:         %commblocks = %{$blocksref};
 9419:     } else {
 9420:         %commblocks = &dump('comm_block',$cdom,$cnum);
 9421:         my $cachetime = 600;
 9422:         &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
 9423:     }
 9424:     return %commblocks;
 9425: }
 9426: 
 9427: sub get_commblock_resources {
 9428:     my ($blocks) = @_;
 9429:     my %blockers = ();
 9430:     return %blockers unless ($env{'request.course.id'});
 9431:     my $courseurl = &courseid_to_courseurl($env{'request.course.id'});
 9432:     if ($env{'request.course.sec'}) {
 9433:         $courseurl .= '/'.$env{'request.course.sec'};
 9434:     }
 9435:     return %blockers if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseurl} =~/evb\&([^\:]*)/);
 9436:     my %commblocks;
 9437:     if (ref($blocks) eq 'HASH') {
 9438:         %commblocks = %{$blocks};
 9439:     } else {
 9440:         %commblocks = &get_comm_blocks();
 9441:     }
 9442:     return %blockers unless (keys(%commblocks) > 0); 
 9443:     my $navmap = Apache::lonnavmaps::navmap->new();
 9444:     return %blockers unless (ref($navmap));
 9445:     my $now = time;
 9446:     foreach my $block (keys(%commblocks)) {
 9447:         if ($block =~ /^(\d+)____(\d+)$/) {
 9448:             my ($start,$end) = ($1,$2);
 9449:             if ($start <= $now && $end >= $now) {
 9450:                 if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
 9451:                     if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
 9452:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
 9453:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
 9454:                                 $blockers{$block}{maps} = $commblocks{$block}{'blocks'}{'docs'}{'maps'}; 
 9455:                             }
 9456:                         }
 9457:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
 9458:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
 9459:                                 $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
 9460:                             }
 9461:                         }
 9462:                     }
 9463:                 }
 9464:             }
 9465:         } elsif ($block =~ /^firstaccess____(.+)$/) {
 9466:             my $item = $1;
 9467:             if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
 9468:                 if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
 9469:                     my (@interval,$mapname);
 9470:                     my $type = 'map';
 9471:                     if ($item eq 'course') {
 9472:                         $type = 'course';
 9473:                         @interval=&EXT("resource.0.interval");
 9474:                     } else {
 9475:                         if ($item =~ /___\d+___/) {
 9476:                             $type = 'resource';
 9477:                             @interval=&EXT("resource.0.interval",$item);
 9478:                         } else {
 9479:                             $mapname = &deversion($item);
 9480:                             if (ref($navmap)) {
 9481:                                 my $timelimit = $navmap->get_mapparam(undef,$mapname,'0.interval');
 9482:                                 @interval = ($timelimit,'map');
 9483:                             }
 9484:                         }
 9485:                     }
 9486:                     if ($interval[0] =~ /^(\d+)/) {
 9487:                         my $timelimit = $1; 
 9488:                         my $first_access;
 9489:                         if ($type eq 'resource') {
 9490:                             $first_access=&get_first_access($interval[1],$item);
 9491:                         } elsif ($type eq 'map') {
 9492:                             $first_access=&get_first_access($interval[1],undef,$item);
 9493:                         } else {
 9494:                             $first_access=&get_first_access($interval[1]);
 9495:                         }
 9496:                         if ($first_access) {
 9497:                             my $timesup = $first_access+$timelimit;
 9498:                             if ($timesup > $now) {
 9499:                                 my $activeblock;
 9500:                                 if ($type eq 'resource') {
 9501:                                     if (ref($navmap)) {
 9502:                                         my $res = $navmap->getBySymb($item);
 9503:                                         if ($res->answerable()) {
 9504:                                             $activeblock = 1;
 9505:                                         }
 9506:                                     }
 9507:                                 } elsif ($type eq 'map') {
 9508:                                     my $mapsymb = &symbread($mapname,1);
 9509:                                     if (($mapsymb) && (ref($navmap))) {
 9510:                                         my $mapres = $navmap->getBySymb($mapsymb);
 9511:                                         if (ref($mapres)) {
 9512:                                             my $first = $mapres->map_start();
 9513:                                             my $finish = $mapres->map_finish();
 9514:                                             my $it = $navmap->getIterator($first,$finish,undef,0,0);
 9515:                                             if (ref($it)) {
 9516:                                                 my $res;
 9517:                                                 while ($res = $it->next(undef,1)) {
 9518:                                                     next unless (ref($res));
 9519:                                                     my $symb = $res->symb();
 9520:                                                     next if (($symb eq $mapsymb) || ($symb eq ''));
 9521:                                                     @interval=&EXT("resource.0.interval",$symb);
 9522:                                                     if ($interval[1] eq 'map') {
 9523:                                                         if ($res->answerable()) {
 9524:                                                             $activeblock = 1;
 9525:                                                             last;
 9526:                                                         }
 9527:                                                     }
 9528:                                                 }
 9529:                                             }
 9530:                                         }
 9531:                                     }
 9532:                                 }
 9533:                                 if ($activeblock) {
 9534:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
 9535:                                          if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
 9536:                                              $blockers{$block}{'maps'} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
 9537:                                          }
 9538:                                     }
 9539:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
 9540:                                         if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
 9541:                                             $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
 9542:                                         }
 9543:                                     }
 9544:                                 }
 9545:                             }
 9546:                         }
 9547:                     }
 9548:                 }
 9549:             }
 9550:         }
 9551:     }
 9552:     return %blockers;
 9553: }
 9554: 
 9555: sub has_comm_blocking {
 9556:     my ($priv,$symb,$uri,$ignoresymbdb,$noenccheck,$blocked,$blocks) = @_;
 9557:     my @blockers;
 9558:     return unless ($env{'request.course.id'});
 9559:     return unless ($priv eq 'bre');
 9560:     return if ($env{'request.state'} eq 'construct');
 9561:     my $courseurl = &courseid_to_courseurl($env{'request.course.id'});
 9562:     if ($env{'request.course.sec'}) {
 9563:         $courseurl .= '/'.$env{'request.course.sec'};
 9564:     }
 9565:     return if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseurl} =~/evb\&([^\:]*)/);
 9566:     my %blockinfo;
 9567:     if (ref($blocks) eq 'HASH') {
 9568:         %blockinfo = &get_commblock_resources($blocks);
 9569:     } else {
 9570:         &load_all_blockers($env{'user.name'},$env{'user.domain'});
 9571:         %blockinfo = %cachedblockers;
 9572:     }
 9573:     return unless (keys(%blockinfo) > 0);
 9574:     my (%possibles,@symbs);
 9575:     if (!$symb) {
 9576:         $symb = &symbread($uri,1,1,1,\%possibles,$ignoresymbdb,$noenccheck);
 9577:     }
 9578:     if ($symb) {
 9579:         @symbs = ($symb);
 9580:     } elsif (keys(%possibles)) { 
 9581:         @symbs = keys(%possibles);
 9582:     }
 9583:     my $noblock;
 9584:     foreach my $symb (@symbs) {
 9585:         last if ($noblock);
 9586:         my ($map,$resid,$resurl)=&decode_symb($symb);
 9587:         foreach my $block (keys(%blockinfo)) {
 9588:             if ($block =~ /^firstaccess____(.+)$/) {
 9589:                 my $item = $1;
 9590:                 unless ($blocked) {
 9591:                     if (($item eq $map) || ($item eq $symb)) {
 9592:                         $noblock = 1;
 9593:                         last;
 9594:                     }
 9595:                 }
 9596:             }
 9597:             if (ref($blockinfo{$block}) eq 'HASH') {
 9598:                 if (ref($blockinfo{$block}{'resources'}) eq 'HASH') {
 9599:                     if ($blockinfo{$block}{'resources'}{$symb}) {
 9600:                         unless (grep(/^\Q$block\E$/,@blockers)) {
 9601:                             push(@blockers,$block);
 9602:                         }
 9603:                     }
 9604:                 }
 9605:                 if (ref($blockinfo{$block}{'maps'}) eq 'HASH') {
 9606:                     if ($blockinfo{$block}{'maps'}{$map}) {
 9607:                         unless (grep(/^\Q$block\E$/,@blockers)) {
 9608:                             push(@blockers,$block);
 9609:                         }
 9610:                     }
 9611:                 }
 9612:             }
 9613:         }
 9614:     }
 9615:     unless ($noblock) { 
 9616:         return @blockers;
 9617:     }
 9618:     return;
 9619: }
 9620: }
 9621: 
 9622: sub deeplink_check {
 9623:     my ($priv,$symb,$uri) = @_;
 9624:     return unless ($env{'request.course.id'});
 9625:     return unless ($priv eq 'bre');
 9626:     return if ($env{'request.state'} eq 'construct');
 9627:     return if ($env{'request.role.adv'});
 9628:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 9629:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 9630:     my (%possibles,@symbs);
 9631:     if (!$symb) {
 9632:         $symb = &symbread($uri,1,1,1,\%possibles);
 9633:     }
 9634:     if ($symb) {
 9635:         @symbs = ($symb);
 9636:     } elsif (keys(%possibles)) {
 9637:         @symbs = keys(%possibles);
 9638:     }
 9639: 
 9640:     my ($deeplink_symb,$allow);
 9641:     if ($env{'request.deeplink.login'}) {
 9642:         $deeplink_symb = &Apache::loncommon::deeplink_login_symb($cnum,$cdom);
 9643:     }
 9644:     foreach my $symb (@symbs) {
 9645:         last if ($allow);
 9646:         my $deeplink = &EXT("resource.0.deeplink",$symb);
 9647:         if ($deeplink eq '') {
 9648:             $allow = 1;
 9649:         } else {
 9650:             my ($state,$others,$listed,$scope,$protect) = split(/,/,$deeplink);
 9651:             if ($state ne 'only') {
 9652:                 $allow = 1;
 9653:             } else {
 9654:                 my $check_deeplink_entry;
 9655:                 if ($protect ne 'none') {
 9656:                     my ($acctype,$item) = split(/:/,$protect);
 9657:                     if (($acctype eq 'ltic') && ($env{'user.linkprotector'})) {
 9658:                         if (grep(/^\Q$item\Ec$/,split(/,/,$env{'user.linkprotector'}))) {
 9659:                             $check_deeplink_entry = 1
 9660:                         }
 9661:                     } elsif (($acctype eq 'ltid') && ($env{'user.linkprotector'})) {
 9662:                         if (grep(/^\Q$item\Ed$/,split(/,/,$env{'user.linkprotector'}))) {
 9663:                             $check_deeplink_entry = 1;
 9664:                         }
 9665:                     } elsif (($acctype eq 'key') && ($env{'user.deeplinkkey'})) {
 9666:                         if (grep(/^\Q$item\E$/,split(/,/,$env{'user.deeplinkkey'}))) {
 9667:                             $check_deeplink_entry = 1;
 9668:                         }
 9669:                     }
 9670:                 }
 9671:                 if (($protect eq 'none') || ($check_deeplink_entry)) {
 9672:                     if ($scope eq 'res') {
 9673:                         if ($symb eq $deeplink_symb) {
 9674:                             $allow = 1;
 9675:                         }
 9676:                     } elsif (($scope eq 'map') || ($scope eq 'rec')) {
 9677:                         my ($map_from_symb,$map_from_login);
 9678:                         $map_from_symb = &deversion((&decode_symb($symb))[0]);
 9679:                         if ($deeplink_symb =~ /\.(page|sequence)$/) {
 9680:                             $map_from_login = &deversion((&decode_symb($deeplink_symb))[2]);
 9681:                         } else {
 9682:                             $map_from_login = &deversion((&decode_symb($deeplink_symb))[0]);
 9683:                         }
 9684:                         if (($map_from_symb) && ($map_from_login)) {
 9685:                             if ($map_from_symb eq $map_from_login) {
 9686:                                 $allow = 1;
 9687:                             } elsif ($scope eq 'rec') {
 9688:                                 my @recurseup = &get_map_hierarchy($map_from_symb,$env{'request.course.id'});
 9689:                                 if (grep(/^\Q$map_from_login\E$/,@recurseup)) {
 9690:                                     $allow = 1;
 9691:                                 }
 9692:                             }
 9693:                         }
 9694:                     }
 9695:                 }
 9696:             }
 9697:         }
 9698:     }
 9699:     return if ($allow);
 9700:     return 1;
 9701: }
 9702: 
 9703: # -------------------------------- Deversion and split uri into path an filename   
 9704: 
 9705: #
 9706: #   Removes the version from a URI and
 9707: #   splits it in to its filename and path to the filename.
 9708: #   Seems like File::Basename could have done this more clearly.
 9709: #   Parameters:
 9710: #      $uri   - input URI
 9711: #   Returns:
 9712: #     Two element list consisting of 
 9713: #     $pathname  - the URI up to and excluding the trailing /
 9714: #     $filename  - The part of the URI following the last /
 9715: #  NOTE:
 9716: #    Another realization of this is simply:
 9717: #    use File::Basename;
 9718: #    ...
 9719: #    $uri = shift;
 9720: #    $filename = basename($uri);
 9721: #    $path     = dirname($uri);
 9722: #    return ($filename, $path);
 9723: #
 9724: #     The implementation below is probably faster however.
 9725: #
 9726: sub split_uri_for_cond {
 9727:     my $uri=&deversion(&declutter(shift));
 9728:     my @uriparts=split(/\//,$uri);
 9729:     my $filename=pop(@uriparts);
 9730:     my $pathname=join('/',@uriparts);
 9731:     return ($pathname,$filename);
 9732: }
 9733: # --------------------------------------------------- Is a resource on the map?
 9734: 
 9735: sub is_on_map {
 9736:     my ($pathname,$filename) = &split_uri_for_cond(shift);
 9737:     #Trying to find the conditional for the file
 9738:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
 9739: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
 9740:     if ($match) {
 9741: 	return (1,$1);
 9742:     } else {
 9743: 	return (0,0);
 9744:     }
 9745: }
 9746: 
 9747: # --------------------------------------------------------- Get symb from alias
 9748: 
 9749: sub get_symb_from_alias {
 9750:     my $symb=shift;
 9751:     my ($map,$resid,$url)=&decode_symb($symb);
 9752: # Already is a symb
 9753:     if ($url) { return $symb; }
 9754: # Must be an alias
 9755:     my $aliassymb='';
 9756:     my %bighash;
 9757:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 9758:                             &GDBM_READER(),0640)) {
 9759:         my $rid=$bighash{'mapalias_'.$symb};
 9760: 	if ($rid) {
 9761: 	    my ($mapid,$resid)=split(/\./,$rid);
 9762: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
 9763: 				    $resid,$bighash{'src_'.$rid});
 9764: 	}
 9765:         untie %bighash;
 9766:     }
 9767:     return $aliassymb;
 9768: }
 9769: 
 9770: # ----------------------------------------------------------------- Define Role
 9771: 
 9772: sub definerole {
 9773:   if (allowed('mcr','/')) {
 9774:     my ($rolename,$sysrole,$domrole,$courole,$uname,$udom)=@_;
 9775:     foreach my $role (split(':',$sysrole)) {
 9776: 	my ($crole,$cqual)=split(/\&/,$role);
 9777:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
 9778:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
 9779: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 9780:                return "refused:s:$crole&$cqual"; 
 9781:             }
 9782:         }
 9783:     }
 9784:     foreach my $role (split(':',$domrole)) {
 9785: 	my ($crole,$cqual)=split(/\&/,$role);
 9786:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
 9787:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
 9788: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
 9789:                return "refused:d:$crole&$cqual"; 
 9790:             }
 9791:         }
 9792:     }
 9793:     foreach my $role (split(':',$courole)) {
 9794: 	my ($crole,$cqual)=split(/\&/,$role);
 9795:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
 9796:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
 9797: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 9798:                return "refused:c:$crole&$cqual"; 
 9799:             }
 9800:         }
 9801:     }
 9802:     my $uhome;
 9803:     if (($uname ne '') && ($udom ne '')) {
 9804:         $uhome = &homeserver($uname,$udom);
 9805:         return $uhome if ($uhome eq 'no_host');
 9806:     } else {
 9807:         $uname = $env{'user.name'};
 9808:         $udom = $env{'user.domain'};
 9809:         $uhome = $env{'user.home'};
 9810:     }
 9811:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
 9812:                 "$udom:$uname:rolesdef_$rolename=".
 9813:                 escape($sysrole.'_'.$domrole.'_'.$courole);
 9814:     return reply($command,$uhome);
 9815:   } else {
 9816:     return 'refused';
 9817:   }
 9818: }
 9819: 
 9820: # ---------------- Make a metadata query against the network of library servers
 9821: 
 9822: sub metadata_query {
 9823:     my ($query,$custom,$customshow,$server_array,$domains_hash)=@_;
 9824:     my %rhash;
 9825:     my %libserv = &all_library();
 9826:     my @server_list = (defined($server_array) ? @$server_array
 9827:                                               : keys(%libserv) );
 9828:     for my $server (@server_list) {
 9829:         my $domains = ''; 
 9830:         if (ref($domains_hash) eq 'HASH') {
 9831:             $domains = $domains_hash->{$server}; 
 9832:         }
 9833: 	unless ($custom or $customshow) {
 9834: 	    my $reply=&reply("querysend:".&escape($query).':::'.&escape($domains),$server);
 9835: 	    $rhash{$server}=$reply;
 9836: 	}
 9837: 	else {
 9838: 	    my $reply=&reply("querysend:".&escape($query).':'.
 9839: 			     &escape($custom).':'.&escape($customshow).':'.&escape($domains),
 9840: 			     $server);
 9841: 	    $rhash{$server}=$reply;
 9842: 	}
 9843:     }
 9844:     return \%rhash;
 9845: }
 9846: 
 9847: # ----------------------------------------- Send log queries and wait for reply
 9848: 
 9849: sub log_query {
 9850:     my ($uname,$udom,$query,%filters)=@_;
 9851:     my $uhome=&homeserver($uname,$udom);
 9852:     if ($uhome eq 'no_host') { return 'error: no_host'; }
 9853:     my $uhost=&hostname($uhome);
 9854:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
 9855:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
 9856:                        $uhome);
 9857:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
 9858:     return get_query_reply($queryid);
 9859: }
 9860: 
 9861: # -------------------------- Update MySQL table for portfolio file
 9862: 
 9863: sub update_portfolio_table {
 9864:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
 9865:     if ($group ne '') {
 9866:         $file_name =~s /^\Q$group\E//;
 9867:     }
 9868:     my $homeserver = &homeserver($uname,$udom);
 9869:     my $queryid=
 9870:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
 9871:                ':'.&escape($file_name).':'.$action,$homeserver);
 9872:     my $reply = &get_query_reply($queryid);
 9873:     return $reply;
 9874: }
 9875: 
 9876: # -------------------------- Update MySQL allusers table
 9877: 
 9878: sub update_allusers_table {
 9879:     my ($uname,$udom,$names) = @_;
 9880:     my $homeserver = &homeserver($uname,$udom);
 9881:     my $queryid=
 9882:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
 9883:                'lastname='.&escape($names->{'lastname'}).'%%'.
 9884:                'firstname='.&escape($names->{'firstname'}).'%%'.
 9885:                'middlename='.&escape($names->{'middlename'}).'%%'.
 9886:                'generation='.&escape($names->{'generation'}).'%%'.
 9887:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
 9888:                'id='.&escape($names->{'id'}),$homeserver);
 9889:     return;
 9890: }
 9891: 
 9892: # ------- Request retrieval of institutional classlists for course(s)
 9893: 
 9894: sub fetch_enrollment_query {
 9895:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
 9896:     my ($homeserver,$sleep,$loopmax);
 9897:     my $maxtries = 1;
 9898:     if ($context eq 'automated') {
 9899:         $homeserver = $perlvar{'lonHostID'};
 9900:         $sleep = 2;
 9901:         $loopmax = 100;
 9902:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
 9903:     } else {
 9904:         $homeserver = &homeserver($cnum,$dom);
 9905:     }
 9906:     my $host=&hostname($homeserver);
 9907:     my $cmd = '';
 9908:     foreach my $affiliate (keys(%{$affiliatesref})) {
 9909:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
 9910:     }
 9911:     $cmd =~ s/%%$//;
 9912:     $cmd = &escape($cmd);
 9913:     my $query = 'fetchenrollment';
 9914:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
 9915:     unless ($queryid=~/^\Q$host\E\_/) { 
 9916:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
 9917:         return 'error: '.$queryid;
 9918:     }
 9919:     my $reply = &get_query_reply($queryid,$sleep,$loopmax);
 9920:     my $tries = 1;
 9921:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 9922:         $reply = &get_query_reply($queryid,$sleep,$loopmax);
 9923:         $tries ++;
 9924:     }
 9925:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 9926:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 9927:     } else {
 9928:         my @responses = split(/:/,$reply);
 9929:         if (grep { $_ eq $homeserver } &current_machine_ids()) {
 9930:             foreach my $line (@responses) {
 9931:                 my ($key,$value) = split(/=/,$line,2);
 9932:                 $$replyref{$key} = $value;
 9933:             }
 9934:         } else {
 9935:             my $pathname = LONCAPA::tempdir();
 9936:             foreach my $line (@responses) {
 9937:                 my ($key,$value) = split(/=/,$line);
 9938:                 $$replyref{$key} = $value;
 9939:                 if ($value > 0) {
 9940:                     foreach my $item (@{$$affiliatesref{$key}}) {
 9941:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
 9942:                         my $destname = $pathname.'/'.$filename;
 9943:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
 9944:                         if ($xml_classlist =~ /^error/) {
 9945:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
 9946:                         } else {
 9947:                             if ( open(FILE,">",$destname) ) {
 9948:                                 print FILE &unescape($xml_classlist);
 9949:                                 close(FILE);
 9950:                             } else {
 9951:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
 9952:                             }
 9953:                         }
 9954:                     }
 9955:                 }
 9956:             }
 9957:         }
 9958:         return 'ok';
 9959:     }
 9960:     return 'error';
 9961: }
 9962: 
 9963: sub get_query_reply {
 9964:     my ($queryid,$sleep,$loopmax) = @_;
 9965:     if (($sleep eq '') || ($sleep !~ /^\d+\.?\d*$/)) {
 9966:         $sleep = 0.2;
 9967:     }
 9968:     if (($loopmax eq '') || ($loopmax =~ /\D/)) {
 9969:         $loopmax = 100;
 9970:     }
 9971:     my $replyfile=LONCAPA::tempdir().$queryid;
 9972:     my $reply='';
 9973:     for (1..$loopmax) {
 9974: 	sleep($sleep);
 9975:         if (-e $replyfile.'.end') {
 9976: 	    if (open(my $fh,"<",$replyfile)) {
 9977: 		$reply = join('',<$fh>);
 9978: 		close($fh);
 9979: 	   } else { return 'error: reply_file_error'; }
 9980:            return &unescape($reply);
 9981: 	}
 9982:     }
 9983:     return 'timeout:'.$queryid;
 9984: }
 9985: 
 9986: sub courselog_query {
 9987: #
 9988: # possible filters:
 9989: # url: url or symb
 9990: # username
 9991: # domain
 9992: # action: view, submit, grade
 9993: # start: timestamp
 9994: # end: timestamp
 9995: #
 9996:     my (%filters)=@_;
 9997:     unless ($env{'request.course.id'}) { return 'no_course'; }
 9998:     if ($filters{'url'}) {
 9999: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
10000:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
10001:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
10002:     }
10003:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
10004:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
10005:     return &log_query($cname,$cdom,'courselog',%filters);
10006: }
10007: 
10008: sub userlog_query {
10009: #
10010: # possible filters:
10011: # action: log check role
10012: # start: timestamp
10013: # end: timestamp
10014: #
10015:     my ($uname,$udom,%filters)=@_;
10016:     return &log_query($uname,$udom,'userlog',%filters);
10017: }
10018: 
10019: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
10020: 
10021: sub auto_run {
10022:     my ($cnum,$cdom) = @_;
10023:     my $response = 0;
10024:     my $settings;
10025:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
10026:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
10027:         $settings = $domconfig{'autoenroll'};
10028:         if ($settings->{'run'} eq '1') {
10029:             $response = 1;
10030:         }
10031:     } else {
10032:         my $homeserver;
10033:         if (&is_course($cdom,$cnum)) {
10034:             $homeserver = &homeserver($cnum,$cdom);
10035:         } else {
10036:             $homeserver = &domain($cdom,'primary');
10037:         }
10038:         if ($homeserver ne 'no_host') {
10039:             $response = &reply('autorun:'.$cdom,$homeserver);
10040:         }
10041:     }
10042:     return $response;
10043: }
10044: 
10045: sub auto_get_sections {
10046:     my ($cnum,$cdom,$inst_coursecode) = @_;
10047:     my $homeserver;
10048:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) { 
10049:         $homeserver = &homeserver($cnum,$cdom);
10050:     }
10051:     if (!defined($homeserver)) { 
10052:         if ($cdom =~ /^$match_domain$/) {
10053:             $homeserver = &domain($cdom,'primary');
10054:         }
10055:     }
10056:     my @secs;
10057:     if (defined($homeserver)) {
10058:         my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
10059:         unless ($response eq 'refused') {
10060:             @secs = split(/:/,$response);
10061:         }
10062:     }
10063:     return @secs;
10064: }
10065: 
10066: sub auto_new_course {
10067:     my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
10068:     my $homeserver = &homeserver($cnum,$cdom);
10069:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
10070:     return $response;
10071: }
10072: 
10073: sub auto_validate_courseID {
10074:     my ($cnum,$cdom,$inst_course_id) = @_;
10075:     my $homeserver = &homeserver($cnum,$cdom);
10076:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
10077:     return $response;
10078: }
10079: 
10080: sub auto_validate_instcode {
10081:     my ($cnum,$cdom,$instcode,$owner) = @_;
10082:     my ($homeserver,$response);
10083:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
10084:         $homeserver = &homeserver($cnum,$cdom);
10085:     }
10086:     if (!defined($homeserver)) {
10087:         if ($cdom =~ /^$match_domain$/) {
10088:             $homeserver = &domain($cdom,'primary');
10089:         }
10090:     }
10091:     $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
10092:                         &escape($instcode).':'.&escape($owner),$homeserver));
10093:     my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
10094:     return ($outcome,$description,$defaultcredits);
10095: }
10096: 
10097: sub auto_validate_inst_crosslist {
10098:     my ($cnum,$cdom,$instcode,$inst_xlist,$coowner) = @_;
10099:     my ($homeserver,$response);
10100:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
10101:         $homeserver = &homeserver($cnum,$cdom);
10102:     }
10103:     if (!defined($homeserver)) {
10104:         if ($cdom =~ /^$match_domain$/) {
10105:             $homeserver = &domain($cdom,'primary');
10106:         }
10107:     }
10108:     unless (($homeserver eq '') || ($homeserver eq 'no_host')) {
10109:         $response=&reply('autovalidateinstcrosslist:'.$cdom.':'.
10110:                          &escape($instcode).':'.&escape($inst_xlist).':'.
10111:                          &escape($coowner),$homeserver);
10112:     }
10113:     return $response;
10114: }
10115: 
10116: sub auto_create_password {
10117:     my ($cnum,$cdom,$authparam,$udom) = @_;
10118:     my ($homeserver,$response);
10119:     my $create_passwd = 0;
10120:     my $authchk = '';
10121:     if ($udom =~ /^$match_domain$/) {
10122:         $homeserver = &domain($udom,'primary');
10123:     }
10124:     if ($homeserver eq '') {
10125:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
10126:             $homeserver = &homeserver($cnum,$cdom);
10127:         }
10128:     }
10129:     if ($homeserver eq '') {
10130:         $authchk = 'nodomain';
10131:     } else {
10132:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
10133:         if ($response eq 'refused') {
10134:             $authchk = 'refused';
10135:         } else {
10136:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
10137:         }
10138:     }
10139:     return ($authparam,$create_passwd,$authchk);
10140: }
10141: 
10142: sub auto_photo_permission {
10143:     my ($cnum,$cdom,$students) = @_;
10144:     my $homeserver = &homeserver($cnum,$cdom);
10145:     my ($outcome,$perm_reqd,$conditions) = 
10146: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
10147:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
10148: 	return (undef,undef);
10149:     }
10150:     return ($outcome,$perm_reqd,$conditions);
10151: }
10152: 
10153: sub auto_checkphotos {
10154:     my ($uname,$udom,$pid) = @_;
10155:     my $homeserver = &homeserver($uname,$udom);
10156:     my ($result,$resulttype);
10157:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
10158: 				   &escape($uname).':'.&escape($pid),
10159: 				   $homeserver));
10160:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
10161: 	return (undef,undef);
10162:     }
10163:     if ($outcome) {
10164:         ($result,$resulttype) = split(/:/,$outcome);
10165:     } 
10166:     return ($result,$resulttype);
10167: }
10168: 
10169: sub auto_photochoice {
10170:     my ($cnum,$cdom) = @_;
10171:     my $homeserver = &homeserver($cnum,$cdom);
10172:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
10173: 						       &escape($cdom),
10174: 						       $homeserver)));
10175:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
10176: 	return (undef,undef);
10177:     }
10178:     return ($update,$comment);
10179: }
10180: 
10181: sub auto_photoupdate {
10182:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
10183:     my $homeserver = &homeserver($cnum,$dom);
10184:     my $host=&hostname($homeserver);
10185:     my $cmd = '';
10186:     my $maxtries = 1;
10187:     foreach my $affiliate (keys(%{$affiliatesref})) {
10188:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
10189:     }
10190:     $cmd =~ s/%%$//;
10191:     $cmd = &escape($cmd);
10192:     my $query = 'institutionalphotos';
10193:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
10194:     unless ($queryid=~/^\Q$host\E\_/) {
10195:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
10196:         return 'error: '.$queryid;
10197:     }
10198:     my $reply = &get_query_reply($queryid);
10199:     my $tries = 1;
10200:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
10201:         $reply = &get_query_reply($queryid);
10202:         $tries ++;
10203:     }
10204:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
10205:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
10206:     } else {
10207:         my @responses = split(/:/,$reply);
10208:         my $outcome = shift(@responses); 
10209:         foreach my $item (@responses) {
10210:             my ($key,$value) = split(/=/,$item);
10211:             $$photo{$key} = $value;
10212:         }
10213:         return $outcome;
10214:     }
10215:     return 'error';
10216: }
10217: 
10218: sub auto_instcode_format {
10219:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
10220: 	$cat_order) = @_;
10221:     my $courses = '';
10222:     my @homeservers;
10223:     if ($caller eq 'global') {
10224: 	my %servers = &get_servers($codedom,'library');
10225: 	foreach my $tryserver (keys(%servers)) {
10226: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
10227: 		push(@homeservers,$tryserver);
10228: 	    }
10229:         }
10230:     } elsif ($caller eq 'requests') {
10231:         if ($codedom =~ /^$match_domain$/) {
10232:             my $chome = &domain($codedom,'primary');
10233:             unless ($chome eq 'no_host') {
10234:                 push(@homeservers,$chome);
10235:             }
10236:         }
10237:     } else {
10238:         push(@homeservers,&homeserver($caller,$codedom));
10239:     }
10240:     foreach my $code (keys(%{$instcodes})) {
10241:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
10242:     }
10243:     chop($courses);
10244:     my $ok_response = 0;
10245:     my $response;
10246:     while (@homeservers > 0 && $ok_response == 0) {
10247:         my $server = shift(@homeservers); 
10248:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
10249:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
10250:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
10251: 		split(/:/,$response);
10252:             %{$codes} = (%{$codes},&str2hash($codes_str));
10253:             push(@{$codetitles},&str2array($codetitles_str));
10254:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
10255:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
10256:             $ok_response = 1;
10257:         }
10258:     }
10259:     if ($ok_response) {
10260:         return 'ok';
10261:     } else {
10262:         return $response;
10263:     }
10264: }
10265: 
10266: sub auto_instcode_defaults {
10267:     my ($domain,$returnhash,$code_order) = @_;
10268:     my @homeservers;
10269: 
10270:     my %servers = &get_servers($domain,'library');
10271:     foreach my $tryserver (keys(%servers)) {
10272: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
10273: 	    push(@homeservers,$tryserver);
10274: 	}
10275:     }
10276: 
10277:     my $response;
10278:     foreach my $server (@homeservers) {
10279:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
10280:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
10281: 	
10282: 	foreach my $pair (split(/\&/,$response)) {
10283: 	    my ($name,$value)=split(/\=/,$pair);
10284: 	    if ($name eq 'code_order') {
10285: 		@{$code_order} = split(/\&/,&unescape($value));
10286: 	    } else {
10287: 		$returnhash->{&unescape($name)}=&unescape($value);
10288: 	    }
10289: 	}
10290: 	return 'ok';
10291:     }
10292: 
10293:     return $response;
10294: }
10295: 
10296: sub auto_possible_instcodes {
10297:     my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
10298:     unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') && 
10299:             (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
10300:         return;
10301:     }
10302:     my (@homeservers,$uhome);
10303:     if (defined(&domain($domain,'primary'))) {
10304:         $uhome=&domain($domain,'primary');
10305:         push(@homeservers,&domain($domain,'primary'));
10306:     } else {
10307:         my %servers = &get_servers($domain,'library');
10308:         foreach my $tryserver (keys(%servers)) {
10309:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
10310:                 push(@homeservers,$tryserver);
10311:             }
10312:         }
10313:     }
10314:     my $response;
10315:     foreach my $server (@homeservers) {
10316:         $response=&reply('autopossibleinstcodes:'.$domain,$server);
10317:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
10318:         my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) = 
10319:             split(':',$response);
10320:         @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
10321:         @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
10322:         foreach my $item (split('&',$cat_title)) {   
10323:             my ($name,$value)=split('=',$item);
10324:             $cat_titles->{&unescape($name)}=&thaw_unescape($value);
10325:         }
10326:         foreach my $item (split('&',$cat_order)) {
10327:             my ($name,$value)=split('=',$item);
10328:             $cat_orders->{&unescape($name)}=&thaw_unescape($value);
10329:         }
10330:         return 'ok';
10331:     }
10332:     return $response;
10333: }
10334: 
10335: sub auto_courserequest_checks {
10336:     my ($dom) = @_;
10337:     my ($homeserver,%validations);
10338:     if ($dom =~ /^$match_domain$/) {
10339:         $homeserver = &domain($dom,'primary');
10340:     }
10341:     unless ($homeserver eq 'no_host') {
10342:         my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
10343:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
10344:             my @items = split(/&/,$response);
10345:             foreach my $item (@items) {
10346:                 my ($key,$value) = split('=',$item);
10347:                 $validations{&unescape($key)} = &thaw_unescape($value);
10348:             }
10349:         }
10350:     }
10351:     return %validations; 
10352: }
10353: 
10354: sub auto_courserequest_validation {
10355:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist,$custominfo) = @_;
10356:     my ($homeserver,$response);
10357:     if ($dom =~ /^$match_domain$/) {
10358:         $homeserver = &domain($dom,'primary');
10359:     }
10360:     unless ($homeserver eq 'no_host') {
10361:         my $customdata;
10362:         if (ref($custominfo) eq 'HASH') {
10363:             $customdata = &freeze_escape($custominfo);
10364:         }
10365:         $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
10366:                                     ':'.&escape($crstype).':'.&escape($inststatuslist).
10367:                                     ':'.&escape($instcode).':'.&escape($instseclist).':'.
10368:                                     $customdata,$homeserver));
10369:     }
10370:     return $response;
10371: }
10372: 
10373: sub auto_validate_class_sec {
10374:     my ($cdom,$cnum,$owners,$inst_class) = @_;
10375:     my $homeserver = &homeserver($cnum,$cdom);
10376:     my $ownerlist;
10377:     if (ref($owners) eq 'ARRAY') {
10378:         $ownerlist = join(',',@{$owners});
10379:     } else {
10380:         $ownerlist = $owners;
10381:     }
10382:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
10383:                         &escape($ownerlist).':'.$cdom,$homeserver);
10384:     return $response;
10385: }
10386: 
10387: sub auto_instsec_reformat {
10388:     my ($cdom,$action,$instsecref) = @_;
10389:     return unless(($action eq 'clutter') || ($action eq 'declutter'));
10390:     my @homeservers;
10391:     if (defined(&domain($cdom,'primary'))) {
10392:         push(@homeservers,&domain($cdom,'primary'));
10393:     } else {
10394:         my %servers = &get_servers($cdom,'library');
10395:         foreach my $tryserver (keys(%servers)) {
10396:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
10397:                 push(@homeservers,$tryserver);
10398:             }
10399:         }
10400:     }
10401:     my $response;
10402:     my %reformatted = %{$instsecref};
10403:     foreach my $server (@homeservers) {
10404:         if (ref($instsecref) eq 'HASH') {
10405:             my $info = &freeze_escape($instsecref);
10406:             my $response=&reply('autoinstsecreformat:'.$cdom.':'.
10407:                                 $action.':'.$info,$server);
10408:             next if ($response =~ /(con_lost|error|no_such_host|refused|unknown_command)/);
10409:             my @items = split(/&/,$response);
10410:             foreach my $item (@items) {
10411:                 my ($key,$value) = split(/=/,$item);
10412:                 $reformatted{&unescape($key)} = &thaw_unescape($value);
10413:             }
10414:         }
10415:     }
10416:     return %reformatted;
10417: }
10418: 
10419: sub auto_validate_instclasses {
10420:     my ($cdom,$cnum,$owners,$classesref) = @_;
10421:     my ($homeserver,%validations);
10422:     $homeserver = &homeserver($cnum,$cdom);
10423:     unless ($homeserver eq 'no_host') {
10424:         my $ownerlist;
10425:         if (ref($owners) eq 'ARRAY') {
10426:             $ownerlist = join(',',@{$owners});
10427:         } else {
10428:             $ownerlist = $owners;
10429:         }
10430:         if (ref($classesref) eq 'HASH') {
10431:             my $classes = &freeze_escape($classesref);
10432:             my $response=&reply('autovalidateinstclasses:'.&escape($ownerlist).
10433:                                 ':'.$cdom.':'.$classes,$homeserver);
10434:             unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
10435:                 my @items = split(/&/,$response);
10436:                 foreach my $item (@items) {
10437:                     my ($key,$value) = split('=',$item);
10438:                     $validations{&unescape($key)} = &thaw_unescape($value);
10439:                 }
10440:             }
10441:         }
10442:     }
10443:     return %validations;
10444: }
10445: 
10446: sub auto_crsreq_update {
10447:     my ($cdom,$cnum,$crstype,$action,$ownername,$ownerdomain,$fullname,$title,
10448:         $code,$accessstart,$accessend,$inbound) = @_;
10449:     my ($homeserver,%crsreqresponse);
10450:     if ($cdom =~ /^$match_domain$/) {
10451:         $homeserver = &domain($cdom,'primary');
10452:     }
10453:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
10454:         my $info;
10455:         if (ref($inbound) eq 'HASH') {
10456:             $info = &freeze_escape($inbound);
10457:         }
10458:         my $response=&reply('autocrsrequpdate:'.$cdom.':'.$cnum.':'.&escape($crstype).
10459:                             ':'.&escape($action).':'.&escape($ownername).':'.
10460:                             &escape($ownerdomain).':'.&escape($fullname).':'.
10461:                             &escape($title).':'.&escape($code).':'.
10462:                             &escape($accessstart).':'.&escape($accessend).':'.$info,
10463:                             $homeserver);
10464:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
10465:             my @items = split(/&/,$response);
10466:             foreach my $item (@items) {
10467:                 my ($key,$value) = split('=',$item);
10468:                 $crsreqresponse{&unescape($key)} = &thaw_unescape($value);
10469:             }
10470:         }
10471:     }
10472:     return \%crsreqresponse;
10473: }
10474: 
10475: sub auto_export_grades {
10476:     my ($cdom,$cnum,$inforef,$gradesref) = @_;
10477:     my ($homeserver,%exportresponse);
10478:     if ($cdom =~ /^$match_domain$/) {
10479:         $homeserver = &domain($cdom,'primary');
10480:     }
10481:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
10482:         my $info;
10483:         if (ref($inforef) eq 'HASH') {
10484:             $info = &freeze_escape($inforef);
10485:         }
10486:         if (ref($gradesref) eq 'HASH') {
10487:             my $grades = &freeze_escape($gradesref);
10488:             my $response=&reply('encrypt:autoexportgrades:'.$cdom.':'.$cnum.':'.
10489:                                 $info.':'.$grades,$homeserver);
10490:             unless ($response =~ /(con_lost|error|no_such_host|refused|unknown_command)/) {
10491:                 my @items = split(/&/,$response);
10492:                 foreach my $item (@items) {
10493:                     my ($key,$value) = split('=',$item);
10494:                     $exportresponse{&unescape($key)} = &thaw_unescape($value);
10495:                 }
10496:             }
10497:         }
10498:     }
10499:     return \%exportresponse;
10500: }
10501: 
10502: sub check_instcode_cloning {
10503:     my ($codedefaults,$code_order,$cloner,$clonefromcode,$clonetocode) = @_;
10504:     unless ((ref($codedefaults) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
10505:         return;
10506:     }
10507:     my $canclone;
10508:     if (@{$code_order} > 0) {
10509:         my $instcoderegexp ='^';
10510:         my @clonecodes = split(/\&/,$cloner);
10511:         foreach my $item (@{$code_order}) {
10512:             if (grep(/^\Q$item\E=/,@clonecodes)) {
10513:                 foreach my $pair (@clonecodes) {
10514:                     my ($key,$val) = split(/\=/,$pair,2);
10515:                     $val = &unescape($val);
10516:                     if ($key eq $item) {
10517:                         $instcoderegexp .= '('.$val.')';
10518:                         last;
10519:                     }
10520:                 }
10521:             } else {
10522:                 $instcoderegexp .= $codedefaults->{$item};
10523:             }
10524:         }
10525:         $instcoderegexp .= '$';
10526:         my (@from,@to);
10527:         eval {
10528:                (@from) = ($clonefromcode =~ /$instcoderegexp/);
10529:                (@to) = ($clonetocode =~ /$instcoderegexp/);
10530:         };
10531:         if ((@from > 0) && (@to > 0)) {
10532:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
10533:             if (!@diffs) {
10534:                 $canclone = 1;
10535:             }
10536:         }
10537:     }
10538:     return $canclone;
10539: }
10540: 
10541: sub default_instcode_cloning {
10542:     my ($clonedom,$domdefclone,$clonefromcode,$clonetocode,$codedefaultsref,$codeorderref) = @_;
10543:     my (%codedefaults,@code_order,$canclone);
10544:     if ((ref($codedefaultsref) eq 'HASH') && (ref($codeorderref) eq 'ARRAY')) {
10545:         %codedefaults = %{$codedefaultsref};
10546:         @code_order = @{$codeorderref};
10547:     } elsif ($clonedom) {
10548:         &auto_instcode_defaults($clonedom,\%codedefaults,\@code_order);
10549:     }
10550:     if (($domdefclone) && (@code_order)) {
10551:         my @clonecodes = split(/\+/,$domdefclone);
10552:         my $instcoderegexp ='^';
10553:         foreach my $item (@code_order) {
10554:             if (grep(/^\Q$item\E$/,@clonecodes)) {
10555:                 $instcoderegexp .= '('.$codedefaults{$item}.')';
10556:             } else {
10557:                 $instcoderegexp .= $codedefaults{$item};
10558:             }
10559:         }
10560:         $instcoderegexp .= '$';
10561:         my (@from,@to);
10562:         eval {
10563:             (@from) = ($clonefromcode =~ /$instcoderegexp/);
10564:             (@to) = ($clonetocode =~ /$instcoderegexp/);
10565:         };
10566:         if ((@from > 0) && (@to > 0)) {
10567:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
10568:             if (!@diffs) {
10569:                 $canclone = 1;
10570:             }
10571:         }
10572:     }
10573:     return $canclone;
10574: }
10575: 
10576: # ------------------------------------------------------- Course Group routines
10577: 
10578: sub get_coursegroups {
10579:     my ($cdom,$cnum,$group,$namespace) = @_;
10580:     return(&dump($namespace,$cdom,$cnum,$group));
10581: }
10582: 
10583: sub modify_coursegroup {
10584:     my ($cdom,$cnum,$groupsettings) = @_;
10585:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
10586: }
10587: 
10588: sub toggle_coursegroup_status {
10589:     my ($cdom,$cnum,$group,$action) = @_;
10590:     my ($from_namespace,$to_namespace);
10591:     if ($action eq 'delete') {
10592:         $from_namespace = 'coursegroups';
10593:         $to_namespace = 'deleted_groups';
10594:     } else {
10595:         $from_namespace = 'deleted_groups';
10596:         $to_namespace = 'coursegroups';
10597:     }
10598:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
10599:     if (my $tmp = &error(%curr_group)) {
10600:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
10601:         return ('read error',$tmp);
10602:     } else {
10603:         my %savedsettings = %curr_group; 
10604:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
10605:         my $deloutcome;
10606:         if ($result eq 'ok') {
10607:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
10608:         } else {
10609:             return ('write error',$result);
10610:         }
10611:         if ($deloutcome eq 'ok') {
10612:             return 'ok';
10613:         } else {
10614:             return ('delete error',$deloutcome);
10615:         }
10616:     }
10617: }
10618: 
10619: sub modify_group_roles {
10620:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context,
10621:         $othdomby,$requester) = @_;
10622:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
10623:     my $role = 'gr/'.&escape($userprivs);
10624:     my ($uname,$udom) = split(/:/,$user);
10625:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context,
10626:                              $othdomby,$requester);
10627:     if ($result eq 'ok') {
10628:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
10629:     }
10630:     return $result;
10631: }
10632: 
10633: sub modify_coursegroup_membership {
10634:     my ($cdom,$cnum,$membership) = @_;
10635:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
10636:     return $result;
10637: }
10638: 
10639: sub get_active_groups {
10640:     my ($udom,$uname,$cdom,$cnum) = @_;
10641:     my $now = time;
10642:     my %groups = ();
10643:     foreach my $key (keys(%env)) {
10644:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
10645:             my ($start,$end) = split(/\./,$env{$key});
10646:             if (($end!=0) && ($end<$now)) { next; }
10647:             if (($start!=0) && ($start>$now)) { next; }
10648:             if ($1 eq $cdom && $2 eq $cnum) {
10649:                 $groups{$3} = $env{$key} ;
10650:             }
10651:         }
10652:     }
10653:     return %groups;
10654: }
10655: 
10656: sub get_group_membership {
10657:     my ($cdom,$cnum,$group) = @_;
10658:     return(&dump('groupmembership',$cdom,$cnum,$group));
10659: }
10660: 
10661: sub get_users_groups {
10662:     my ($udom,$uname,$courseid) = @_;
10663:     my @usersgroups;
10664:     my $cachetime=1800;
10665: 
10666:     my $hashid="$udom:$uname:$courseid";
10667:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
10668:     if (defined($cached)) {
10669:         @usersgroups = split(/:/,$grouplist);
10670:     } else {  
10671:         $grouplist = '';
10672:         my $courseurl = &courseid_to_courseurl($courseid);
10673:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
10674:         my $access_end = $env{'course.'.$courseid.
10675:                               '.default_enrollment_end_date'};
10676:         my $now = time;
10677:         foreach my $key (keys(%roleshash)) {
10678:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
10679:                 my $group = $1;
10680:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
10681:                     my $start = $2;
10682:                     my $end = $1;
10683:                     if ($start == -1) { next; } # deleted from group
10684:                     if (($start!=0) && ($start>$now)) { next; }
10685:                     if (($end!=0) && ($end<$now)) {
10686:                         if ($access_end && $access_end < $now) {
10687:                             if ($access_end - $end < 86400) {
10688:                                 push(@usersgroups,$group);
10689:                             }
10690:                         }
10691:                         next;
10692:                     }
10693:                     push(@usersgroups,$group);
10694:                 }
10695:             }
10696:         }
10697:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
10698:         $grouplist = join(':',@usersgroups);
10699:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
10700:     }
10701:     return @usersgroups;
10702: }
10703: 
10704: sub devalidate_getgroups_cache {
10705:     my ($udom,$uname,$cdom,$cnum)=@_;
10706:     my $courseid = $cdom.'_'.$cnum;
10707: 
10708:     my $hashid="$udom:$uname:$courseid";
10709:     &devalidate_cache_new('getgroups',$hashid);
10710: }
10711: 
10712: # ------------------------------------------------------------------ Plain Text
10713: 
10714: sub plaintext {
10715:     my ($short,$type,$cid,$forcedefault) = @_;
10716:     if ($short =~ m{^cr/}) {
10717: 	return (split('/',$short))[-1];
10718:     }
10719:     if (!defined($cid)) {
10720:         $cid = $env{'request.course.id'};
10721:     }
10722:     my %rolenames = (
10723:                       Course    => 'std',
10724:                       Community => 'alt1',
10725:                       Placement => 'std',
10726:                     );
10727:     if ($cid ne '') {
10728:         if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
10729:             unless ($forcedefault) {
10730:                 my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
10731:                 &Apache::lonlocal::mt_escape(\$roletext);
10732:                 return &Apache::lonlocal::mt($roletext);
10733:             }
10734:         }
10735:     }
10736:     if ((defined($type)) && (defined($rolenames{$type})) &&
10737:         (defined($rolenames{$type})) && 
10738:         (defined($prp{$short}{$rolenames{$type}}))) {
10739:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
10740:     } elsif ($cid ne '') {
10741:         my $crstype = $env{'course.'.$cid.'.type'};
10742:         if (($crstype ne '') && (defined($rolenames{$crstype})) &&
10743:             (defined($prp{$short}{$rolenames{$crstype}}))) {
10744:             return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
10745:         }
10746:     }
10747:     return &Apache::lonlocal::mt($prp{$short}{'std'});
10748: }
10749: 
10750: # ----------------------------------------------------------------- Assign Role
10751: 
10752: sub assignrole {
10753:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
10754:         $context,$othdomby,$requester,$reqsec,$reqrole)=@_;
10755:     my ($mrole,$rolelogcontext);
10756:     if ($role =~ /^cr\//) {
10757:         my $cwosec=$url;
10758:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
10759:         if ((!&allowed('ccr',$cwosec)) && (!&allowed('ccr',$udom))) {
10760:             my $refused = 1;
10761:             if ($context eq 'requestcourses') {
10762:                 if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
10763:                     if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
10764:                         if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
10765:                             my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
10766:                             my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
10767:                             if ($crsenv{'internal.courseowner'} eq
10768:                                 $env{'user.name'}.':'.$env{'user.domain'}) {
10769:                                 $refused = '';
10770:                             }
10771:                         }
10772:                     }
10773:                 }
10774:             } elsif (($context eq 'course') && ($othdomby eq 'othdombyuser')) {
10775:                 my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
10776:                 my ($sec) = ($url =~ m{^/\Q$cwosec\E/(.*)$});
10777:                 my $key = "$uname:$udom:$role:$sec";
10778:                 my %queuedrolereq = &Apache::lonnet::get('nohist_othdomqueued',[$key],$cdom,$cnum);
10779:                 if ((exists($queuedrolereq{$key})) && (ref($queuedrolereq{$key}) eq 'HASH')) {
10780:                     if (($queuedrolereq{$key}{'adj'} eq 'user') && ($queuedrolereq{$key}{'requester'} eq $requester)) {
10781:                         $refused = '';
10782:                     }
10783:                 }
10784:             }
10785:             if ($refused) {
10786:                 &logthis('Refused custom assignrole: '.
10787:                          $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
10788:                          ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
10789:                 return 'refused';
10790:             }
10791:         }
10792:         $mrole='cr';
10793:     } elsif ($role =~ /^gr\//) {
10794:         my $cwogrp=$url;
10795:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
10796:         if (!&allowed('mdg',$cwogrp)) {
10797:             my $refused = 1;
10798:             if (($refused) && ($othdomby eq 'othdombyuser') && ($requester ne '') && ($reqrole ne '')) {
10799:                 my ($cdom,$cnum) = ($cwogrp =~ m{^/?($match_domain)/($match_courseid)$});
10800:                 my $key = "$uname:$udom:$reqrole:$reqsec";
10801:                 my %queuedrolereq = &Apache::lonnet::get('nohist_othdomqueued',[$key],$cdom,$cnum);
10802:                 if ((exists($queuedrolereq{$key})) && (ref($queuedrolereq{$key}) eq 'HASH')) {
10803:                     if (($queuedrolereq{$key}{'adj'} eq 'user') && ($queuedrolereq{$key}{'requester'} eq $requester)) {
10804:                         $refused = '';
10805:                     }
10806:                 }
10807:             }
10808:             if ($refused) {
10809:                 &logthis('Refused group assignrole: '.
10810:                          $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
10811:                          $env{'user.name'}.' at '.$env{'user.domain'});
10812:                 return 'refused';
10813:             }
10814:         }
10815:         $mrole='gr';
10816:     } else {
10817:         my $cwosec=$url;
10818:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
10819:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
10820:             my $refused;
10821:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
10822:                 if (!(&allowed('c'.$role,$url))) {
10823:                     $refused = 1;
10824:                 }
10825:             } else {
10826:                 $refused = 1;
10827:             }
10828:             if ($refused) {
10829:                 my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
10830:                 if (!$selfenroll && ($othdomby ne 'othdombyuser') &&
10831:                    (($context eq 'course') || ($context eq 'ltienroll' && $env{'request.lti.login'}))) {
10832:                     my %crsenv;
10833:                     if ($role eq 'cc' || $role eq 'co') {
10834:                         %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
10835:                         if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
10836:                             if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
10837:                                 if ($crsenv{'internal.courseowner'} eq 
10838:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
10839:                                     $refused = '';
10840:                                 }
10841:                             }
10842:                         } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) { 
10843:                             if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
10844:                                 if ($crsenv{'internal.courseowner'} eq 
10845:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
10846:                                     $refused = '';
10847:                                 }
10848:                             }
10849:                         }
10850:                     }
10851:                 } elsif (($selfenroll == 1) && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
10852:                     if ($role eq 'st') {
10853:                         $refused = '';
10854:                     } elsif (($context eq 'ltienroll') && ($env{'request.lti.login'})) {
10855:                         $refused = '';
10856:                     }
10857:                 } elsif ($othdomby eq 'othdombyuser') {
10858:                     my ($key,%queuedrolereq);
10859:                     if ($context eq 'course') {
10860:                         my ($sec) = ($url =~ m{^/\Q$cwosec\E/(.*)$});
10861:                         $key = "$uname:$udom:$role:$sec";
10862:                         %queuedrolereq = &Apache::lonnet::get('nohist_othdomqueued',[$key],$cdom,$cnum);
10863:                         if ((exists($queuedrolereq{$key})) && (ref($queuedrolereq{$key}) eq 'HASH')) {
10864:                             if (($queuedrolereq{$key}{'adj'} eq 'user') && ($queuedrolereq{$key}{'requester'} eq $requester)) {
10865:                                 if ((($role eq 'cc') && ($cnum !~ /^$match_community$/)) || 
10866:                                     (($role eq 'co') && ($cnum =~ /^$match_community$/))) {
10867:                                     my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
10868:                                     if ($crsenv{'internal.courseowner'} eq $requester) {
10869:                                         $refused = '';
10870:                                     }
10871:                                 } elsif ($role =~ /^(?:in|ta|ep|st)$/) {
10872:                                     $refused = '';
10873:                                 }
10874:                             }
10875:                         }
10876:                     } elsif (($context eq 'author') && ($role =~ /^ca|aa$/)) {
10877:                         my $key = "$uname:$udom:$role"; 
10878:                         my ($audom,$auname) = ($url =~ m{^/($match_domain)/($match_username)$});
10879:                         if (($audom ne '') && ($auname ne '')) {
10880:                             my %queuedrolereq = &Apache::lonnet::get('nohist_othdomqueued',[$key],$audom,$auname);
10881:                             if ((exists($queuedrolereq{$key})) && (ref($queuedrolereq{$key}) eq 'HASH')) {
10882:                                 if (($queuedrolereq{$key}{'adj'} eq 'user') && ($queuedrolereq{$key}{'requester'} eq $requester)) {
10883:                                     $refused = '';
10884:                                 }
10885:                             }
10886:                         }
10887:                     } elsif (($context eq 'domain') && ($role ne 'dc') && ($role ne 'su')) {
10888:                         my $key = "$uname:$udom:$role";
10889:                         my ($roledom) = ($url =~ m{^/($match_domain)/\Q$role\E$});
10890:                         if ($roledom ne '') {
10891:                             my $confname = $roledom.'-domainconfig';
10892:                             my %queuedrolereq = &Apache::lonnet::get('nohist_othdomqueued',[$key],$roledom,$confname);
10893:                             if ((exists($queuedrolereq{$key})) && (ref($queuedrolereq{$key}) eq 'HASH')) {
10894:                                 if (($queuedrolereq{$key}{'adj'} eq 'user') && ($queuedrolereq{$key}{'requester'} eq $requester)) {
10895:                                     $refused = '';
10896:                                 }
10897:                             }
10898:                         }
10899:                     }
10900:                 } elsif ($context eq 'requestcourses') {
10901:                     my @possroles = ('st','ta','ep','in','cc','co');
10902:                     if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
10903:                         my $wrongcc;
10904:                         if ($cnum =~ /^$match_community$/) {
10905:                             $wrongcc = 1 if ($role eq 'cc');
10906:                         } else {
10907:                             $wrongcc = 1 if ($role eq 'co');
10908:                         }
10909:                         unless ($wrongcc) {
10910:                             my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
10911:                             if ($crsenv{'internal.courseowner'} eq 
10912:                                  $env{'user.name'}.':'.$env{'user.domain'}) {
10913:                                 $refused = '';
10914:                             }
10915:                         }
10916:                     }
10917:                 } elsif ($context eq 'requestauthor') {
10918:                     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) && 
10919:                         ($url eq '/'.$udom.'/') && ($role eq 'au')) {
10920:                         if ($env{'environment.requestauthor'} eq 'automatic') {
10921:                             $refused = '';
10922:                         } else {
10923:                             my %domdefaults = &get_domain_defaults($udom);
10924:                             if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
10925:                                 my $checkbystatus;
10926:                                 if ($env{'user.adv'}) { 
10927:                                     my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
10928:                                     if ($disposition eq 'automatic') {
10929:                                         $refused = '';
10930:                                     } elsif ($disposition eq '') {
10931:                                         $checkbystatus = 1;
10932:                                     } 
10933:                                 } else {
10934:                                     $checkbystatus = 1;
10935:                                 }
10936:                                 if ($checkbystatus) {
10937:                                     if ($env{'environment.inststatus'}) {
10938:                                         my @inststatuses = split(/,/,$env{'environment.inststatus'});
10939:                                         foreach my $type (@inststatuses) {
10940:                                             if (($type ne '') &&
10941:                                                 ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
10942:                                                 $refused = '';
10943:                                             }
10944:                                         }
10945:                                     } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
10946:                                         $refused = '';
10947:                                     }
10948:                                 }
10949:                             }
10950:                         }
10951:                     }
10952:                 } elsif (($context eq 'author') && (($role eq 'ca' || $role eq 'aa'))) {
10953:                     if ($url =~ m{^/($match_domain)/($match_username)$}) {
10954:                         my ($audom,$auname) = ($1,$2);
10955:                         if ((&Apache::lonnet::allowed('v'.$role,"$audom/$auname")) &&
10956:                             ($env{"environment.internal.manager.$url"})) {
10957:                             $refused = '';
10958:                             $rolelogcontext = 'coauthor';
10959:                         }
10960:                     }
10961:                 }
10962:                 if ($refused) {
10963:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
10964:                              ' '.$role.' '.$end.' '.$start.' by '.
10965: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
10966:                     return 'refused';
10967:                 }
10968:             }
10969:         } elsif ($role eq 'au') {
10970:             if ($url ne '/'.$udom.'/') {
10971:                 &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
10972:                          ' to assign author role for '.$uname.':'.$udom.
10973:                          ' in domain: '.$url.' refused (wrong domain).');
10974:                 return 'refused';
10975:             }
10976:         }
10977:         $mrole=$role;
10978:     }
10979:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
10980:                 "$udom:$uname:$url".'_'."$mrole=$role";
10981:     if ($end) { $command.='_'.$end; }
10982:     if ($start) {
10983: 	if ($end) { 
10984:            $command.='_'.$start; 
10985:         } else {
10986:            $command.='_0_'.$start;
10987:         }
10988:     }
10989:     my $origstart = $start;
10990:     my $origend = $end;
10991:     my $delflag;
10992: # actually delete
10993:     if ($deleteflag) {
10994: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
10995: # modify command to delete the role
10996:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
10997:                 "$udom:$uname:$url".'_'."$mrole";
10998: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
10999: # set start and finish to negative values for userrolelog
11000:            $start=-1;
11001:            $end=-1;
11002:            $delflag = 1;
11003:         }
11004:     }
11005: # send command
11006:     my $answer=&reply($command,&homeserver($uname,$udom));
11007: # log new user role if status is ok
11008:     if ($answer eq 'ok') {
11009: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
11010:         if (($role eq 'cc') || ($role eq 'in') ||
11011:             ($role eq 'ep') || ($role eq 'ad') ||
11012:             ($role eq 'ta') || ($role eq 'st') ||
11013:             ($role=~/^cr/) || ($role eq 'gr') ||
11014:             ($role eq 'co')) {
11015: # for course roles, perform group memberships changes triggered by role change.
11016:             unless ($role =~ /^gr/) {
11017:                 &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
11018:                                                  $origstart,$selfenroll,$context);
11019:             }
11020:             &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
11021:                            $selfenroll,$context,$othdomby,$requester);
11022:         } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
11023:                  ($role eq 'au') || ($role eq 'dc') || ($role eq 'dh') ||
11024:                  ($role eq 'da')) {
11025:             &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
11026:                            $context,$othdomby,$requester);
11027:         } elsif (($role eq 'ca') || ($role eq 'aa')) {
11028:             if ($rolelogcontext eq '') {
11029:                 $rolelogcontext = $context;
11030:             }
11031:             &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
11032:                              $rolelogcontext,$othdomby,$requester); 
11033:         }
11034:         if ($role eq 'cc') {
11035:             &autoupdate_coowners($url,$end,$start,$uname,$udom);
11036:         }
11037:     }
11038:     return $answer;
11039: }
11040: 
11041: sub autoupdate_coowners {
11042:     my ($url,$end,$start,$uname,$udom) = @_;
11043:     my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
11044:     if (($cdom ne '') && ($cnum ne '')) {
11045:         my $now = time;
11046:         my %domdesign = &Apache::loncommon::get_domainconf($cdom);
11047:         if ($domdesign{$cdom.'.autoassign.co-owners'}) {
11048:             my %coursehash = &coursedescription($cdom.'_'.$cnum);
11049:             my $instcode = $coursehash{'internal.coursecode'};
11050:             my $xlists = $coursehash{'internal.crosslistings'};
11051:             if ($instcode ne '') {
11052:                 if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
11053:                     unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
11054:                         my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
11055:                         my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
11056:                         unless ($result eq 'valid') {
11057:                             if ($xlists ne '') {
11058:                                 foreach my $xlist (split(',',$xlists)) {
11059:                                     my ($inst_crosslist,$lcsec) = split(':',$xlist);
11060:                                     $result =
11061:                                         &auto_validate_inst_crosslist($cnum,$cdom,$instcode,
11062:                                                                       $inst_crosslist,$uname.':'.$udom);
11063:                                     last if ($result eq 'valid');
11064:                                 }
11065:                             }
11066:                         }
11067:                         if ($result eq 'valid') {
11068:                             if ($coursehash{'internal.co-owners'}) {
11069:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
11070:                                     push(@newcoowners,$coowner);
11071:                                 }
11072:                                 unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
11073:                                     push(@newcoowners,$uname.':'.$udom);
11074:                                 }
11075:                                 @newcoowners = sort(@newcoowners);
11076:                             } else {
11077:                                 push(@newcoowners,$uname.':'.$udom);
11078:                             }
11079:                         } elsif ($coursehash{'internal.co-owners'}) {
11080:                             foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
11081:                                 unless ($coowner eq $uname.':'.$udom) {
11082:                                     push(@newcoowners,$coowner);
11083:                                 }
11084:                             }
11085:                             unless (@newcoowners > 0) {
11086:                                 $delcoowners = 1;
11087:                                 $coowners = '';
11088:                             }
11089:                         }
11090:                         if (@newcoowners || $delcoowners) {
11091:                             &store_coowners($cdom,$cnum,$coursehash{'home'},
11092:                                             $delcoowners,@newcoowners);
11093:                         }
11094:                     }
11095:                 }
11096:             }
11097:         }
11098:     }
11099: }
11100: 
11101: sub store_coowners {
11102:     my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
11103:     my $cid = $cdom.'_'.$cnum;
11104:     my ($coowners,$delresult,$putresult);
11105:     if (@newcoowners) {
11106:         $coowners = join(',',@newcoowners);
11107:         my %coownershash = (
11108:                             'internal.co-owners' => $coowners,
11109:                            );
11110:         $putresult = &put('environment',\%coownershash,$cdom,$cnum);
11111:         if ($putresult eq 'ok') {
11112:             if ($env{'course.'.$cid.'.num'} eq $cnum) {
11113:                 &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
11114:             }
11115:         }
11116:     }
11117:     if ($delcoowners) {
11118:         $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
11119:         if ($delresult eq 'ok') {
11120:             if ($env{'course.'.$cid.'.internal.co-owners'}) {
11121:                 &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
11122:             }
11123:         }
11124:     }
11125:     if (($putresult eq 'ok') || ($delresult eq 'ok')) {
11126:         my %crsinfo =
11127:             &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
11128:         if (ref($crsinfo{$cid}) eq 'HASH') {
11129:             $crsinfo{$cid}{'co-owners'} = \@newcoowners;
11130:             my $cidput = &courseidput($cdom,\%crsinfo,$chome,'notime');
11131:         }
11132:     }
11133: }
11134: 
11135: # -------------------------------------------------- Modify user authentication
11136: # Overrides without validation
11137: 
11138: sub modifyuserauth {
11139:     my ($udom,$uname,$umode,$upass)=@_;
11140:     my $uhome=&homeserver($uname,$udom);
11141:     my $allowed;
11142:     if (&allowed('mau',$udom)) {
11143:         $allowed = 1;
11144:     } elsif (($umode eq 'internal') && ($udom eq $env{'user.domain'}) &&
11145:              ($env{'request.course.id'}) && (&allowed('mip',$env{'request.course.id'})) &&
11146:              (!$env{'course.'.$env{'request.course.id'}.'.internal.nopasswdchg'})) {
11147:         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
11148:         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
11149:         if (($cdom ne '') && ($cnum ne '')) {
11150:             my $is_owner = &is_course_owner($cdom,$cnum);
11151:             if ($is_owner) {
11152:                 $allowed = 1;
11153:             }
11154:         }
11155:     }
11156:     unless ($allowed) { return 'refused'; }
11157:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
11158:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
11159:              ' in domain '.$env{'request.role.domain'});  
11160:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
11161: 		     &escape($upass),$uhome);
11162:     my $ip = &get_requestor_ip();
11163:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
11164:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
11165:          '(Remote '.$ip.'): '.$reply);
11166:     &log($udom,,$uname,$uhome,
11167:         'Authentication changed by '.$env{'user.domain'}.', '.
11168:                                      $env{'user.name'}.', '.$umode.
11169:          '(Remote '.$ip.'): '.$reply);
11170:     unless ($reply eq 'ok') {
11171:         &logthis('Authentication mode error: '.$reply);
11172: 	return 'error: '.$reply;
11173:     }   
11174:     return 'ok';
11175: }
11176: 
11177: # --------------------------------------------------------------- Modify a user
11178: 
11179: sub modifyuser {
11180:     my ($udom,    $uname, $uid,
11181:         $umode,   $upass, $first,
11182:         $middle,  $last,  $gene,
11183:         $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
11184:     $udom= &LONCAPA::clean_domain($udom);
11185:     $uname=&LONCAPA::clean_username($uname);
11186:     my $showcandelete = 'none';
11187:     if (ref($candelete) eq 'ARRAY') {
11188:         if (@{$candelete} > 0) {
11189:             $showcandelete = join(', ',@{$candelete});
11190:         }
11191:     }
11192:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
11193:              $umode.', '.$first.', '.$middle.', '.
11194: 	     $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
11195:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
11196:                                      ' desiredhome not specified'). 
11197:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
11198:              ' in domain '.$env{'request.role.domain'});
11199:     my $uhome=&homeserver($uname,$udom,'true');
11200:     my $newuser;
11201:     if ($uhome eq 'no_host') {
11202:         $newuser = 1;
11203:         unless (($umode && ($upass ne '')) || ($umode eq 'localauth') ||
11204:                 ($umode eq 'lti')) {
11205:             return 'error: more information needed to create new user';
11206:         }
11207:     }
11208: # ----------------------------------------------------------------- Create User
11209:     if (($uhome eq 'no_host') && 
11210: 	(($umode && $upass) || ($umode eq 'localauth') || ($umode eq 'lti'))) {
11211:         my $unhome='';
11212:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
11213:             $unhome = $desiredhome;
11214: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
11215: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
11216:         } else { # load balancing routine for determining $unhome
11217:             my $loadm=10000000;
11218: 	    my %servers = &get_servers($udom,'library');
11219: 	    foreach my $tryserver (keys(%servers)) {
11220: 		my $answer=reply('load',$tryserver);
11221: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
11222: 		    $loadm=$answer;
11223: 		    $unhome=$tryserver;
11224: 		}
11225: 	    }
11226:         }
11227:         if (($unhome eq '') || ($unhome eq 'no_host')) {
11228: 	    return 'error: unable to find a home server for '.$uname.
11229:                    ' in domain '.$udom;
11230:         }
11231:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
11232:                          &escape($upass),$unhome);
11233: 	unless ($reply eq 'ok') {
11234:             return 'error: '.$reply;
11235:         }   
11236:         $uhome=&homeserver($uname,$udom,'true');
11237:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
11238: 	    return 'error: unable verify users home machine.';
11239:         }
11240:     }   # End of creation of new user
11241: # ---------------------------------------------------------------------- Add ID
11242:     if ($uid) {
11243:        $uid=~tr/A-Z/a-z/;
11244:        my %uidhash=&idrget($udom,$uname);
11245:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
11246:          && (!$forceid)) {
11247: 	  unless ($uid eq $uidhash{$uname}) {
11248: 	      return 'error: user id "'.$uid.'" does not match '.
11249:                   'current user id "'.$uidhash{$uname}.'".';
11250:           }
11251:        } else {
11252: 	  &idput($udom,{$uname => $uid},$uhome,'ids');
11253:        }
11254:     }
11255: # -------------------------------------------------------------- Add names, etc
11256:     my @tmp=&get('environment',
11257: 		   ['firstname','middlename','lastname','generation','id',
11258:                     'permanentemail','inststatus'],
11259: 		   $udom,$uname);
11260:     my (%names,%oldnames);
11261:     if ($tmp[0] =~ m/^error:.*/) { 
11262:         %names=(); 
11263:     } else {
11264:         %names = @tmp;
11265:         %oldnames = %names;
11266:     }
11267: #
11268: # If name, email and/or uid are blank (e.g., because an uploaded file
11269: # of users did not contain them), do not overwrite existing values
11270: # unless field is in $candelete array ref.  
11271: #
11272: 
11273:     my @fields = ('firstname','middlename','lastname','generation',
11274:                   'permanentemail','id');
11275:     my %newvalues;
11276:     if (ref($candelete) eq 'ARRAY') {
11277:         foreach my $field (@fields) {
11278:             if (grep(/^\Q$field\E$/,@{$candelete})) {
11279:                 if ($field eq 'firstname') {
11280:                     $names{$field} = $first;
11281:                 } elsif ($field eq 'middlename') {
11282:                     $names{$field} = $middle;
11283:                 } elsif ($field eq 'lastname') {
11284:                     $names{$field} = $last;
11285:                 } elsif ($field eq 'generation') { 
11286:                     $names{$field} = $gene;
11287:                 } elsif ($field eq 'permanentemail') {
11288:                     $names{$field} = $email;
11289:                 } elsif ($field eq 'id') {
11290:                     $names{$field}  = $uid;
11291:                 }
11292:             }
11293:         }
11294:     }
11295:     if ($first)  { $names{'firstname'}  = $first; }
11296:     if (defined($middle)) { $names{'middlename'} = $middle; }
11297:     if ($last)   { $names{'lastname'}   = $last; }
11298:     if (defined($gene))   { $names{'generation'} = $gene; }
11299:     if ($email) {
11300:        $email=~s/[^\w\@\.\-\,]//gs;
11301:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
11302:     }
11303:     if ($uid) { $names{'id'}  = $uid; }
11304:     if (defined($inststatus)) {
11305:         $names{'inststatus'} = '';
11306:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
11307:         if (ref($usertypes) eq 'HASH') {
11308:             my @okstatuses; 
11309:             foreach my $item (split(/:/,$inststatus)) {
11310:                 if (defined($usertypes->{$item})) {
11311:                     push(@okstatuses,$item);  
11312:                 }
11313:             }
11314:             if (@okstatuses) {
11315:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
11316:             }
11317:         }
11318:     }
11319:     my $logmsg = $udom.', '.$uname.', '.$uid.', '.
11320:                  $umode.', '.$first.', '.$middle.', '.
11321:                  $last.', '.$gene.', '.$email.', '.$inststatus;
11322:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
11323:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
11324:     } else {
11325:         $logmsg .= ' during self creation';
11326:     }
11327:     my $changed;
11328:     if ($newuser) {
11329:         $changed = 1;
11330:     } else {
11331:         foreach my $field (@fields) {
11332:             if ($names{$field} ne $oldnames{$field}) {
11333:                 $changed = 1;
11334:                 last;
11335:             }
11336:         }
11337:     }
11338:     unless ($changed) {
11339:         $logmsg = 'No changes in user information needed for: '.$logmsg;
11340:         &logthis($logmsg);
11341:         return 'ok';
11342:     }
11343:     my $reply = &put('environment', \%names, $udom,$uname);
11344:     if ($reply ne 'ok') { 
11345:         return 'error: '.$reply;
11346:     }
11347:     if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
11348:         &devalidate_cache_new('emailscache',$uname.':'.$udom);
11349:     }
11350:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
11351:     &devalidate_cache_new('namescache',$uname.':'.$udom);
11352:     $logmsg = 'Success modifying user '.$logmsg;
11353:     &logthis($logmsg);
11354:     return 'ok';
11355: }
11356: 
11357: # -------------------------------------------------------------- Modify student
11358: 
11359: sub modifystudent {
11360:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
11361:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
11362:         $selfenroll,$context,$inststatus,$credits,$instsec)=@_;
11363:     if (!$cid) {
11364: 	unless ($cid=$env{'request.course.id'}) {
11365: 	    return 'not_in_class';
11366: 	}
11367:     }
11368: # --------------------------------------------------------------- Make the user
11369:     my $reply=&modifyuser
11370: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
11371:          $desiredhome,$email,$inststatus);
11372:     unless ($reply eq 'ok') { return $reply; }
11373:     # This will cause &modify_student_enrollment to get the uid from the
11374:     # student's environment
11375:     $uid = undef if (!$forceid);
11376:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
11377:                                         $gene,$usec,$end,$start,$type,$locktype,
11378:                                         $cid,$selfenroll,$context,$credits,$instsec);
11379:     return $reply;
11380: }
11381: 
11382: sub modify_student_enrollment {
11383:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,
11384:         $locktype,$cid,$selfenroll,$context,$credits,$instsec,$othdomby,$requester) = @_;
11385:     my ($cdom,$cnum,$chome);
11386:     if (!$cid) {
11387: 	unless ($cid=$env{'request.course.id'}) {
11388: 	    return 'not_in_class';
11389: 	}
11390: 	$cdom=$env{'course.'.$cid.'.domain'};
11391: 	$cnum=$env{'course.'.$cid.'.num'};
11392:     } else {
11393: 	($cdom,$cnum)=split(/_/,$cid);
11394:     }
11395:     $chome=$env{'course.'.$cid.'.home'};
11396:     if (!$chome) {
11397: 	$chome=&homeserver($cnum,$cdom);
11398:     }
11399:     if (!$chome) { return 'unknown_course'; }
11400:     # Make sure the user exists
11401:     my $uhome=&homeserver($uname,$udom);
11402:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
11403: 	return 'error: no such user';
11404:     }
11405:     # Get student data if we were not given enough information
11406:     if (!defined($first)  || $first  eq '' || 
11407:         !defined($last)   || $last   eq '' || 
11408:         !defined($uid)    || $uid    eq '' || 
11409:         !defined($middle) || $middle eq '' || 
11410:         !defined($gene)   || $gene   eq '') {
11411:         # They did not supply us with enough data to enroll the student, so
11412:         # we need to pick up more information.
11413:         my %tmp = &get('environment',
11414:                        ['firstname','middlename','lastname', 'generation','id']
11415:                        ,$udom,$uname);
11416: 
11417:         #foreach my $key (keys(%tmp)) {
11418:         #    &logthis("key $key = ".$tmp{$key});
11419:         #}
11420:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
11421:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
11422:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
11423:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
11424:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
11425:     }
11426:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
11427:     my $user = "$uname:$udom";
11428:     my %old_entry = &get('classlist',[$user],$cdom,$cnum);
11429:     my $reply=cput('classlist',
11430: 		   {$user => 
11431: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits,$instsec) },
11432: 		   $cdom,$cnum);
11433:     if (($reply eq 'ok') || ($reply eq 'delayed')) {
11434:         &devalidate_getsection_cache($udom,$uname,$cid);
11435:     } else { 
11436: 	return 'error: '.$reply;
11437:     }
11438:     # Add student role to user
11439:     my $uurl='/'.$cid;
11440:     $uurl=~s/\_/\//g;
11441:     if ($usec) {
11442: 	$uurl.='/'.$usec;
11443:     }
11444:     my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
11445:                              $selfenroll,$context,$othdomby,$requester);
11446:     if ($result ne 'ok') {
11447:         if ($old_entry{$user} ne '') {
11448:             $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
11449:         } else {
11450:             $reply = &del('classlist',[$user],$cdom,$cnum);
11451:         }
11452:     }
11453:     return $result; 
11454: }
11455: 
11456: sub format_name {
11457:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
11458:     my $name;
11459:     if ($first ne 'lastname') {
11460: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
11461:     } else {
11462: 	if ($lastname=~/\S/) {
11463: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
11464: 	    $name=~s/\s+,/,/;
11465: 	} else {
11466: 	    $name.= $firstname.' '.$middlename.' '.$generation;
11467: 	}
11468:     }
11469:     $name=~s/^\s+//;
11470:     $name=~s/\s+$//;
11471:     $name=~s/\s+/ /g;
11472:     return $name;
11473: }
11474: 
11475: # ------------------------------------------------- Write to course preferences
11476: 
11477: sub writecoursepref {
11478:     my ($courseid,%prefs)=@_;
11479:     $courseid=~s/^\///;
11480:     $courseid=~s/\_/\//g;
11481:     my ($cdomain,$cnum)=split(/\//,$courseid);
11482:     my $chome=homeserver($cnum,$cdomain);
11483:     if (($chome eq '') || ($chome eq 'no_host')) { 
11484: 	return 'error: no such course';
11485:     }
11486:     my $cstring='';
11487:     foreach my $pref (keys(%prefs)) {
11488: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
11489:     }
11490:     $cstring=~s/\&$//;
11491:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
11492: }
11493: 
11494: # ---------------------------------------------------------- Make/modify course
11495: 
11496: sub createcourse {
11497:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
11498:         $course_owner,$crstype,$cnum,$context,$category,$callercontext)=@_;
11499:     $url=&declutter($url);
11500:     my $cid='';
11501:     if ($context eq 'requestcourses') {
11502:         my $can_create = 0;
11503:         my ($ownername,$ownerdom) = split(':',$course_owner);
11504:         if ($udom eq $ownerdom) {
11505:             my $reload;
11506:             if (($callercontext eq 'auto') &&
11507:                ($ownerdom eq $env{'user.domain'}) && ($ownername eq $env{'user.name'})) {
11508:                 $reload = 'reload';
11509:             }
11510:             if (&usertools_access($ownername,$ownerdom,$category,$reload,
11511:                                   $context)) {
11512:                 $can_create = 1;
11513:             }
11514:         } else {
11515:             my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
11516:                                            $category);
11517:             if ($userenv{'reqcrsotherdom.'.$category} ne '') {
11518:                 my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
11519:                 if (@curr > 0) {
11520:                     my @options = qw(approval validate autolimit);
11521:                     my $optregex = join('|',@options);
11522:                     if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
11523:                         $can_create = 1;
11524:                     }
11525:                 }
11526:             }
11527:         }
11528:         if ($can_create) {
11529:             unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
11530:                 unless (&allowed('ccc',$udom)) {
11531:                     return 'refused'; 
11532:                 }
11533:             }
11534:         } else {
11535:             return 'refused';
11536:         }
11537:     } elsif (!&allowed('ccc',$udom)) {
11538:         return 'refused';
11539:     }
11540: # --------------------------------------------------------------- Get Unique ID
11541:     my $uname;
11542:     if ($cnum =~ /^$match_courseid$/) {
11543:         my $chome=&homeserver($cnum,$udom,'true');
11544:         if (($chome eq '') || ($chome eq 'no_host')) {
11545:             $uname = $cnum;
11546:         } else {
11547:             $uname = &generate_coursenum($udom,$crstype);
11548:         }
11549:     } else {
11550:         $uname = &generate_coursenum($udom,$crstype);
11551:     }
11552:     return $uname if ($uname =~ /^error/);
11553: # -------------------------------------------------- Check supplied server name
11554:     if (!defined($course_server)) {
11555:         if (defined(&domain($udom,'primary'))) {
11556:             $course_server = &domain($udom,'primary');
11557:         } else {
11558:             $course_server = $env{'user.home'}; 
11559:         }
11560:     }
11561:     my %host_servers =
11562:         &get_servers($udom,'library');
11563:     unless ($host_servers{$course_server}) {
11564:         return 'error: invalid home server for course: '.$course_server;
11565:     }
11566: # ------------------------------------------------------------- Make the course
11567:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
11568:                       $course_server);
11569:     unless ($reply eq 'ok') { return 'error: '.$reply; }
11570:     my $uhome=&homeserver($uname,$udom,'true');
11571:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
11572: 	return 'error: no such course';
11573:     }
11574: # ----------------------------------------------------------------- Course made
11575: # log existence
11576:     my $now = time;
11577:     my $newcourse = {
11578:                     $udom.'_'.$uname => {
11579:                                      description => $description,
11580:                                      inst_code   => $inst_code,
11581:                                      owner       => $course_owner,
11582:                                      type        => $crstype,
11583:                                      creator     => $env{'user.name'}.':'.
11584:                                                     $env{'user.domain'},
11585:                                      created     => $now,
11586:                                      context     => $context,
11587:                                                 },
11588:                     };
11589:     &courseidput($udom,$newcourse,$uhome,'notime');
11590: # set toplevel url
11591:     my $topurl=$url;
11592:     unless ($nonstandard) {
11593: # ------------------------------------------ For standard courses, make top url
11594:         my $mapurl=&clutter($url);
11595:         if ($mapurl eq '/res/') { $mapurl=''; }
11596:         $env{'form.initmap'}=(<<ENDINITMAP);
11597: <map>
11598: <resource id="1" type="start"></resource>
11599: <resource id="2" src="$mapurl"></resource>
11600: <resource id="3" type="finish"></resource>
11601: <link index="1" from="1" to="2"></link>
11602: <link index="2" from="2" to="3"></link>
11603: </map>
11604: ENDINITMAP
11605:         $topurl=&declutter(
11606:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
11607:                           );
11608:     }
11609: # ----------------------------------------------------------- Write preferences
11610:     &writecoursepref($udom.'_'.$uname,
11611:                      ('description'              => $description,
11612:                       'url'                      => $topurl,
11613:                       'internal.creator'         => $env{'user.name'}.':'.
11614:                                                     $env{'user.domain'},
11615:                       'internal.created'         => $now,
11616:                       'internal.creationcontext' => $context)
11617:                     );
11618:     return '/'.$udom.'/'.$uname;
11619: }
11620: 
11621: # ------------------------------------------------------------------- Create ID
11622: sub generate_coursenum {
11623:     my ($udom,$crstype) = @_;
11624:     my $domdesc = &domain($udom);
11625:     return 'error: invalid domain' if ($domdesc eq '');
11626:     my $first;
11627:     if ($crstype eq 'Community') {
11628:         $first = '0';
11629:     } else {
11630:         $first = int(1+rand(9)); 
11631:     } 
11632:     my $uname=$first.
11633:         ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
11634:         substr($$.time,0,5).unpack("H8",pack("I32",time)).
11635:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
11636: # ----------------------------------------------- Make sure that does not exist
11637:     my $uhome=&homeserver($uname,$udom,'true');
11638:     unless (($uhome eq '') || ($uhome eq 'no_host')) {
11639:         if ($crstype eq 'Community') {
11640:             $first = '0';
11641:         } else {
11642:             $first = int(1+rand(9));
11643:         }
11644:         $uname=$first.
11645:                ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
11646:                substr($$.time,0,5).unpack("H8",pack("I32",time)).
11647:                unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
11648:         $uhome=&homeserver($uname,$udom,'true');
11649:         unless (($uhome eq '') || ($uhome eq 'no_host')) {
11650:             return 'error: unable to generate unique course-ID';
11651:         }
11652:     }
11653:     return $uname;
11654: }
11655: 
11656: sub is_course {
11657:     my ($cdom, $cnum) = scalar(@_) == 1 ? 
11658:          ($_[0] =~ /^($match_domain)_($match_courseid)$/)  :  @_;
11659: 
11660:     return unless (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/));
11661:     my $uhome=&homeserver($cnum,$cdom);
11662:     my $iscourse;
11663:     if (grep { $_ eq $uhome } current_machine_ids()) {
11664:         $iscourse = &LONCAPA::Lond::is_course($cdom,$cnum);
11665:     } else {
11666:         my $hashid = $cdom.':'.$cnum;
11667:         ($iscourse,my $cached) = &is_cached_new('iscourse',$hashid);
11668:         unless (defined($cached)) {
11669:             my %courses = &courseiddump($cdom, '.', 1, '.', '.',
11670:                                         $cnum,undef,undef,'.');
11671:             $iscourse = 0;
11672:             if (exists($courses{$cdom.'_'.$cnum})) {
11673:                 $iscourse = 1;
11674:             }
11675:             &do_cache_new('iscourse',$hashid,$iscourse,3600);
11676:         }
11677:     }
11678:     return unless ($iscourse);
11679:     return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
11680: }
11681: 
11682: sub store_userdata {
11683:     my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
11684:     my $result;
11685:     if ($datakey ne '') {
11686:         if (ref($storehash) eq 'HASH') {
11687:             if ($udom eq '' || $uname eq '') {
11688:                 $udom = $env{'user.domain'};
11689:                 $uname = $env{'user.name'};
11690:             }
11691:             my $uhome=&homeserver($uname,$udom);
11692:             if (($uhome eq '') || ($uhome eq 'no_host')) {
11693:                 $result = 'error: no_host';
11694:             } else {
11695:                 $storehash->{'ip'} = &get_requestor_ip();
11696:                 $storehash->{'host'} = $perlvar{'lonHostID'};
11697: 
11698:                 my $namevalue='';
11699:                 foreach my $key (keys(%{$storehash})) {
11700:                     $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
11701:                 }
11702:                 $namevalue=~s/\&$//;
11703:                 unless ($namespace eq 'courserequests') {
11704:                     $datakey = &escape($datakey);
11705:                 }
11706:                 $result =  &reply("store:$udom:$uname:$namespace:$datakey:".
11707:                                   $namevalue,$uhome);
11708:             }
11709:         } else {
11710:             $result = 'error: data to store was not a hash reference'; 
11711:         }
11712:     } else {
11713:         $result= 'error: invalid requestkey'; 
11714:     }
11715:     return $result;
11716: }
11717: 
11718: # ---------------------------------------------------------- Assign Custom Role
11719: 
11720: sub assigncustomrole {
11721:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,
11722:         $selfenroll,$context,$othdomby,$requester)=@_;
11723:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
11724:                        $end,$start,$deleteflag,$selfenroll,$context,$othdomby,
11725:                        $requester);
11726: }
11727: 
11728: # ----------------------------------------------------------------- Revoke Role
11729: 
11730: sub revokerole {
11731:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
11732:     my $now=time;
11733:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
11734: }
11735: 
11736: # ---------------------------------------------------------- Revoke Custom Role
11737: 
11738: sub revokecustomrole {
11739:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
11740:     my $now=time;
11741:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
11742:            $deleteflag,$selfenroll,$context);
11743: }
11744: 
11745: # ------------------------------------------------------------ Disk usage
11746: sub diskusage {
11747:     my ($udom,$uname,$directorypath,$getpropath)=@_;
11748:     $directorypath =~ s/\/$//;
11749:     my $listing=&reply('du2:'.&escape($directorypath).':'
11750:                        .&escape($getpropath).':'.&escape($uname).':'
11751:                        .&escape($udom),homeserver($uname,$udom));
11752:     if ($listing eq 'unknown_cmd') {
11753:         if ($getpropath) {
11754:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
11755:         }
11756:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
11757:     }
11758:     return $listing;
11759: }
11760: 
11761: sub is_locked {
11762:     my ($file_name, $domain, $user, $which) = @_;
11763:     my @check;
11764:     my $is_locked;
11765:     push (@check,$file_name);
11766:     my %locked = &get('file_permissions',\@check,
11767: 		      $env{'user.domain'},$env{'user.name'});
11768:     my ($tmp)=keys(%locked);
11769:     if ($tmp=~/^error:/) { undef(%locked); }
11770:     
11771:     if (ref($locked{$file_name}) eq 'ARRAY') {
11772:         $is_locked = 'false';
11773:         foreach my $entry (@{$locked{$file_name}}) {
11774:            if (ref($entry) eq 'ARRAY') {
11775:                $is_locked = 'true';
11776:                if (ref($which) eq 'ARRAY') {
11777:                    push(@{$which},$entry);
11778:                } else {
11779:                    last;
11780:                }
11781:            }
11782:        }
11783:     } else {
11784:         $is_locked = 'false';
11785:     }
11786:     return $is_locked;
11787: }
11788: 
11789: sub declutter_portfile {
11790:     my ($file) = @_;
11791:     $file =~ s{^(/portfolio/|portfolio/)}{/};
11792:     return $file;
11793: }
11794: 
11795: # ------------------------------------------------------------- Mark as Read Only
11796: 
11797: sub mark_as_readonly {
11798:     my ($domain,$user,$files,$what) = @_;
11799:     my %current_permissions = &dump('file_permissions',$domain,$user);
11800:     my ($tmp)=keys(%current_permissions);
11801:     if ($tmp=~/^error:/) { undef(%current_permissions); }
11802:     foreach my $file (@{$files}) {
11803: 	$file = &declutter_portfile($file);
11804:         push(@{$current_permissions{$file}},$what);
11805:     }
11806:     &put('file_permissions',\%current_permissions,$domain,$user);
11807:     return;
11808: }
11809: 
11810: # ------------------------------------------------------------Save Selected Files
11811: 
11812: sub save_selected_files {
11813:     my ($user, $path, @files) = @_;
11814:     my $filename = $user."savedfiles";
11815:     my @other_files = &files_not_in_path($user, $path);
11816:     open (OUT,'>',LONCAPA::tempdir().$filename);
11817:     foreach my $file (@files) {
11818:         print (OUT $env{'form.currentpath'}.$file."\n");
11819:     }
11820:     foreach my $file (@other_files) {
11821:         print (OUT $file."\n");
11822:     }
11823:     close (OUT);
11824:     return 'ok';
11825: }
11826: 
11827: sub clear_selected_files {
11828:     my ($user) = @_;
11829:     my $filename = $user."savedfiles";
11830:     open (OUT,'>',LONCAPA::tempdir().$filename);
11831:     print (OUT undef);
11832:     close (OUT);
11833:     return ("ok");    
11834: }
11835: 
11836: sub files_in_path {
11837:     my ($user, $path) = @_;
11838:     my $filename = $user."savedfiles";
11839:     my %return_files;
11840:     open (IN,'<',LONCAPA::tempdir().$filename);
11841:     while (my $line_in = <IN>) {
11842:         chomp ($line_in);
11843:         my @paths_and_file = split (m!/!, $line_in);
11844:         my $file_part = pop (@paths_and_file);
11845:         my $path_part = join ('/', @paths_and_file);
11846:         $path_part.='/';
11847:         my $path_and_file = $path_part.$file_part;
11848:         if ($path_part eq $path) {
11849:             $return_files{$file_part}= 'selected';
11850:         }
11851:     }
11852:     close (IN);
11853:     return (\%return_files);
11854: }
11855: 
11856: # called in portfolio select mode, to show files selected NOT in current directory
11857: sub files_not_in_path {
11858:     my ($user, $path) = @_;
11859:     my $filename = $user."savedfiles";
11860:     my @return_files;
11861:     my $path_part;
11862:     open(IN, '<',LONCAPA::tempdir().$filename);
11863:     while (my $line = <IN>) {
11864:         #ok, I know it's clunky, but I want it to work
11865:         my @paths_and_file = split(m|/|, $line);
11866:         my $file_part = pop(@paths_and_file);
11867:         chomp($file_part);
11868:         my $path_part = join('/', @paths_and_file);
11869:         $path_part .= '/';
11870:         my $path_and_file = $path_part.$file_part;
11871:         if ($path_part ne $path) {
11872:             push(@return_files, ($path_and_file));
11873:         }
11874:     }
11875:     close(OUT);
11876:     return (@return_files);
11877: }
11878: 
11879: #------------------------------Submitted/Handedback Portfolio Files Versioning
11880:  
11881: sub portfiles_versioning {
11882:     my ($symb,$domain,$stu_name,$portfiles,$versioned_portfiles) = @_;
11883:     my $portfolio_root = '/userfiles/portfolio';
11884:     return unless ((ref($portfiles) eq 'ARRAY') && (ref($versioned_portfiles) eq 'ARRAY'));
11885:     foreach my $file (@{$portfiles}) {
11886:         &unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
11887:         my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
11888:         my ($answer_name,$answer_ver,$answer_ext) = &file_name_version_ext($answer_file);
11889:         my $getpropath = 1;
11890:         my ($dir_list,$listerror) = &dirlist($portfolio_root.$directory,$domain,
11891:                                              $stu_name,$getpropath);
11892:         my $version = &get_next_version($answer_name,$answer_ext,$dir_list);
11893:         my $new_answer = 
11894:             &version_selected_portfile($domain,$stu_name,$directory,$answer_file,$version);
11895:         if ($new_answer ne 'problem getting file') {
11896:             push(@{$versioned_portfiles}, $directory.$new_answer);
11897:             &mark_as_readonly($domain,$stu_name,[$directory.$new_answer],
11898:                               [$symb,$env{'request.course.id'},'graded']);
11899:         }
11900:     }
11901: }
11902: 
11903: sub get_next_version {
11904:     my ($answer_name, $answer_ext, $dir_list) = @_;
11905:     my $version;
11906:     if (ref($dir_list) eq 'ARRAY') {
11907:         foreach my $row (@{$dir_list}) {
11908:             my ($file) = split(/\&/,$row,2);
11909:             my ($file_name,$file_version,$file_ext) =
11910:                 &file_name_version_ext($file);
11911:             if (($file_name eq $answer_name) &&
11912:                 ($file_ext eq $answer_ext)) {
11913:                      # gets here if filename and extension match,
11914:                      # regardless of version
11915:                 if ($file_version ne '') {
11916:                     # a versioned file is found  so save it for later
11917:                     if ($file_version > $version) {
11918:                         $version = $file_version;
11919:                     }
11920:                 }
11921:             }
11922:         }
11923:     }
11924:     $version ++;
11925:     return($version);
11926: }
11927: 
11928: sub version_selected_portfile {
11929:     my ($domain,$stu_name,$directory,$file_name,$version) = @_;
11930:     my ($answer_name,$answer_ver,$answer_ext) =
11931:         &file_name_version_ext($file_name);
11932:     my $new_answer;
11933:     $env{'form.copy'} =
11934:         &getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
11935:     if($env{'form.copy'} eq '-1') {
11936:         $new_answer = 'problem getting file';
11937:     } else {
11938:         $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
11939:         my $copy_result = 
11940:             &finishuserfileupload($stu_name,$domain,'copy',
11941:                                   '/portfolio'.$directory.$new_answer);
11942:     }
11943:     undef($env{'form.copy'});
11944:     return ($new_answer);
11945: }
11946: 
11947: sub file_name_version_ext {
11948:     my ($file)=@_;
11949:     my @file_parts = split(/\./, $file);
11950:     my ($name,$version,$ext);
11951:     if (@file_parts > 1) {
11952:         $ext=pop(@file_parts);
11953:         if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
11954:             $version=pop(@file_parts);
11955:         }
11956:         $name=join('.',@file_parts);
11957:     } else {
11958:         $name=join('.',@file_parts);
11959:     }
11960:     return($name,$version,$ext);
11961: }
11962: 
11963: #----------------------------------------------Get portfolio file permissions
11964: 
11965: sub get_portfile_permissions {
11966:     my ($domain,$user) = @_;
11967:     my %current_permissions = &dump('file_permissions',$domain,$user);
11968:     my ($tmp)=keys(%current_permissions);
11969:     if ($tmp=~/^error:/) { undef(%current_permissions); }
11970:     return \%current_permissions;
11971: }
11972: 
11973: #---------------------------------------------Get portfolio file access controls
11974: 
11975: sub get_access_controls {
11976:     my ($current_permissions,$group,$file) = @_;
11977:     my %access;
11978:     my $real_file = $file;
11979:     $file =~ s/\.meta$//;
11980:     if (defined($file)) {
11981:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
11982:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
11983:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
11984:             }
11985:         }
11986:     } else {
11987:         foreach my $key (keys(%{$current_permissions})) {
11988:             if ($key =~ /\0accesscontrol$/) {
11989:                 if (defined($group)) {
11990:                     if ($key !~ m-^\Q$group\E/-) {
11991:                         next;
11992:                     }
11993:                 }
11994:                 my ($fullpath) = split(/\0/,$key);
11995:                 if (ref($$current_permissions{$key}) eq 'HASH') {
11996:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
11997:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
11998:                     }
11999:                 }
12000:             }
12001:         }
12002:     }
12003:     return %access;
12004: }
12005: 
12006: sub modify_access_controls {
12007:     my ($file_name,$changes,$domain,$user)=@_;
12008:     my ($outcome,$deloutcome);
12009:     my %store_permissions;
12010:     my %new_values;
12011:     my %new_control;
12012:     my %translation;
12013:     my @deletions = ();
12014:     my $now = time;
12015:     if (exists($$changes{'activate'})) {
12016:         if (ref($$changes{'activate'}) eq 'HASH') {
12017:             my @newitems = sort(keys(%{$$changes{'activate'}}));
12018:             my $numnew = scalar(@newitems);
12019:             for (my $i=0; $i<$numnew; $i++) {
12020:                 my $newkey = $newitems[$i];
12021:                 my $newid = &Apache::loncommon::get_cgi_id();
12022:                 if ($newkey =~ /^\d+:/) { 
12023:                     $newkey =~ s/^(\d+)/$newid/;
12024:                     $translation{$1} = $newid;
12025:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
12026:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
12027:                     $translation{$1} = $newid;
12028:                 }
12029:                 $new_values{$file_name."\0".$newkey} = 
12030:                                           $$changes{'activate'}{$newitems[$i]};
12031:                 $new_control{$newkey} = $now;
12032:             }
12033:         }
12034:     }
12035:     my %todelete;
12036:     my %changed_items;
12037:     foreach my $action ('delete','update') {
12038:         if (exists($$changes{$action})) {
12039:             if (ref($$changes{$action}) eq 'HASH') {
12040:                 foreach my $key (keys(%{$$changes{$action}})) {
12041:                     my ($itemnum) = ($key =~ /^([^:]+):/);
12042:                     if ($action eq 'delete') { 
12043:                         $todelete{$itemnum} = 1;
12044:                     } else {
12045:                         $changed_items{$itemnum} = $key;
12046:                     }
12047:                 }
12048:             }
12049:         }
12050:     }
12051:     # get lock on access controls for file.
12052:     my $lockhash = {
12053:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
12054:                                                        ':'.$env{'user.domain'},
12055:                    }; 
12056:     my $tries = 0;
12057:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
12058:    
12059:     while (($gotlock ne 'ok') && $tries < 10) {
12060:         $tries ++;
12061:         sleep(0.1);
12062:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
12063:     }
12064:     if ($gotlock eq 'ok') {
12065:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
12066:         my ($tmp)=keys(%curr_permissions);
12067:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
12068:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
12069:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
12070:             if (ref($curr_controls) eq 'HASH') {
12071:                 foreach my $control_item (keys(%{$curr_controls})) {
12072:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
12073:                     if (defined($todelete{$itemnum})) {
12074:                         push(@deletions,$file_name."\0".$control_item);
12075:                     } else {
12076:                         if (defined($changed_items{$itemnum})) {
12077:                             $new_control{$changed_items{$itemnum}} = $now;
12078:                             push(@deletions,$file_name."\0".$control_item);
12079:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
12080:                         } else {
12081:                             $new_control{$control_item} = $$curr_controls{$control_item};
12082:                         }
12083:                     }
12084:                 }
12085:             }
12086:         }
12087:         my ($group);
12088:         if (&is_course($domain,$user)) {
12089:             ($group,my $file) = split(/\//,$file_name,2);
12090:         }
12091:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
12092:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
12093:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
12094:         #  remove lock
12095:         my @del_lock = ($file_name."\0".'locked_access_records');
12096:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
12097:         my $sqlresult =
12098:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
12099:                                     $group);
12100:     } else {
12101:         $outcome = "error: could not obtain lockfile\n";  
12102:     }
12103:     return ($outcome,$deloutcome,\%new_values,\%translation);
12104: }
12105: 
12106: sub make_public_indefinitely {
12107:     my (@requrl) = @_;
12108:     return &automated_portfile_access('public',\@requrl);
12109: }
12110: 
12111: sub automated_portfile_access {
12112:     my ($accesstype,$addsref,$delsref,$info) = @_;
12113:     unless (($accesstype eq 'public') || ($accesstype eq 'ip')) {
12114:         return 'invalid';
12115:     }
12116:     my %urls;
12117:     if (ref($addsref) eq 'ARRAY') {
12118:         foreach my $requrl (@{$addsref}) {
12119:             if (&is_portfolio_url($requrl)) {
12120:                 unless (exists($urls{$requrl})) {
12121:                     $urls{$requrl} = 'add';
12122:                 }
12123:             }
12124:         }
12125:     }
12126:     if (ref($delsref) eq 'ARRAY') {
12127:         foreach my $requrl (@{$delsref}) { 
12128:             if (&is_portfolio_url($requrl)) {
12129:                 unless (exists($urls{$requrl})) {
12130:                     $urls{$requrl} = 'delete'; 
12131:                 }
12132:             }
12133:         }
12134:     }
12135:     unless (keys(%urls)) {
12136:         return 'invalid';
12137:     }
12138:     my $ip;
12139:     if ($accesstype eq 'ip') {
12140:         if (ref($info) eq 'HASH') {
12141:             if ($info->{'ip'} ne '') {
12142:                 $ip = $info->{'ip'};
12143:             }
12144:         }
12145:         if ($ip eq '') {
12146:             return 'invalid';
12147:         }
12148:     }
12149:     my $errors;
12150:     my $now = time;
12151:     my %current_perms;
12152:     foreach my $requrl (sort(keys(%urls))) {
12153:         my $action;
12154:         if ($urls{$requrl} eq 'add') {
12155:             $action = 'activate';
12156:         } else {
12157:             $action = 'none';
12158:         }
12159:         my $aclnum = 0;
12160:         my (undef,$udom,$unum,$file_name,$group) =
12161:             &parse_portfolio_url($requrl);
12162:         unless (exists($current_perms{$unum.':'.$udom})) {
12163:             $current_perms{$unum.':'.$udom} = &get_portfile_permissions($udom,$unum);
12164:         }
12165:         my %access_controls = &get_access_controls($current_perms{$unum.':'.$udom},
12166:                                                    $group,$file_name);
12167:         foreach my $key (keys(%{$access_controls{$file_name}})) {
12168:             my ($num,$scope,$end,$start) = 
12169:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
12170:             if ($scope eq $accesstype) {
12171:                 if (($start <= $now) && ($end == 0)) {
12172:                     if ($accesstype eq 'ip') {
12173:                         if (ref($access_controls{$file_name}{$key}) eq 'HASH') {
12174:                             if (ref($access_controls{$file_name}{$key}{'ip'}) eq 'ARRAY') {
12175:                                 if (grep(/^\Q$ip\E$/,@{$access_controls{$file_name}{$key}{'ip'}})) {
12176:                                     if ($urls{$requrl} eq 'add') {
12177:                                         $action = 'none';
12178:                                         last;
12179:                                     } else {
12180:                                         $action = 'delete';
12181:                                         $aclnum = $num;
12182:                                         last;
12183:                                     }
12184:                                 }
12185:                             }
12186:                         }
12187:                     } elsif ($accesstype eq 'public') {
12188:                         if ($urls{$requrl} eq 'add') {
12189:                             $action = 'none';
12190:                             last;
12191:                         } else {
12192:                             $action = 'delete';
12193:                             $aclnum = $num;
12194:                             last;
12195:                         }
12196:                     }
12197:                 } elsif ($accesstype eq 'public') {
12198:                     $action = 'update';
12199:                     $aclnum = $num;
12200:                     last;
12201:                 }
12202:             }
12203:         }
12204:         if ($action eq 'none') {
12205:             next;
12206:         } else {
12207:             my %changes;
12208:             my $newend = 0;
12209:             my $newstart = $now;
12210:             my $newkey = $aclnum.':'.$accesstype.'_'.$newend.'_'.$newstart;
12211:             $changes{$action}{$newkey} = {
12212:                 type => $accesstype,
12213:                 time => {
12214:                     start => $newstart,
12215:                     end   => $newend,
12216:                 },
12217:             };
12218:             if ($accesstype eq 'ip') {
12219:                 $changes{$action}{$newkey}{'ip'} = [$ip];
12220:             }
12221:             my ($outcome,$deloutcome,$new_values,$translation) =
12222:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
12223:             unless ($outcome eq 'ok') {
12224:                 $errors .= $outcome.' ';
12225:             }
12226:         }
12227:     }
12228:     if ($errors) {
12229:         $errors =~ s/\s$//;
12230:         return $errors;
12231:     } else {
12232:         return 'ok';
12233:     }
12234: }
12235: 
12236: #------------------------------------------------------Get Marked as Read Only
12237: 
12238: sub get_marked_as_readonly {
12239:     my ($domain,$user,$what,$group) = @_;
12240:     my $current_permissions = &get_portfile_permissions($domain,$user);
12241:     my @readonly_files;
12242:     my $cmp1=$what;
12243:     if (ref($what)) { $cmp1=join('',@{$what}) };
12244:     while (my ($file_name,$value) = each(%{$current_permissions})) {
12245:         if (defined($group)) {
12246:             if ($file_name !~ m-^\Q$group\E/-) {
12247:                 next;
12248:             }
12249:         }
12250:         if (ref($value) eq "ARRAY"){
12251:             foreach my $stored_what (@{$value}) {
12252:                 my $cmp2=$stored_what;
12253:                 if (ref($stored_what) eq 'ARRAY') {
12254:                     $cmp2=join('',@{$stored_what});
12255:                 }
12256:                 if ($cmp1 eq $cmp2) {
12257:                     push(@readonly_files, $file_name);
12258:                     last;
12259:                 } elsif (!defined($what)) {
12260:                     push(@readonly_files, $file_name);
12261:                     last;
12262:                 }
12263:             }
12264:         }
12265:     }
12266:     return @readonly_files;
12267: }
12268: #-----------------------------------------------------------Get Marked as Read Only Hash
12269: 
12270: sub get_marked_as_readonly_hash {
12271:     my ($current_permissions,$group,$what) = @_;
12272:     my %readonly_files;
12273:     while (my ($file_name,$value) = each(%{$current_permissions})) {
12274:         if (defined($group)) {
12275:             if ($file_name !~ m-^\Q$group\E/-) {
12276:                 next;
12277:             }
12278:         }
12279:         if (ref($value) eq "ARRAY"){
12280:             foreach my $stored_what (@{$value}) {
12281:                 if (ref($stored_what) eq 'ARRAY') {
12282:                     foreach my $lock_descriptor(@{$stored_what}) {
12283:                         if ($lock_descriptor eq 'graded') {
12284:                             $readonly_files{$file_name} = 'graded';
12285:                         } elsif ($lock_descriptor eq 'handback') {
12286:                             $readonly_files{$file_name} = 'handback';
12287:                         } else {
12288:                             if (!exists($readonly_files{$file_name})) {
12289:                                 $readonly_files{$file_name} = 'locked';
12290:                             }
12291:                         }
12292:                     }
12293:                 } 
12294:             }
12295:         } 
12296:     }
12297:     return %readonly_files;
12298: }
12299: # ------------------------------------------------------------ Unmark as Read Only
12300: 
12301: sub unmark_as_readonly {
12302:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
12303:     # for portfolio submissions, $what contains [$symb,$crsid] 
12304:     my ($domain,$user,$what,$file_name,$group) = @_;
12305:     $file_name = &declutter_portfile($file_name);
12306:     my $symb_crs = $what;
12307:     if (ref($what)) { $symb_crs=join('',@$what); }
12308:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
12309:     my ($tmp)=keys(%current_permissions);
12310:     if ($tmp=~/^error:/) { undef(%current_permissions); }
12311:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
12312:     foreach my $file (@readonly_files) {
12313: 	my $clean_file = &declutter_portfile($file);
12314: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
12315: 	my $current_locks = $current_permissions{$file};
12316:         my @new_locks;
12317:         my @del_keys;
12318:         if (ref($current_locks) eq "ARRAY"){
12319:             foreach my $locker (@{$current_locks}) {
12320:                 my $compare=$locker;
12321:                 if (ref($locker) eq 'ARRAY') {
12322:                     $compare=join('',@{$locker});
12323:                     if ($compare ne $symb_crs) {
12324:                         push(@new_locks, $locker);
12325:                     }
12326:                 }
12327:             }
12328:             if (scalar(@new_locks) > 0) {
12329:                 $current_permissions{$file} = \@new_locks;
12330:             } else {
12331:                 push(@del_keys, $file);
12332:                 &del('file_permissions',\@del_keys, $domain, $user);
12333:                 delete($current_permissions{$file});
12334:             }
12335:         }
12336:     }
12337:     &put('file_permissions',\%current_permissions,$domain,$user);
12338:     return;
12339: }
12340: 
12341: # ------------------------------------------------------------ Directory lister
12342: 
12343: sub dirlist {
12344:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
12345:     $uri=~s/^\///;
12346:     $uri=~s/\/$//;
12347:     my ($udom, $uname);
12348:     if ($getuserdir) {
12349:         $udom = $userdomain;
12350:         $uname = $username;
12351:     } else {
12352:         (undef,$udom,$uname)=split(/\//,$uri);
12353:         if(defined($userdomain)) {
12354:             $udom = $userdomain;
12355:         }
12356:         if(defined($username)) {
12357:             $uname = $username;
12358:         }
12359:     }
12360:     my ($dirRoot,$listing,@listing_results);
12361: 
12362:     $dirRoot = $perlvar{'lonDocRoot'};
12363:     if (defined($getpropath)) {
12364:         $dirRoot = &propath($udom,$uname);
12365:         $dirRoot =~ s/\/$//;
12366:     } elsif (defined($getuserdir)) {
12367:         my $subdir=$uname.'__';
12368:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
12369:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
12370:                    ."/$udom/$subdir/$uname";
12371:     } elsif (defined($alternateRoot)) {
12372:         $dirRoot = $alternateRoot;
12373:     }
12374: 
12375:     if($udom) {
12376:         if($uname) {
12377:             my $uhome = &homeserver($uname,$udom);
12378:             if ($uhome eq 'no_host') {
12379:                 return ([],'no_host');
12380:             }
12381:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
12382:                               .$getuserdir.':'.&escape($dirRoot)
12383:                               .':'.&escape($uname).':'.&escape($udom),$uhome);
12384:             if ($listing eq 'unknown_cmd') {
12385:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
12386:             } else {
12387:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
12388:             }
12389:             if ($listing eq 'unknown_cmd') {
12390:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
12391:                 @listing_results = split(/:/,$listing);
12392:             } else {
12393:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
12394:             }
12395:             if (($listing eq 'no_such_host') || ($listing eq 'con_lost') || 
12396:                 ($listing eq 'rejected') || ($listing eq 'refused') ||
12397:                 ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
12398:                 return ([],$listing);
12399:             } else {
12400:                 return (\@listing_results);
12401:             }
12402:         } elsif(!$alternateRoot) {
12403:             my (%allusers,%listerror);
12404: 	    my %servers = &get_servers($udom,'library');
12405:  	    foreach my $tryserver (keys(%servers)) {
12406:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
12407:                                   &escape($udom),$tryserver);
12408:                 if ($listing eq 'unknown_cmd') {
12409: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
12410: 				      $udom, $tryserver);
12411:                 } else {
12412:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
12413:                 }
12414: 		if ($listing eq 'unknown_cmd') {
12415: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
12416: 				      $udom, $tryserver);
12417: 		    @listing_results = split(/:/,$listing);
12418: 		} else {
12419: 		    @listing_results =
12420: 			map { &unescape($_); } split(/:/,$listing);
12421: 		}
12422:                 if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
12423:                     ($listing eq 'rejected') || ($listing eq 'refused') ||
12424:                     ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
12425:                     $listerror{$tryserver} = $listing;
12426:                 } else {
12427: 		    foreach my $line (@listing_results) {
12428: 			my ($entry) = split(/&/,$line,2);
12429: 			$allusers{$entry} = 1;
12430: 		    }
12431: 		}
12432:             }
12433:             my @alluserslist=();
12434:             foreach my $user (sort(keys(%allusers))) {
12435:                 push(@alluserslist,$user.'&user');
12436:             }
12437: 
12438:             if (!%listerror) {
12439:                 # no errors
12440:                 return (\@alluserslist);
12441:             } elsif (scalar(keys(%servers)) == 1) {
12442:                 # one library server, one error 
12443:                 my ($key) = keys(%listerror);
12444:                 return (\@alluserslist, $listerror{$key});
12445:             } elsif ( grep { $_ eq 'con_lost' } values(%listerror) ) {
12446:                 # con_lost indicates that we might miss data from at least one
12447:                 # library server
12448:                 return (\@alluserslist, 'con_lost');
12449:             } else {
12450:                 # multiple library servers and no con_lost -> data should be
12451:                 # complete. 
12452:                 return (\@alluserslist);
12453:             }
12454: 
12455:         } else {
12456:             return ([],'missing username');
12457:         }
12458:     } elsif(!defined($getpropath)) {
12459:         my $path = $perlvar{'lonDocRoot'}.'/res/'; 
12460:         my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
12461:         return (\@all_domains);
12462:     } else {
12463:         return ([],'missing domain');
12464:     }
12465: }
12466: 
12467: # --------------------------------------------- GetFileTimestamp
12468: # This function utilizes dirlist and returns the date stamp for
12469: # when it was last modified.  It will also return an error of -1
12470: # if an error occurs
12471: 
12472: sub GetFileTimestamp {
12473:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
12474:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
12475:     $studentName   = &LONCAPA::clean_username($studentName);
12476:     my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
12477:                                     undef,$getuserdir);
12478:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
12479:         return -1;
12480:     }
12481:     if (ref($fileref) eq 'ARRAY') {
12482:         my @stats = split('&',$fileref->[0]);
12483:         # @stats contains first the filename, then the stat output
12484:         return $stats[10]; # so this is 10 instead of 9.
12485:     } else {
12486:         return -1;
12487:     }
12488: }
12489: 
12490: sub stat_file {
12491:     my ($uri) = @_;
12492:     $uri = &clutter_with_no_wrapper($uri);
12493: 
12494:     my ($udom,$uname,$file);
12495:     if ($uri =~ m-^/(uploaded|editupload)/-) {
12496: 	($udom,$uname,$file) =
12497: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
12498: 	$file = 'userfiles/'.$file;
12499:     }
12500:     if ($uri =~ m-^/res/-) {
12501: 	($udom,$uname) = 
12502: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
12503: 	$file = $uri;
12504:     }
12505: 
12506:     if (!$udom || !$uname || !$file) {
12507: 	# unable to handle the uri
12508: 	return ();
12509:     }
12510:     my $getpropath;
12511:     if ($file =~ /^userfiles\//) {
12512:         $getpropath = 1;
12513:     }
12514:     my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
12515:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
12516:         return ();
12517:     } else {
12518:         if (ref($listref) eq 'ARRAY') {
12519:             my @stats = split('&',$listref->[0]);
12520: 	    shift(@stats); #filename is first
12521: 	    return @stats;
12522:         }
12523:     }
12524:     return ();
12525: }
12526: 
12527: # --------------------------------------------------------- recursedirs
12528: # Recursive function to traverse either a specific user's Authoring Space
12529: # or corresponding Published Resource Space, and populate the hash ref:
12530: # $dirhashref with URLs of all directories, and if $filehashref hash
12531: # ref arg is provided, the URLs of any files, excluding versioned, .meta,
12532: # or .rights files in resource space, and .meta, .save, .log, .bak and
12533: # .rights files in Authoring Space.
12534: #
12535: # Inputs:
12536: #
12537: # $is_home - true if current server is home server for user's space
12538: # $recurse - if true will also traverse subdirectories recursively
12539: # $include - reference to hash containing allowed file extensions.  If provided,
12540: #             files which do not have a matching extension will be ignored.
12541: # $exclude - reference to hash containing excluded file extensions.  If provided,
12542: #             files which have a matching extension will be ignored.
12543: # $nonemptydir - if true, will only populate $fileshashref hash entry for a particular
12544: #             directory with first file found (with acceptable extension).
12545: # $addtopdir - if true, set $dirhashref->{'/'} = 1 
12546: # $toppath - Top level directory (i.e., /res/$dom/$uname or /priv/$dom/$uname
12547: # $relpath - Current path (relative to top level).
12548: # $dirhashref - reference to hash to populate with URLs of directories (Required)
12549: # $filehashref - reference to hash to populate with URLs of files (Optional)
12550: #
12551: # Returns: nothing
12552: #
12553: # Side Effects: populates $dirhashref, and $filehashref (if provided).
12554: #
12555: # Currently used by interface/londocs.pm to create linked select boxes for
12556: # directory and filename to import a Course "Author" resource into a course, and
12557: # also to create linked select boxes for Authoring Space and Directory to choose
12558: # save location for creation of a new "standard" problem from the Course Editor.
12559: #
12560: 
12561: sub recursedirs {
12562:     my ($is_home,$recurse,$include,$exclude,$nonemptydir,$addtopdir,$toppath,$relpath,$dirhashref,$filehashref) = @_;
12563:     return unless (ref($dirhashref) eq 'HASH');
12564:     my $docroot = $perlvar{'lonDocRoot'};
12565:     my $currpath = $docroot.$toppath;
12566:     if ($relpath ne '') {
12567:         $currpath .= "/$relpath";
12568:     }
12569:     my ($savefile,$checkinc,$checkexc);
12570:     if (ref($filehashref)) {
12571:         $savefile = 1;
12572:     }
12573:     if (ref($include) eq 'HASH') {
12574:         $checkinc = 1;
12575:     }
12576:     if (ref($exclude) eq 'HASH') {
12577:         $checkexc = 1;
12578:     }
12579:     if ($is_home) {
12580:         if ((-e $currpath) && (opendir(my $dirh,$currpath))) {
12581:             my $filecount = 0;
12582:             foreach my $item (sort { lc($a) cmp lc($b) } grep(!/^\.+$/,readdir($dirh))) {
12583:                 next if ($item eq '');
12584:                 if (-d "$currpath/$item") {
12585:                     my $newpath;
12586:                     if ($relpath ne '') {
12587:                         $newpath = "$relpath/$item";
12588:                     } else {
12589:                         $newpath = $item;
12590:                     }
12591:                     $dirhashref->{&Apache::lonlocal::js_escape($newpath)} = 1;
12592:                     if ($recurse) {
12593:                         &recursedirs($is_home,$recurse,$include,$exclude,$nonemptydir,$addtopdir,$toppath,$newpath,$dirhashref,$filehashref);
12594:                     }
12595:                 } elsif (($savefile) || ($relpath eq '')) {
12596:                     next if ($nonemptydir && $filecount);
12597:                     if ($checkinc || $checkexc) {
12598:                         my ($extension) = ($item =~ /\.(\w+)$/);
12599:                         if ($checkinc) {
12600:                             next unless ($extension && $include->{$extension});
12601:                         }
12602:                         if ($checkexc) {
12603:                             next if ($extension && $exclude->{$extension});
12604:                         }
12605:                     }
12606:                     if (($relpath eq '') && (!exists($dirhashref->{'/'}))) {
12607:                         $dirhashref->{'/'} = 1;
12608:                     }
12609:                     if ($savefile) {
12610:                         if ($relpath eq '') {
12611:                             $filehashref->{'/'}{$item} = 1;
12612:                         } else {
12613:                             $filehashref->{&Apache::lonlocal::js_escape($relpath)}{$item} = 1;
12614:                         }
12615:                     }
12616:                     $filecount ++;
12617:                 }
12618:             }
12619:             closedir($dirh);
12620:         }
12621:     } else {
12622:         my ($dirlistref,$listerror) =
12623:             &dirlist($toppath.$relpath);
12624:         my @dir_lines;
12625:         my $dirptr=16384;
12626:         if (ref($dirlistref) eq 'ARRAY') {
12627:             my $filecount = 0;
12628:             foreach my $dir_line (sort
12629:                               {
12630:                                   my ($afile)=split('&',$a,2);
12631:                                   my ($bfile)=split('&',$b,2);
12632:                                   return (lc($afile) cmp lc($bfile));
12633:                               } (@{$dirlistref})) {
12634:                 my ($item,$dom,undef,$testdir,undef,undef,undef,undef,$size,undef,$mtime,undef,undef,undef,$obs,undef) =
12635:                     split(/\&/,$dir_line,16);
12636:                 $item =~ s/\s+$//;
12637:                 next if (($item =~ /^\.\.?$/) || ($obs));
12638:                 if ($dirptr&$testdir) {
12639:                     my $newpath;
12640:                     if ($relpath) {
12641:                         $newpath = "$relpath/$item";
12642:                     } else {
12643:                         $newpath = $item;
12644:                     }
12645:                     $dirhashref->{&Apache::lonlocal::js_escape($newpath)} = 1;
12646:                     if ($recurse) {
12647:                         &recursedirs($is_home,$recurse,$include,$exclude,$nonemptydir,$addtopdir,$toppath,$newpath,$dirhashref,$filehashref);
12648:                     }
12649:                 } elsif (($savefile) || ($relpath eq '')) {
12650:                     next if ($nonemptydir && $filecount);
12651:                     if ($checkinc || $checkexc) {
12652:                         my $extension;
12653:                         if ($checkinc) {
12654:                             next unless ($extension && $include->{$extension});
12655:                         }
12656:                         if ($checkexc) {
12657:                             next if ($extension && $exclude->{$extension});
12658:                         }
12659:                     }
12660:                     if (($relpath eq '') && (!exists($dirhashref->{'/'}))) {
12661:                         $dirhashref->{'/'} = 1;
12662:                     }
12663:                     if ($savefile) {
12664:                         if ($relpath eq '') {
12665:                             $filehashref->{'/'}{$item} = 1;
12666:                         } else {
12667:                             $filehashref->{&Apache::lonlocal::js_escape($relpath)}{$item} = 1;
12668:                         }
12669:                     }
12670:                     $filecount ++; 
12671:                 }
12672:             }
12673:         }
12674:     }
12675:     if ($addtopdir) {
12676:         if (($relpath eq '') && (!exists($dirhashref->{'/'}))) {
12677:             $dirhashref->{'/'} = 1;
12678:         }
12679:     }
12680:     return;
12681: }
12682: 
12683: sub priv_exclude {
12684:     return {
12685:              meta => 1,
12686:              save => 1,
12687:              log => 1,
12688:              bak => 1,
12689:              rights => 1,
12690:              DS_Store => 1,
12691:            };
12692: }
12693: 
12694: # -------------------------------------------------------- Value of a Condition
12695: 
12696: # gets the value of a specific preevaluated condition
12697: #    stored in the string  $env{user.state.<cid>}
12698: # or looks up a condition reference in the bighash and if if hasn't
12699: # already been evaluated recurses into docondval to get the value of
12700: # the condition, then memoizing it to 
12701: #   $env{user.state.<cid>.<condition>}
12702: sub directcondval {
12703:     my $number=shift;
12704:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
12705: 	&Apache::lonuserstate::evalstate();
12706:     }
12707:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
12708: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
12709:     } elsif ($number =~ /^_/) {
12710: 	my $sub_condition;
12711: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
12712: 		&GDBM_READER(),0640)) {
12713: 	    $sub_condition=$bighash{'conditions'.$number};
12714: 	    untie(%bighash);
12715: 	}
12716: 	my $value = &docondval($sub_condition);
12717: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
12718: 	return $value;
12719:     }
12720:     if ($env{'user.state.'.$env{'request.course.id'}}) {
12721:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
12722:     } else {
12723:        return 2;
12724:     }
12725: }
12726: 
12727: # get the collection of conditions for this resource
12728: sub condval {
12729:     my $condidx=shift;
12730:     my $allpathcond='';
12731:     foreach my $cond (split(/\|/,$condidx)) {
12732: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
12733: 	    $allpathcond.=
12734: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
12735: 	}
12736:     }
12737:     $allpathcond=~s/\|$//;
12738:     return &docondval($allpathcond);
12739: }
12740: 
12741: #evaluates an expression of conditions
12742: sub docondval {
12743:     my ($allpathcond) = @_;
12744:     my $result=0;
12745:     if ($env{'request.course.id'}
12746: 	&& defined($allpathcond)) {
12747: 	my $operand='|';
12748: 	my @stack;
12749: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
12750: 	    if ($chunk eq '(') {
12751: 		push @stack,($operand,$result);
12752: 	    } elsif ($chunk eq ')') {
12753: 		my $before=pop @stack;
12754: 		if (pop @stack eq '&') {
12755: 		    $result=$result>$before?$before:$result;
12756: 		} else {
12757: 		    $result=$result>$before?$result:$before;
12758: 		}
12759: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
12760: 		$operand=$chunk;
12761: 	    } else {
12762: 		my $new=directcondval($chunk);
12763: 		if ($operand eq '&') {
12764: 		    $result=$result>$new?$new:$result;
12765: 		} else {
12766: 		    $result=$result>$new?$result:$new;
12767: 		}
12768: 	    }
12769: 	}
12770:     }
12771:     return $result;
12772: }
12773: 
12774: # ---------------------------------------------------- Devalidate courseresdata
12775: 
12776: sub devalidatecourseresdata {
12777:     my ($coursenum,$coursedomain)=@_;
12778:     my $hashid=$coursenum.':'.$coursedomain;
12779:     &devalidate_cache_new('courseres',$hashid);
12780: }
12781: 
12782: 
12783: # --------------------------------------------------- Course Resourcedata Query
12784: #
12785: #  Parameters:
12786: #      $coursenum    - Number of the course.
12787: #      $coursedomain - Domain at which the course was created.
12788: #  Returns:
12789: #     A hash of the course parameters along (I think) with timestamps
12790: #     and version info.
12791: 
12792: sub get_courseresdata {
12793:     my ($coursenum,$coursedomain)=@_;
12794:     my $coursehom=&homeserver($coursenum,$coursedomain);
12795:     my $hashid=$coursenum.':'.$coursedomain;
12796:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
12797:     my %dumpreply;
12798:     unless (defined($cached)) {
12799: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
12800: 	$result=\%dumpreply;
12801: 	my ($tmp) = keys(%dumpreply);
12802: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
12803: 	    &do_cache_new('courseres',$hashid,$result,600);
12804: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
12805: 	    return $tmp;
12806: 	} elsif ($tmp =~ /^(error)/) {
12807: 	    $result=undef;
12808: 	    &do_cache_new('courseres',$hashid,$result,600);
12809: 	}
12810:     }
12811:     return $result;
12812: }
12813: 
12814: sub devalidateuserresdata {
12815:     my ($uname,$udom)=@_;
12816:     my $hashid="$udom:$uname";
12817:     &devalidate_cache_new('userres',$hashid);
12818: }
12819: 
12820: sub get_userresdata {
12821:     my ($uname,$udom)=@_;
12822:     #most student don\'t have any data set, check if there is some data
12823:     if (&EXT_cache_status($udom,$uname)) { return undef; }
12824: 
12825:     my $hashid="$udom:$uname";
12826:     my ($result,$cached)=&is_cached_new('userres',$hashid);
12827:     if (!defined($cached)) {
12828: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
12829: 	$result=\%resourcedata;
12830: 	&do_cache_new('userres',$hashid,$result,600);
12831:     }
12832:     my ($tmp)=keys(%$result);
12833:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
12834: 	return $result;
12835:     }
12836:     #error 2 occurs when the .db doesn't exist
12837:     if ($tmp!~/error: 2 /) {
12838:         if ((!defined($cached)) || ($tmp ne 'con_lost')) {
12839: 	    &logthis("<font color=\"blue\">WARNING:".
12840: 		     " Trying to get resource data for ".
12841: 		     $uname." at ".$udom.": ".
12842: 		     $tmp."</font>");
12843:         }
12844:     } elsif ($tmp=~/error: 2 /) {
12845: 	#&EXT_cache_set($udom,$uname);
12846: 	&do_cache_new('userres',$hashid,undef,600);
12847: 	undef($tmp); # not really an error so don't send it back
12848:     }
12849:     return $tmp;
12850: }
12851: #----------------------------------------------- resdata - return resource data
12852: #  Purpose:
12853: #    Return resource data for either users or for a course.
12854: #  Parameters:
12855: #     $name      - Course/user name.
12856: #     $domain    - Name of the domain the user/course is registered on.
12857: #     $type      - Type of thing $name is (must be 'course' or 'user')
12858: #     $mapp      - decluttered URL of enclosing map  
12859: #     $recursed  - Ref to scalar -- set to 1, if nested maps have been recursed.
12860: #     $recurseup - Ref to array of map URLs, starting with map containing
12861: #                  $mapp up through hierarchy of nested maps to top level map.  
12862: #     $courseid  - CourseID (first part of param identifier).
12863: #     $modifier  - Middle part of param identifier.
12864: #     $what      - Last part of param identifier.
12865: #     @which     - Array of names of resources desired.
12866: #  Returns:
12867: #     The value of the first reasource in @which that is found in the
12868: #     resource hash.
12869: #  Exceptional Conditions:
12870: #     If the $type passed in is not valid (not the string 'course' or 
12871: #     'user', an undefined  reference is returned.
12872: #     If none of the resources are found, an undef is returned
12873: sub resdata {
12874:     my ($name,$domain,$type,$mapp,$recursed,$recurseup,$courseid,
12875:         $modifier,$what,@which)=@_;
12876:     my $result;
12877:     if ($type eq 'course') {
12878: 	$result=&get_courseresdata($name,$domain);
12879:     } elsif ($type eq 'user') {
12880: 	$result=&get_userresdata($name,$domain);
12881:     }
12882:     if (!ref($result)) { return $result; }    
12883:     foreach my $item (@which) {
12884:         if ($item->[1] eq 'course') {
12885:             if ((ref($recurseup) eq 'ARRAY') && (ref($recursed) eq 'SCALAR')) {
12886:                 unless ($$recursed) {
12887:                     @{$recurseup} = &get_map_hierarchy($mapp,$courseid);
12888:                     $$recursed = 1;
12889:                 }
12890:                 foreach my $item (@${recurseup}) {
12891:                     my $norecursechk=$courseid.$modifier.$item.'___(all).'.$what;
12892:                     last if (defined($result->{$norecursechk}));
12893:                     my $recursechk=$courseid.$modifier.$item.'___(rec).'.$what;
12894:                     if (defined($result->{$recursechk})) { return [$result->{$recursechk},'map']; }
12895:                 }
12896:             }
12897:         }
12898:         if (defined($result->{$item->[0]})) {
12899: 	    return [$result->{$item->[0]},$item->[1]];
12900: 	}
12901:     }
12902:     return undef;
12903: }
12904: 
12905: sub get_domain_lti {
12906:     my ($cdom,$context) = @_;
12907:     my ($name,$cachename,%lti);
12908:     if ($context eq 'consumer') {
12909:         $name = 'ltitools';
12910:     } elsif ($context eq 'provider') {
12911:         $name = 'lti';
12912:     } elsif ($context eq 'linkprot') {
12913:         $name = 'ltisec';
12914:     } else {
12915:         return %lti;
12916:     }
12917:     if ($context eq 'linkprot') {
12918:         $cachename = $context;
12919:     } else {
12920:         $cachename = $name;
12921:     }
12922:     my ($result,$cached)=&is_cached_new($cachename,$cdom);
12923:     if (defined($cached)) {
12924:         if (ref($result) eq 'HASH') {
12925:             %lti = %{$result};
12926:         }
12927:     } else {
12928:         my %domconfig = &get_dom('configuration',[$name],$cdom);
12929:         if (ref($domconfig{$name}) eq 'HASH') {
12930:             if ($context eq 'linkprot') {
12931:                 if (ref($domconfig{$name}{'linkprot'}) eq 'HASH') {
12932:                     %lti = %{$domconfig{$name}{'linkprot'}};
12933:                 }
12934:             } else {
12935:                 %lti = %{$domconfig{$name}};
12936:             }
12937:         }
12938:         my $cachetime = 24*60*60;
12939:         &do_cache_new($cachename,$cdom,\%lti,$cachetime);
12940:     }
12941:     return %lti;
12942: }
12943: 
12944: sub get_course_lti {
12945:     my ($cnum,$cdom,$context) = @_;
12946:     my ($name,$cachename,%lti);
12947:     if ($context eq 'consumer') {
12948:         $name = 'ltitools';
12949:         $cachename = 'courseltitools';
12950:     } elsif ($context eq 'provider') {
12951:         $name = 'lti';
12952:         $cachename = 'courselti';
12953:     } else {
12954:         return %lti;
12955:     }
12956:     my $hashid=$cdom.'_'.$cnum;
12957:     my ($result,$cached)=&is_cached_new($cachename,$hashid);
12958:     if (defined($cached)) {
12959:         if (ref($result) eq 'HASH') {
12960:             %lti = %{$result};
12961:         }
12962:     } else {
12963:         %lti = &dump($name,$cdom,$cnum,undef,undef,undef,1);
12964:         my $cachetime = 24*60*60;
12965:         &do_cache_new($cachename,$hashid,\%lti,$cachetime);
12966:     }
12967:     return %lti;
12968: }
12969: 
12970: sub courselti_itemid {
12971:     my ($cnum,$cdom,$url,$method,$params,$context) = @_;
12972:     my ($chome,$itemid);
12973:     $chome = &homeserver($cnum,$cdom);
12974:     return if ($chome eq 'no_host');
12975:     if (ref($params) eq 'HASH') {
12976:         my $rep;
12977:         if (grep { $_ eq $chome } current_machine_ids()) {
12978:             $rep = LONCAPA::Lond::crslti_itemid($cdom,$cnum,$url,$method,$params,$perlvar{'lonVersion'});
12979:         } else {
12980:             my $escurl = &escape($url);
12981:             my $escmethod = &escape($method);
12982:             my $items = &freeze_escape($params);
12983:             $rep = &reply("encrypt:lti:$cdom:$cnum:$context:$escurl:$escmethod:$items",$chome);
12984:         }
12985:         unless (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
12986:                 ($rep eq 'unknown_cmd')) {
12987:             $itemid = $rep;
12988:         }
12989:     }
12990:     return $itemid;
12991: }
12992: 
12993: sub domainlti_itemid {
12994:     my ($cdom,$url,$method,$params,$context) = @_;
12995:     my ($primary_id,$itemid);
12996:     $primary_id = &domain($cdom,'primary');
12997:     return if ($primary_id eq '');
12998:     if (ref($params) eq 'HASH') {
12999:         my $rep;
13000:         if (grep { $_ eq $primary_id } current_machine_ids()) {
13001:             $rep = LONCAPA::Lond::domlti_itemid($cdom,$context,$url,$method,$params,$perlvar{'lonVersion'});
13002:         } else {
13003:             my $cnum = '';
13004:             my $escurl = &escape($url);
13005:             my $escmethod = &escape($method);
13006:             my $items = &freeze_escape($params);
13007:             $rep = &reply("encrypt:lti:$cdom:$cnum:$context:$escurl:$escmethod:$items",$primary_id);
13008:         }
13009:         unless (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
13010:                 ($rep eq 'unknown_cmd')) {
13011:             $itemid = $rep;
13012:         }
13013:     }
13014:     return $itemid;
13015: }
13016: 
13017: sub get_ltitools_id {
13018:     my ($context,$cdom,$cnum,$title) = @_;
13019:     my ($lockhash,$tries,$gotlock,$id,$error);
13020: 
13021:     # get lock on ltitools db
13022:     $lockhash = {
13023:                    lock => $env{'user.name'}.
13024:                            ':'.$env{'user.domain'},
13025:                 };
13026:     $tries = 0;
13027:     if ($context eq 'domain') {
13028:         $gotlock = &newput_dom('ltitools',$lockhash,$cdom);
13029:     } else {
13030:         $gotlock = &newput('ltitools',$lockhash,$cdom,$cnum);
13031:     }
13032:     while (($gotlock ne 'ok') && ($tries<10)) {
13033:         $tries ++;
13034:         sleep (0.1);
13035:         if ($context eq 'domain') {
13036:             $gotlock = &newput_dom('ltitools',$lockhash,$cdom);
13037:         } else {
13038:             $gotlock = &newput('ltitools',$lockhash,$cdom,$cnum);
13039:         }
13040:     }
13041:     if ($gotlock eq 'ok') {
13042:         my %currids;
13043:         if ($context eq 'domain') {
13044:             %currids = &dump_dom('ltitools',$cdom);
13045:         } else {
13046:             %currids = &dump('ltitools',$cdom,$cnum);
13047:         }
13048:         if ($currids{'lock'}) {
13049:             delete($currids{'lock'});
13050:             if (keys(%currids)) {
13051:                 my @curr = sort { $a <=> $b } keys(%currids);
13052:                 if ($curr[-1] =~ /^\d+$/) {
13053:                     $id = 1 + $curr[-1];
13054:                 }
13055:             } else {
13056:                 $id = 1;
13057:             }
13058:             if ($id) {
13059:                 if ($context eq 'domain') {
13060:                     unless (&newput_dom('ltitools',{ $id => $title },$cdom) eq 'ok') {
13061:                         $error = 'nostore';
13062:                     }
13063:                 } else {
13064:                     unless (&newput('ltitools',{ $id => $title },$cdom,$cnum) eq 'ok') {
13065:                         $error = 'nostore';
13066:                     }
13067:                 }
13068:             } else {
13069:                 $error = 'nonumber';
13070:             }
13071:         }
13072:         my $dellockoutcome;
13073:         if ($context eq 'domain') {
13074:             $dellockoutcome = &del_dom('ltitools',['lock'],$cdom);
13075:         } else {
13076:             $dellockoutcome = &del('ltitools',['lock'],$cdom,$cnum);
13077:         }
13078:     } else {
13079:         $error = 'nolock';
13080:     }
13081:     return ($id,$error);
13082: }
13083: 
13084: sub count_supptools {
13085:     my ($cnum,$cdom,$ignorecache,$reload)=@_;
13086:     my $hashid=$cnum.':'.$cdom;
13087:     my ($numexttools,$cached);
13088:     unless ($ignorecache) {
13089:         ($numexttools,$cached) = &is_cached_new('supptools',$hashid);
13090:     }
13091:     unless (defined($cached)) {
13092:         my $chome=&homeserver($cnum,$cdom);
13093:         $numexttools = 0;
13094:         unless ($chome eq 'no_host') {
13095:             my ($supplemental) = &Apache::loncommon::get_supplemental($cnum,$cdom,$reload);
13096:             if (ref($supplemental) eq 'HASH') {
13097:                 if ((ref($supplemental->{'ids'}) eq 'HASH') && (ref($supplemental->{'hidden'}) eq 'HASH')) {
13098:                     foreach my $key (keys(%{$supplemental->{'ids'}})) {
13099:                         if ($key =~ m{^/adm/$cdom/$cnum/\d+/ext\.tool$}) {
13100:                             $numexttools ++;
13101:                         }
13102:                     }
13103:                 }
13104:             }
13105:         }
13106:         &do_cache_new('supptools',$hashid,$numexttools,600);
13107:     }
13108:     return $numexttools;
13109: }
13110: 
13111: sub has_unhidden_suppfiles {
13112:     my ($cnum,$cdom,$ignorecache,$possdel)=@_;
13113:     my $hashid=$cnum.':'.$cdom;
13114:     my ($showsupp,$cached);
13115:     unless ($ignorecache) {
13116:         ($showsupp,$cached) = &is_cached_new('showsupp',$hashid);
13117:     }
13118:     unless (defined($cached)) {
13119:         my $chome=&homeserver($cnum,$cdom);
13120:         unless ($chome eq 'no_host') {
13121:             my ($supplemental) = &Apache::loncommon::get_supplemental($cnum,$cdom,$ignorecache,$possdel);
13122:             if (ref($supplemental) eq 'HASH') {
13123:                 if ((ref($supplemental->{'ids'}) eq 'HASH') && (ref($supplemental->{'hidden'}) eq 'HASH')) {
13124:                     foreach my $key (keys(%{$supplemental->{'ids'}})) {
13125:                         next if ($key =~ /\.sequence$/);
13126:                         if (ref($supplemental->{'ids'}->{$key}) eq 'ARRAY') {
13127:                             foreach my $id (@{$supplemental->{'ids'}->{$key}}) {
13128:                                 unless ($supplemental->{'hidden'}->{$id}) {
13129:                                     $showsupp = 1;
13130:                                     last;
13131:                                 }
13132:                             }
13133:                         }
13134:                         last if ($showsupp);
13135:                     }
13136:                 }
13137:             }
13138:         }
13139:         &do_cache_new('showsupp',$hashid,$showsupp,600);
13140:     }
13141:     return $showsupp;
13142: }
13143: 
13144: #
13145: # EXT resource caching routines
13146: #
13147: 
13148: {
13149: # Cache (5 seconds) of map hierarchy for speedup of navmaps display
13150: #
13151: # The course for which we cache
13152: my $cachedmapkey='';
13153: # The cached recursive maps for this course
13154: my %cachedmaps=();
13155: # When this was last done
13156: my $cachedmaptime='';
13157: 
13158: sub clear_EXT_cache_status {
13159:     &delenv('cache.EXT.');
13160: }
13161: 
13162: sub EXT_cache_status {
13163:     my ($target_domain,$target_user) = @_;
13164:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
13165:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
13166:         # We know already the user has no data
13167:         return 1;
13168:     } else {
13169:         return 0;
13170:     }
13171: }
13172: 
13173: sub EXT_cache_set {
13174:     my ($target_domain,$target_user) = @_;
13175:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
13176:     #&appenv({$cachename => time});
13177: }
13178: 
13179: # --------------------------------------------------------- Value of a Variable
13180: sub EXT {
13181: 
13182:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse,$cid,$recurseupref)=@_;
13183:     unless ($varname) { return ''; }
13184:     #get real user name/domain, courseid and symb
13185:     my $courseid;
13186:     my $publicuser;
13187:     if ($symbparm) {
13188: 	$symbparm=&get_symb_from_alias($symbparm);
13189:     }
13190:     if (!($uname && $udom)) {
13191:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
13192:       if (!$symbparm) {	$symbparm=$cursymb; }
13193:     } else {
13194: 	$courseid=$env{'request.course.id'};
13195:     }
13196:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
13197:     my $rest;
13198:     if (defined($therest[0])) {
13199:        $rest=join('.',@therest);
13200:     } else {
13201:        $rest='';
13202:     }
13203: 
13204:     my $qualifierrest=$qualifier;
13205:     if ($rest) { $qualifierrest.='.'.$rest; }
13206:     my $spacequalifierrest=$space;
13207:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
13208:     if ($realm eq 'user') {
13209: # --------------------------------------------------------------- user.resource
13210: 	if ($space eq 'resource') {
13211: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
13212: 		  || defined($Apache::lonhomework::parsing_a_task))
13213: 		 &&
13214: 		 ($symbparm eq &symbread()) ) {
13215: 		# if we are in the middle of processing the resource the
13216: 		# get the value we are planning on committing
13217:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
13218:                     return $Apache::lonhomework::results{$qualifierrest};
13219:                 } else {
13220:                     return $Apache::lonhomework::history{$qualifierrest};
13221:                 }
13222: 	    } else {
13223: 		my %restored;
13224: 		if ($publicuser || $env{'request.state'} eq 'construct') {
13225: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
13226: 		} else {
13227: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
13228: 		}
13229: 		return $restored{$qualifierrest};
13230: 	    }
13231: # ----------------------------------------------------------------- user.access
13232:         } elsif ($space eq 'access') {
13233: 	    # FIXME - not supporting calls for a specific user
13234:             return &allowed($qualifier,$rest);
13235: # ------------------------------------------ user.preferences, user.environment
13236:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
13237: 	    if (($uname eq $env{'user.name'}) &&
13238: 		($udom eq $env{'user.domain'})) {
13239: 		return $env{join('.',('environment',$qualifierrest))};
13240: 	    } else {
13241: 		my %returnhash;
13242: 		if (!$publicuser) {
13243: 		    %returnhash=&userenvironment($udom,$uname,
13244: 						 $qualifierrest);
13245: 		}
13246: 		return $returnhash{$qualifierrest};
13247: 	    }
13248: # ----------------------------------------------------------------- user.course
13249:         } elsif ($space eq 'course') {
13250: 	    # FIXME - not supporting calls for a specific user
13251:             return $env{join('.',('request.course',$qualifier))};
13252: # ------------------------------------------------------------------- user.role
13253:         } elsif ($space eq 'role') {
13254: 	    # FIXME - not supporting calls for a specific user
13255:             my ($role,$where)=split(/\./,$env{'request.role'});
13256:             if ($qualifier eq 'value') {
13257: 		return $role;
13258:             } elsif ($qualifier eq 'extent') {
13259:                 return $where;
13260:             }
13261: # ----------------------------------------------------------------- user.domain
13262:         } elsif ($space eq 'domain') {
13263:             return $udom;
13264: # ------------------------------------------------------------------- user.name
13265:         } elsif ($space eq 'name') {
13266:             return $uname;
13267: # ---------------------------------------------------- Any other user namespace
13268:         } else {
13269: 	    my %reply;
13270: 	    if (!$publicuser) {
13271: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
13272: 	    }
13273: 	    return $reply{$qualifierrest};
13274:         }
13275:     } elsif ($realm eq 'query') {
13276: # ---------------------------------------------- pull stuff out of query string
13277:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
13278: 						[$spacequalifierrest]);
13279: 	return $env{'form.'.$spacequalifierrest}; 
13280:    } elsif ($realm eq 'request') {
13281: # ------------------------------------------------------------- request.browser
13282:         if ($space eq 'browser') {
13283:             return $env{'browser.'.$qualifier};
13284: # ------------------------------------------------------------ request.filename
13285:         } else {
13286:             return $env{'request.'.$spacequalifierrest};
13287:         }
13288:     } elsif ($realm eq 'course') {
13289: # ---------------------------------------------------------- course.description
13290:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
13291:     } elsif ($realm eq 'resource') {
13292: 
13293: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
13294: 	    if (!$symbparm) { $symbparm=&symbread(); }
13295: 	}
13296: 
13297:         if ($qualifier eq '') {
13298: 	    if ($space eq 'title') {
13299: 	        if (!$symbparm) { $symbparm = $env{'request.filename'}; }
13300: 	        return &gettitle($symbparm);
13301: 	    }
13302: 	
13303: 	    if ($space eq 'map') {
13304: 	        my ($map) = &decode_symb($symbparm);
13305: 	        return &symbread($map);
13306: 	    }
13307:             if ($space eq 'maptitle') {
13308:                 my ($map) = &decode_symb($symbparm);
13309:                 return &gettitle($map);
13310:             }
13311: 	    if ($space eq 'filename') {
13312: 	        if ($symbparm) {
13313: 		    return &clutter((&decode_symb($symbparm))[2]);
13314: 	        }
13315: 	        return &hreflocation('',$env{'request.filename'});
13316: 	    }
13317: 
13318:             if ((defined($courseid)) && ($courseid eq $env{'request.course.id'}) && $symbparm) {
13319:                 if ($space eq 'visibleparts') {
13320:                     my $navmap = Apache::lonnavmaps::navmap->new();
13321:                     my $item;
13322:                     if (ref($navmap)) {
13323:                         my $res = $navmap->getBySymb($symbparm);
13324:                         my $parts = $res->parts();
13325:                         if (ref($parts) eq 'ARRAY') {
13326:                             $item = join(',',@{$parts});
13327:                         }
13328:                         undef($navmap);
13329:                     }
13330:                     return $item;
13331:                 }
13332:             }
13333:         }
13334: 
13335: 	my ($section, $group, @groups, @recurseup, $recursed);
13336:         if (ref($recurseupref) eq 'ARRAY') {
13337:             @recurseup = @{$recurseupref};
13338:             $recursed = 1;
13339:         }
13340: 	my ($courselevelm,$courseleveli,$courselevel,$mapp);
13341:         if (($courseid eq '') && ($cid)) {
13342:             $courseid = $cid;
13343:         }
13344: 	if (($symbparm && $courseid) && 
13345: 	    (($courseid eq $env{'request.course.id'}) || ($courseid eq $cid)))  {
13346: 
13347: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
13348: 
13349: # ----------------------------------------------------- Cascading lookup scheme
13350: 	    my $symbp=$symbparm;
13351: 	    $mapp=&deversion((&decode_symb($symbp))[0]);
13352: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
13353:             my $recurseparm=$mapp.'___(rec).'.$spacequalifierrest;
13354: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
13355: 	    if (($env{'user.name'} eq $uname) &&
13356: 		($env{'user.domain'} eq $udom)) {
13357: 		$section=$env{'request.course.sec'};
13358:                 @groups = split(/:/,$env{'request.course.groups'});  
13359:                 @groups=&sort_course_groups($courseid,@groups); 
13360: 	    } else {
13361: 		if (! defined($usection)) {
13362: 		    $section=&getsection($udom,$uname,$courseid);
13363: 		} else {
13364: 		    $section = $usection;
13365: 		}
13366:                 @groups = &get_users_groups($udom,$uname,$courseid);
13367: 	    }
13368: 
13369: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
13370: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
13371:             my $secleveli=$courseid.'.['.$section.'].'.$recurseparm;
13372: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
13373: 
13374: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
13375: 	    my $courselevelr=$courseid.'.'.$symbparm;
13376:             $courseleveli=$courseid.'.'.$recurseparm;
13377: 	    $courselevelm=$courseid.'.'.$mapparm;
13378: 
13379: # ----------------------------------------------------------- first, check user
13380: 
13381: 	    my $userreply=&resdata($uname,$udom,'user',$mapp,\$recursed,
13382:                                    \@recurseup,$courseid,'.',$spacequalifierrest, 
13383: 				       ([$courselevelr,'resource'],
13384: 					[$courselevelm,'map'     ],
13385:                                         [$courseleveli,'map'     ],
13386: 					[$courselevel, 'course'  ]));
13387: 	    if (defined($userreply)) { return &get_reply($userreply); }
13388: 
13389: # ------------------------------------------------ second, check some of course
13390:             my $coursereply;
13391:             if (@groups > 0) {
13392:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
13393:                                        $recurseparm,$mapparm,$spacequalifierrest,
13394:                                        $mapp,\$recursed,\@recurseup);
13395:                 if (defined($coursereply)) { return &get_reply($coursereply); } 
13396:             }
13397: 
13398: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
13399: 				  $env{'course.'.$courseid.'.domain'},
13400: 				  'course',$mapp,\$recursed,\@recurseup,
13401:                                   $courseid,'.['.$section.'].',$spacequalifierrest,
13402: 				  ([$seclevelr,   'resource'],
13403: 				   [$seclevelm,   'map'     ],
13404:                                    [$secleveli,   'map'     ],
13405: 				   [$seclevel,    'course'  ],
13406: 				   [$courselevelr,'resource']));
13407: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
13408: 
13409: # ------------------------------------------------------ third, check map parms
13410: 	    my %parmhash=();
13411: 	    my $thisparm='';
13412: 	    if (tie(%parmhash,'GDBM_File',
13413: 		    $env{'request.course.fn'}.'_parms.db',
13414: 		    &GDBM_READER(),0640)) {
13415: 		$thisparm=$parmhash{$symbparm};
13416: 		untie(%parmhash);
13417: 	    }
13418: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
13419: 	}
13420: # ------------------------------------------ fourth, look in resource metadata
13421:  
13422:         my $what = $spacequalifierrest;
13423: 	$what=~s/\./\_/;
13424: 	my $filename;
13425: 	if (!$symbparm) { $symbparm=&symbread(); }
13426: 	if ($symbparm) {
13427: 	    $filename=(&decode_symb($symbparm))[2];
13428: 	} else {
13429: 	    $filename=$env{'request.filename'};
13430: 	}
13431:         my $toolsymb;
13432:         if (($filename =~ /ext\.tool$/) && ($what ne '0_gradable')) {
13433:             $toolsymb = $symbparm;
13434:         }
13435: 	my $metadata=&metadata($filename,$what,$toolsymb);
13436: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
13437: 	$metadata=&metadata($filename,'parameter_'.$what,$toolsymb);
13438: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
13439: 
13440: # ----------------------------------------------- fifth, look in rest of course
13441: 	if ($symbparm && defined($courseid) && 
13442: 	    $courseid eq $env{'request.course.id'}) {
13443: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
13444: 				     $env{'course.'.$courseid.'.domain'},
13445: 				     'course',$mapp,\$recursed,\@recurseup,
13446:                                      $courseid,'.',$spacequalifierrest,
13447: 				     ([$courselevelm,'map'   ],
13448:                                       [$courseleveli,'map'   ],
13449: 				      [$courselevel, 'course']));
13450: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
13451: 	}
13452: # ------------------------------------------------------------------ Cascade up
13453: 	unless ($space eq '0') {
13454: 	    my @parts=split(/_/,$space);
13455: 	    my $id=pop(@parts);
13456: 	    my $part=join('_',@parts);
13457: 	    if ($part eq '') { $part='0'; }
13458: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
13459: 				 $symbparm,$udom,$uname,$section,1);
13460: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
13461: 	}
13462: 	if ($recurse) { return undef; }
13463: 	my $pack_def=&packages_tab_default($filename,$varname,$toolsymb);
13464: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
13465: # ---------------------------------------------------- Any other user namespace
13466:     } elsif ($realm eq 'environment') {
13467: # ----------------------------------------------------------------- environment
13468: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
13469: 	    return $env{'environment.'.$spacequalifierrest};
13470: 	} else {
13471: 	    if ($uname eq 'anonymous' && $udom eq '') {
13472: 		return '';
13473: 	    }
13474: 	    my %returnhash=&userenvironment($udom,$uname,
13475: 					    $spacequalifierrest);
13476: 	    return $returnhash{$spacequalifierrest};
13477: 	}
13478:     } elsif ($realm eq 'system') {
13479: # ----------------------------------------------------------------- system.time
13480: 	if ($space eq 'time') {
13481: 	    return time;
13482:         }
13483:     } elsif ($realm eq 'server') {
13484: # ----------------------------------------------------------------- system.time
13485: 	if ($space eq 'name') {
13486: 	    return $ENV{'SERVER_NAME'};
13487:         }
13488:     } elsif ($realm eq 'client') {
13489:         if ($space eq 'remote_addr') {
13490:             return &get_requestor_ip();
13491:         }
13492:     }
13493:     return '';
13494: }
13495: 
13496: sub get_reply {
13497:     my ($reply_value) = @_;
13498:     if (ref($reply_value) eq 'ARRAY') {
13499:         if (wantarray) {
13500: 	    return @$reply_value;
13501:         }
13502:         return $reply_value->[0];
13503:     } else {
13504:         return $reply_value;
13505:     }
13506: }
13507: 
13508: sub check_group_parms {
13509:     my ($courseid,$groups,$symbparm,$recurseparm,$mapparm,$what,$mapp,
13510:         $recursed,$recurseupref) = @_;
13511:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$recurseparm,'map'],
13512:                   [$what,'course']);
13513:     my $coursereply;
13514:     foreach my $group (@{$groups}) {
13515:         my @groupitems = ();
13516:         foreach my $level (@levels) {
13517:              my $item = $courseid.'.['.$group.'].'.$level->[0];
13518:              push(@groupitems,[$item,$level->[1]]);
13519:         }
13520:         my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
13521:                                    $env{'course.'.$courseid.'.domain'},
13522:                                    'course',$mapp,$recursed,$recurseupref,
13523:                                    $courseid,'.['.$group.'].',$what,
13524:                                    @groupitems);
13525:         last if (defined($coursereply));
13526:     }
13527:     return $coursereply;
13528: }
13529: 
13530: sub get_map_hierarchy {
13531:     my ($mapname,$courseid) = @_;
13532:     my @recurseup = ();
13533:     if ($mapname) {
13534:         if (($cachedmapkey eq $courseid) &&
13535:             (abs($cachedmaptime-time)<5)) {
13536:             if (ref($cachedmaps{$mapname}) eq 'ARRAY') {
13537:                 return @{$cachedmaps{$mapname}};
13538:             }
13539:         }
13540:         my $navmap = Apache::lonnavmaps::navmap->new();
13541:         if (ref($navmap)) {
13542:             @recurseup = $navmap->recurseup_maps($mapname);
13543:             undef($navmap);
13544:             $cachedmaps{$mapname} = \@recurseup;
13545:             $cachedmaptime=time;
13546:             $cachedmapkey=$courseid;
13547:         }
13548:     }
13549:     return @recurseup;
13550: }
13551: 
13552: }
13553: 
13554: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
13555:     my ($courseid,@groups) = @_;
13556:     @groups = sort(@groups);
13557:     return @groups;
13558: }
13559: 
13560: sub packages_tab_default {
13561:     my ($uri,$varname,$toolsymb)=@_;
13562:     my (undef,$part,$name)=split(/\./,$varname);
13563: 
13564:     my (@extension,@specifics,$do_default);
13565:     foreach my $package (split(/,/,&metadata($uri,'packages',$toolsymb))) {
13566: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
13567: 	if ($pack_type eq 'default') {
13568: 	    $do_default=1;
13569: 	} elsif ($pack_type eq 'extension') {
13570: 	    push(@extension,[$package,$pack_type,$pack_part]);
13571: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
13572: 	    # only look at packages defaults for packages that this id is
13573: 	    push(@specifics,[$package,$pack_type,$pack_part]);
13574: 	}
13575:     }
13576:     # first look for a package that matches the requested part id
13577:     foreach my $package (@specifics) {
13578: 	my (undef,$pack_type,$pack_part)=@{$package};
13579: 	next if ($pack_part ne $part);
13580: 	if (defined($packagetab{"$pack_type&$name&default"})) {
13581: 	    return $packagetab{"$pack_type&$name&default"};
13582: 	}
13583:     }
13584:     # look for any possible matching non extension_ package
13585:     foreach my $package (@specifics) {
13586: 	my (undef,$pack_type,$pack_part)=@{$package};
13587: 	if (defined($packagetab{"$pack_type&$name&default"})) {
13588: 	    return $packagetab{"$pack_type&$name&default"};
13589: 	}
13590: 	if ($pack_type eq 'part') { $pack_part='0'; }
13591: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
13592: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
13593: 	}
13594:     }
13595:     # look for any posible extension_ match
13596:     foreach my $package (@extension) {
13597: 	my ($package,$pack_type)=@{$package};
13598: 	if (defined($packagetab{"$pack_type&$name&default"})) {
13599: 	    return $packagetab{"$pack_type&$name&default"};
13600: 	}
13601: 	if (defined($packagetab{$package."&$name&default"})) {
13602: 	    return $packagetab{$package."&$name&default"};
13603: 	}
13604:     }
13605:     # look for a global default setting
13606:     if ($do_default && defined($packagetab{"default&$name&default"})) {
13607: 	return $packagetab{"default&$name&default"};
13608:     }
13609:     return undef;
13610: }
13611: 
13612: sub add_prefix_and_part {
13613:     my ($prefix,$part)=@_;
13614:     my $keyroot;
13615:     if (defined($prefix) && $prefix !~ /^__/) {
13616: 	# prefix that has a part already
13617: 	$keyroot=$prefix;
13618:     } elsif (defined($prefix)) {
13619: 	# prefix that is missing a part
13620: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
13621:     } else {
13622: 	# no prefix at all
13623: 	if (defined($part)) { $keyroot='_'.$part; }
13624:     }
13625:     return $keyroot;
13626: }
13627: 
13628: # ---------------------------------------------------------------- Get metadata
13629: 
13630: my %metaentry;
13631: my %importedpartids;
13632: my %importedrespids;
13633: sub metadata {
13634:     my ($uri,$what,$toolsymb,$liburi,$prefix,$depthcount)=@_;
13635:     $uri=&declutter($uri);
13636:     # if it is a non metadata possible uri return quickly
13637:     if (($uri eq '') || 
13638: 	(($uri =~ m|^/*adm/|) && 
13639: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard|ext\.tool)$})) ||
13640:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
13641: 	return undef;
13642:     }
13643:     if (($uri =~ /^priv/ || $uri=~m{^home/httpd/html/priv}) 
13644: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
13645: 	return undef;
13646:     }
13647:     my $filename=$uri;
13648:     $uri=~s/\.meta$//;
13649: #
13650: # Is the metadata already cached?
13651: # Look at timestamp of caching
13652: # Everything is cached by the main uri, libraries are never directly cached
13653: #
13654:     if (!defined($liburi)) {
13655: 	my ($result,$cached)=&is_cached_new('meta',$uri);
13656: 	if (defined($cached)) { return $result->{':'.$what}; }
13657:     }
13658: 
13659: #
13660: # If the uri is for an external tool the file from
13661: # which metadata should be retrieved depends on whether
13662: # the tool had been configured to be gradable (set in the Course
13663: # Editor or Resource Editor).
13664: #
13665: # If a valid symb has been included as the third arg in the call
13666: # to &metadata() that can be used to retrieve the value of
13667: # parameter_0_gradable set for the resource, and included in the
13668: # uploaded map containing the tool. The value is retrieved via
13669: # &EXT(), if a valid symb is available.  Otherwise the value of
13670: # gradable in the exttool_$marker.db file for the tool instance
13671: # is retrieved via &get().
13672: #
13673: # When lonuserstate::traceroute() calls lonnet::EXT() for 
13674: # hiddenresource and encrypturl (during course initialization)
13675: # the map-level parameter for resource.0.gradable included in the 
13676: # uploaded map containing the tool will not yet have been stored
13677: # in the user_course_parms.db file for the user's session, so in 
13678: # this case fall back to retrieving gradable status from the
13679: # exttool_$marker.db file.
13680: #
13681: # In order to avoid an infinite loop, &metadata() will return
13682: # before a call to &EXT(), if the uri is for an external tool
13683: # and the $what for which metadata is being requested is
13684: # parameter_0_gradable or 0_gradable.
13685: #
13686: 
13687:     if ($uri =~ /ext\.tool$/) {
13688:         if (($what eq 'parameter_0_gradable') || ($what eq '0_gradable')) {
13689:             return;
13690:         } else {
13691:             my ($checked,$use_passback);
13692:             if ($toolsymb ne '') {
13693:                 (undef,undef,my $tooluri) = &decode_symb($toolsymb);
13694:                 if (($tooluri eq $uri) && (&EXT('resource.0.gradable',$toolsymb))) {
13695:                     $checked = 1;
13696:                     if (&EXT('resource.0.gradable',$toolsymb) =~ /^yes$/i) {
13697:                         $use_passback = 1;
13698:                     }
13699:                 }
13700:             }
13701:             unless ($checked) {
13702:                 my ($ignore,$cdom,$cnum,$marker) = split(m{/},$uri);
13703:                 $marker=~s/\D//g;
13704:                 if ($marker) {
13705:                     my %toolsettings=&get('exttool_'.$marker,['gradable'],$cdom,$cnum);
13706:                     $use_passback = $toolsettings{'gradable'};
13707:                 }
13708:             }
13709:             if ($use_passback) {
13710:                 $filename = '/home/httpd/html/res/lib/templates/LTIpassback.tool';
13711:             } else {
13712:                 $filename = '/home/httpd/html/res/lib/templates/LTIstandard.tool';
13713:             }
13714:         }
13715:     }
13716: 
13717:     {
13718: # Imported parts would go here
13719:         my @origfiletagids=();
13720:         my $importedparts=0;
13721: 
13722: # Imported responseids would go here
13723:         my $importedresponses=0;
13724: #
13725: # Is this a recursive call for a library?
13726: #
13727: #	if (! exists($metacache{$uri})) {
13728: #	    $metacache{$uri}={};
13729: #	}
13730: 	my $cachetime = 60*60;
13731:         if ($liburi) {
13732: 	    $liburi=&declutter($liburi);
13733:             $filename=$liburi;
13734:         } else {
13735: 	    &devalidate_cache_new('meta',$uri);
13736: 	    undef(%metaentry);
13737: 	}
13738:         my %metathesekeys=();
13739:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
13740: 	my $metastring;
13741: 	if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
13742: 	    my $which = &hreflocation('','/'.($liburi || $uri));
13743: 	    $metastring = 
13744: 		&Apache::lonnet::ssi_body($which,
13745: 					  ('grade_target' => 'meta'));
13746: 	    $cachetime = 1; # only want this cached in the child not long term
13747: 	} elsif (($uri !~ m -^(editupload)/-) && 
13748:                  ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
13749: 	    my $file=&filelocation('',&clutter($filename));
13750: 	    #push(@{$metaentry{$uri.'.file'}},$file);
13751: 	    $metastring=&getfile($file);
13752: 	}
13753:         my $parser=HTML::LCParser->new(\$metastring);
13754:         my $token;
13755:         undef %metathesekeys;
13756:         while ($token=$parser->get_token) {
13757: 	    if ($token->[0] eq 'S') {
13758: 		if (defined($token->[2]->{'package'})) {
13759: #
13760: # This is a package - get package info
13761: #
13762: 		    my $package=$token->[2]->{'package'};
13763: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
13764: 		    if (defined($token->[2]->{'id'})) { 
13765: 			$keyroot.='_'.$token->[2]->{'id'}; 
13766: 		    }
13767: 		    if ($metaentry{':packages'}) {
13768: 			$metaentry{':packages'}.=','.$package.$keyroot;
13769: 		    } else {
13770: 			$metaentry{':packages'}=$package.$keyroot;
13771: 		    }
13772: 		    foreach my $pack_entry (keys(%packagetab)) {
13773: 			my $part=$keyroot;
13774: 			$part=~s/^\_//;
13775: 			if ($pack_entry=~/^\Q$package\E\&/ || 
13776: 			    $pack_entry=~/^\Q$package\E_0\&/) {
13777: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
13778: 			    # ignore package.tab specified default values
13779:                             # here &package_tab_default() will fetch those
13780: 			    if ($subp eq 'default') { next; }
13781: 			    my $value=$packagetab{$pack_entry};
13782: 			    my $unikey;
13783: 			    if ($pack =~ /_0$/) {
13784: 				$unikey='parameter_0_'.$name;
13785: 				$part=0;
13786: 			    } else {
13787: 				$unikey='parameter'.$keyroot.'_'.$name;
13788: 			    }
13789: 			    if ($subp eq 'display') {
13790: 				$value.=' [Part: '.$part.']';
13791: 			    }
13792: 			    $metaentry{':'.$unikey.'.part'}=$part;
13793: 			    $metathesekeys{$unikey}=1;
13794: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
13795: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
13796: 			    }
13797: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
13798: 				$metaentry{':'.$unikey}=
13799: 				    $metaentry{':'.$unikey.'.default'};
13800: 			    }
13801: 			}
13802: 		    }
13803: 		} else {
13804: #
13805: # This is not a package - some other kind of start tag
13806: #
13807: 		    my $entry=$token->[1];
13808: 		    my $unikey='';
13809: 
13810: 		    if ($entry eq 'import') {
13811: #
13812: # Importing a library here
13813: #
13814:                         my $location=$parser->get_text('/import');
13815:                         my $dir=$filename;
13816:                         $dir=~s|[^/]*$||;
13817:                         $location=&filelocation($dir,$location);
13818: 
13819:                         my $importid=$token->[2]->{'id'};
13820:                         my $importmode=$token->[2]->{'importmode'};
13821: #
13822: # Check metadata for imported file to
13823: # see if it contained response items
13824: #
13825:                         my ($origfile,@libfilekeys);
13826:                         my %currmetaentry = %metaentry;
13827:                         @libfilekeys = split(/,/,&metadata($location,'keys',undef,undef,undef,
13828:                                                            $depthcount+1));
13829:                         if (grep(/^responseorder$/,@libfilekeys)) {
13830:                             my $libresponseorder = &metadata($location,'responseorder',undef,undef,
13831:                                                              undef,$depthcount+1);
13832:                             if ($libresponseorder ne '') {
13833:                                 if ($#origfiletagids<0) {
13834:                                     undef(%importedrespids);
13835:                                     undef(%importedpartids);
13836:                                 }
13837:                                 my @respids = split(/\s*,\s*/,$libresponseorder);
13838:                                 if (@respids) {
13839:                                     $importedrespids{$importid} = join(',',map { $importid.'_'.$_ } @respids);
13840:                                 }
13841:                                 if ($importedrespids{$importid} ne '') {
13842:                                     $importedresponses = 1;
13843: # We need to get the original file and the imported file to get the response order correct
13844: # Load and inspect original file
13845:                                     if ($#origfiletagids<0) {
13846:                                         my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
13847:                                         $origfile=&getfile($origfilelocation);
13848:                                         @origfiletagids=($origfile=~/<((?:\w+)response|import|part)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
13849:                                     }
13850:                                 }
13851:                             }
13852:                         }
13853: # Do not overwrite contents of %metaentry hash for resource itself with 
13854: # hash populated for imported library file
13855:                         %metaentry = %currmetaentry;
13856:                         undef(%currmetaentry);
13857:                         if ($importmode eq 'part') {
13858: # Import as part(s)
13859:                            $importedparts=1;
13860: # We need to get the original file and the imported file to get the part order correct
13861: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
13862: # Load and inspect original file if we didn't do that already
13863:                            if ($#origfiletagids<0) {
13864:                                undef(%importedrespids);
13865:                                undef(%importedpartids);
13866:                                if ($origfile eq '') {
13867:                                    my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
13868:                                    $origfile=&getfile($origfilelocation);
13869:                                    @origfiletagids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
13870:                                }
13871:                            }
13872:                            my @impfilepartids;
13873: # If <partorder> tag is included in metadata for the imported file
13874: # get the parts in the imported file from that.
13875:                            if (grep(/^partorder$/,@libfilekeys)) {
13876:                                %currmetaentry = %metaentry;
13877:                                my $libpartorder = &metadata($location,'partorder',undef,undef,undef,
13878:                                                             $depthcount+1);
13879:                                %metaentry = %currmetaentry;
13880:                                undef(%currmetaentry);
13881:                                if ($libpartorder ne '') {
13882:                                    @impfilepartids=split(/\s*,\s*/,$libpartorder);
13883:                                }
13884:                            } else {
13885: # If no <partorder> tag available, load and inspect imported file
13886:                                my $impfile=&getfile($location);
13887:                                @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
13888:                            }
13889:                            if ($#impfilepartids>=0) {
13890: # This problem had parts
13891:                                $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
13892:                            } else {
13893: # Importing by turning a single problem into a problem part
13894: # It gets the import-tags ID as part-ID
13895:                                $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
13896:                                $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
13897:                            }
13898:                         } else {
13899: # Import as problem or as normal import
13900:                             $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
13901:                             unless ($importmode eq 'problem') {
13902: # Normal import
13903:                                 if (defined($token->[2]->{'id'})) {
13904:                                     $unikey.='_'.$token->[2]->{'id'};
13905:                                 }
13906:                             }
13907: # Check metadata for imported file to
13908: # see if it contained parts
13909:                             if (grep(/^partorder$/,@libfilekeys)) {
13910:                                 %currmetaentry = %metaentry;
13911:                                 my $libpartorder = &metadata($location,'partorder',undef,undef,undef,
13912:                                                              $depthcount+1);
13913:                                 %metaentry = %currmetaentry;
13914:                                 undef(%currmetaentry);
13915:                                 if ($libpartorder ne '') {
13916:                                     $importedparts = 1;
13917:                                     $importedpartids{$token->[2]->{'id'}}=$libpartorder;
13918:                                 }
13919:                             }
13920:                         }
13921: 			if ($depthcount<20) {
13922: 			    my $metadata = 
13923: 				&metadata($uri,'keys',$toolsymb,$location,$unikey,
13924: 					  $depthcount+1);
13925: 			    foreach my $meta (split(',',$metadata)) {
13926: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
13927: 				$metathesekeys{$meta}=1;
13928: 			    }
13929:                         }
13930: 		    } else {
13931: #
13932: # Not importing, some other kind of non-package, non-library start tag
13933: # 
13934:                         $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
13935:                         if (defined($token->[2]->{'id'})) {
13936:                             $unikey.='_'.$token->[2]->{'id'};
13937:                         }
13938: 			if (defined($token->[2]->{'name'})) { 
13939: 			    $unikey.='_'.$token->[2]->{'name'}; 
13940: 			}
13941: 			$metathesekeys{$unikey}=1;
13942: 			foreach my $param (@{$token->[3]}) {
13943: 			    $metaentry{':'.$unikey.'.'.$param} =
13944: 				$token->[2]->{$param};
13945: 			}
13946: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
13947: 			my $default=$metaentry{':'.$unikey.'.default'};
13948: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
13949: 		 # only ws inside the tag, and not in default, so use default
13950: 		 # as value
13951: 			    $metaentry{':'.$unikey}=$default;
13952: 			} elsif ( $internaltext =~ /\S/ ) {
13953: 		  # something interesting inside the tag
13954: 			    $metaentry{':'.$unikey}=$internaltext;
13955: 			} else {
13956: 		  # no interesting values, don't set a default
13957: 			}
13958: # end of not-a-package not-a-library import
13959: 		    }
13960: # end of not-a-package start tag
13961: 		}
13962: # the next is the end of "start tag"
13963: 	    }
13964: 	}
13965: 	my ($extension) = ($uri =~ /\.(\w+)$/);
13966: 	$extension = lc($extension);
13967: 	if ($extension eq 'htm') { $extension='html'; }
13968: 
13969: 	foreach my $key (keys(%packagetab)) {
13970: 	    #no specific packages #how's our extension
13971: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
13972: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
13973: 					 \%metathesekeys);
13974: 	}
13975: 
13976: 	if (!exists($metaentry{':packages'})
13977: 	    || $packagetab{"import_defaults&extension_$extension"}) {
13978: 	    foreach my $key (keys(%packagetab)) {
13979: 		#no specific packages well let's get default then
13980: 		if ($key!~/^default&/) { next; }
13981: 		&metadata_create_package_def($uri,$key,'default',
13982: 					     \%metathesekeys);
13983: 	    }
13984: 	}
13985: # are there custom rights to evaluate
13986: 	if ($metaentry{':copyright'} eq 'custom') {
13987: 
13988:     #
13989:     # Importing a rights file here
13990:     #
13991: 	    unless ($depthcount) {
13992: 		my $location=$metaentry{':customdistributionfile'};
13993: 		my $dir=$filename;
13994: 		$dir=~s|[^/]*$||;
13995: 		$location=&filelocation($dir,$location);
13996: 		my $rights_metadata =
13997: 		    &metadata($uri,'keys',$toolsymb,$location,'_rights',
13998: 			      $depthcount+1);
13999: 		foreach my $rights (split(',',$rights_metadata)) {
14000: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
14001: 		    $metathesekeys{$rights}=1;
14002: 		}
14003: 	    }
14004: 	}
14005: 	# uniqifiy package listing
14006: 	my %seen;
14007: 	my @uniq_packages =
14008: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
14009: 	$metaentry{':packages'} = join(',',@uniq_packages);
14010: 
14011:         if (($importedresponses) || ($importedparts)) {
14012:             if ($importedparts) {
14013: # We had imported parts and need to rebuild partorder
14014:                 $metaentry{':partorder'}='';
14015:                 $metathesekeys{'partorder'}=1;
14016:             }
14017:             if ($importedresponses) {
14018: # We had imported responses and need to rebuil responseorder
14019:                 $metaentry{':responseorder'}='';
14020:                 $metathesekeys{'responseorder'}=1;
14021:             }
14022:             for (my $index=0;$index<$#origfiletagids;$index+=2) {
14023:                 my $origid = $origfiletagids[$index+1];
14024:                 if ($origfiletagids[$index] eq 'part') {
14025: # Original part, part of the problem
14026:                     if ($importedparts) {
14027:                         $metaentry{':partorder'}.=','.$origid;
14028:                     }
14029:                 } elsif ($origfiletagids[$index] eq 'import') {
14030:                     if ($importedparts) {
14031: # We have imported parts at this position
14032:                         if ($importedpartids{$origid} ne '') {
14033:                             $metaentry{':partorder'}.=','.$importedpartids{$origid};
14034:                         }
14035:                     }
14036:                     if ($importedresponses) {
14037: # We have imported responses at this position
14038:                         if ($importedrespids{$origid} ne '') {
14039:                             $metaentry{':responseorder'}.=','.$importedrespids{$origid};
14040:                         }
14041:                     }
14042:                 } else {
14043: # Original response item, part of the problem
14044:                     if ($importedresponses) {
14045:                         $metaentry{':responseorder'}.=','.$origid;
14046:                     }
14047:                 }
14048:             }
14049:             if ($importedparts) {
14050:                 $metaentry{':partorder'}=~s/^\,//;
14051:             }
14052:             if ($importedresponses) {
14053:                 $metaentry{':responseorder'}=~s/^\,//;
14054:             }
14055:         }
14056: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
14057: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
14058: 	$metaentry{':allpossiblekeys'}=join(',',keys(%metathesekeys));
14059:         unless ($liburi) {
14060: 	    &do_cache_new('meta',$uri,\%metaentry,$cachetime);
14061:         }
14062: # this is the end of "was not already recently cached
14063:     }
14064:     return $metaentry{':'.$what};
14065: }
14066: 
14067: sub metadata_create_package_def {
14068:     my ($uri,$key,$package,$metathesekeys)=@_;
14069:     my ($pack,$name,$subp)=split(/\&/,$key);
14070:     if ($subp eq 'default') { next; }
14071:     
14072:     if (defined($metaentry{':packages'})) {
14073: 	$metaentry{':packages'}.=','.$package;
14074:     } else {
14075: 	$metaentry{':packages'}=$package;
14076:     }
14077:     my $value=$packagetab{$key};
14078:     my $unikey;
14079:     $unikey='parameter_0_'.$name;
14080:     $metaentry{':'.$unikey.'.part'}=0;
14081:     $$metathesekeys{$unikey}=1;
14082:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
14083: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
14084:     }
14085:     if (defined($metaentry{':'.$unikey.'.default'})) {
14086: 	$metaentry{':'.$unikey}=
14087: 	    $metaentry{':'.$unikey.'.default'};
14088:     }
14089: }
14090: 
14091: sub metadata_generate_part0 {
14092:     my ($metadata,$metacache,$uri) = @_;
14093:     my %allnames;
14094:     foreach my $metakey (keys(%$metadata)) {
14095: 	if ($metakey=~/^parameter\_(.*)/) {
14096: 	  my $part=$$metacache{':'.$metakey.'.part'};
14097: 	  my $name=$$metacache{':'.$metakey.'.name'};
14098: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
14099: 	    $allnames{$name}=$part;
14100: 	  }
14101: 	}
14102:     }
14103:     foreach my $name (keys(%allnames)) {
14104:       $$metadata{"parameter_0_$name"}=1;
14105:       my $key=":parameter_0_$name";
14106:       $$metacache{"$key.part"}='0';
14107:       $$metacache{"$key.name"}=$name;
14108:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
14109: 					   $allnames{$name}.'_'.$name.
14110: 					   '.type'};
14111:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
14112: 			     '.display'};
14113:       my $expr='[Part: '.$allnames{$name}.']';
14114:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
14115:       $$metacache{"$key.display"}=$olddis;
14116:     }
14117: }
14118: 
14119: # ------------------------------------------------------ Devalidate title cache
14120: 
14121: sub devalidate_title_cache {
14122:     my ($url)=@_;
14123:     if (!$env{'request.course.id'}) { return; }
14124:     my $symb=&symbread($url);
14125:     if (!$symb) { return; }
14126:     my $key=$env{'request.course.id'}."\0".$symb;
14127:     &devalidate_cache_new('title',$key);
14128: }
14129: 
14130: # ------------------------------------------------- Get the title of a course
14131: 
14132: sub current_course_title {
14133:     return $env{ 'course.' . $env{'request.course.id'} . '.description' };
14134: }
14135: # ------------------------------------------------- Get the title of a resource
14136: 
14137: sub gettitle {
14138:     my $urlsymb=shift;
14139:     my $symb=&symbread($urlsymb);
14140:     if ($symb) {
14141: 	my $key=$env{'request.course.id'}."\0".$symb;
14142: 	my ($result,$cached)=&is_cached_new('title',$key);
14143: 	if (defined($cached)) { 
14144: 	    return $result;
14145: 	}
14146: 	my ($map,$resid,$url)=&decode_symb($symb);
14147: 	my $title='';
14148: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
14149: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
14150: 	} else {
14151: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
14152: 		    &GDBM_READER(),0640)) {
14153: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
14154: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
14155: 		untie(%bighash);
14156: 	    }
14157: 	}
14158: 	$title=~s/\&colon\;/\:/gs;
14159: 	if ($title) {
14160: # Remember both $symb and $title for dynamic metadata
14161:             $accesshash{$symb.'___crstitle'}=$title;
14162:             $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
14163: # Cache this title and then return it
14164: 	    return &do_cache_new('title',$key,$title,600);
14165: 	}
14166: 	$urlsymb=$url;
14167:     }
14168:     my $title=&metadata($urlsymb,'title');
14169:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
14170:     return $title;
14171: }
14172: 
14173: sub get_slot {
14174:     my ($which,$cnum,$cdom)=@_;
14175:     if (!$cnum || !$cdom) {
14176: 	(undef,my $courseid)=&whichuser();
14177: 	$cdom=$env{'course.'.$courseid.'.domain'};
14178: 	$cnum=$env{'course.'.$courseid.'.num'};
14179:     }
14180:     my $key=join("\0",'slots',$cdom,$cnum,$which);
14181:     my %slotinfo;
14182:     if (exists($remembered{$key})) {
14183: 	$slotinfo{$which} = $remembered{$key};
14184:     } else {
14185: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
14186: 	&Apache::lonhomework::showhash(%slotinfo);
14187: 	my ($tmp)=keys(%slotinfo);
14188: 	if ($tmp=~/^error:/) { return (); }
14189: 	$remembered{$key} = $slotinfo{$which};
14190:     }
14191:     if (ref($slotinfo{$which}) eq 'HASH') {
14192: 	return %{$slotinfo{$which}};
14193:     }
14194:     return $slotinfo{$which};
14195: }
14196: 
14197: sub get_reservable_slots {
14198:     my ($cnum,$cdom,$uname,$udom) = @_;
14199:     my $now = time;
14200:     my $reservable_info;
14201:     my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
14202:     if (exists($remembered{$key})) {
14203:         $reservable_info = $remembered{$key};
14204:     } else {
14205:         my %resv;
14206:         ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
14207:         &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
14208:         $reservable_info = \%resv;
14209:         $remembered{$key} = $reservable_info;
14210:     }
14211:     return $reservable_info;
14212: }
14213: 
14214: sub get_course_slots {
14215:     my ($cnum,$cdom) = @_;
14216:     my $hashid=$cnum.':'.$cdom;
14217:     my ($result,$cached) = &is_cached_new('allslots',$hashid);
14218:     if (defined($cached)) {
14219:         if (ref($result) eq 'HASH') {
14220:             return %{$result};
14221:         }
14222:     } else {
14223:         my %slots=&dump('slots',$cdom,$cnum);
14224:         my ($tmp) = keys(%slots);
14225:         if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
14226:             &do_cache_new('allslots',$hashid,\%slots,600);
14227:             return %slots;
14228:         }
14229:     }
14230:     return;
14231: }
14232: 
14233: sub devalidate_slots_cache {
14234:     my ($cnum,$cdom)=@_;
14235:     my $hashid=$cnum.':'.$cdom;
14236:     &devalidate_cache_new('allslots',$hashid);
14237: }
14238: 
14239: sub get_coursechange {
14240:     my ($cdom,$cnum) = @_;
14241:     if ($cdom eq '' || $cnum eq '') {
14242:         return unless ($env{'request.course.id'});
14243:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
14244:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
14245:     }
14246:     my $hashid=$cdom.'_'.$cnum;
14247:     my ($change,$cached)=&is_cached_new('crschange',$hashid);
14248:     if ((defined($cached)) && ($change ne '')) {
14249:         return $change;
14250:     } else {
14251:         my %crshash;
14252:         %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
14253:         if ($crshash{'internal.contentchange'} eq '') {
14254:             $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
14255:             if ($change eq '') {
14256:                 %crshash = &get('environment',['internal.created'],$cdom,$cnum);
14257:                 $change = $crshash{'internal.created'};
14258:             }
14259:         } else {
14260:             $change = $crshash{'internal.contentchange'};
14261:         }
14262:         my $cachetime = 600;
14263:         &do_cache_new('crschange',$hashid,$change,$cachetime);
14264:     }
14265:     return $change;
14266: }
14267: 
14268: sub devalidate_coursechange_cache {
14269:     my ($cdom,$cnum)=@_;
14270:     my $hashid=$cdom.'_'.$cnum;
14271:     &devalidate_cache_new('crschange',$hashid);
14272: }
14273: 
14274: sub get_suppchange {
14275:     my ($cdom,$cnum) = @_;
14276:     if ($cdom eq '' || $cnum eq '') {
14277:         return unless ($env{'request.course.id'});
14278:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
14279:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
14280:     }
14281:     my $hashid=$cdom.'_'.$cnum;
14282:     my ($change,$cached)=&is_cached_new('suppchange',$hashid);
14283:     if ((defined($cached)) && ($change ne '')) {
14284:         return $change;
14285:     } else {
14286:         my %crshash = &get('environment',['internal.supplementalchange'],$cdom,$cnum);
14287:         if ($crshash{'internal.supplementalchange'} eq '') {
14288:             $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
14289:             if ($change eq '') {
14290:                 %crshash = &get('environment',['internal.created'],$cdom,$cnum);
14291:                 $change = $crshash{'internal.created'};
14292:             }
14293:         } else {
14294:             $change = $crshash{'internal.supplementalchange'};
14295:         }
14296:         my $cachetime = 600;
14297:         &do_cache_new('suppchange',$hashid,$change,$cachetime);
14298:     }
14299:     return $change;
14300: }
14301: 
14302: sub devalidate_suppchange_cache {
14303:     my ($cdom,$cnum)=@_;
14304:     my $hashid=$cdom.'_'.$cnum;
14305:     &devalidate_cache_new('suppchange',$hashid);
14306: }
14307: 
14308: sub update_supp_caches {
14309:     my ($cdom,$cnum) = @_;
14310:     my %servers = &internet_dom_servers($cdom);
14311:     my @ids=&current_machine_ids();
14312:     foreach my $server (keys(%servers)) {
14313:         next if (grep(/^\Q$server\E$/,@ids));
14314:         my $hashid=$cnum.':'.$cdom;
14315:         my $cachekey = &escape('showsupp').':'.&escape($hashid);
14316:         &remote_devalidate_cache($server,[$cachekey]);
14317:     }
14318:     &has_unhidden_suppfiles($cnum,$cdom,1,1);
14319:     &count_supptools($cnum,$cdom,1);
14320:     my $now = time;
14321:     if ($env{'request.course.id'} eq $cdom.'_'.$cnum) {
14322:         &Apache::lonnet::appenv({'request.course.suppupdated' => $now});
14323:     }
14324:     &put('environment',{'internal.supplementalchange' => $now},
14325:          $cdom,$cnum);
14326:     &Apache::lonnet::appenv(
14327:         {'course.'.$cdom.'_'.$cnum.'.internal.supplementalchange' => $now});
14328:     &do_cache_new('suppchange',$cdom.'_'.$cnum,$now,600);
14329: }
14330: 
14331: # ------------------------------------------------- Update symbolic store links
14332: 
14333: sub symblist {
14334:     my ($mapname,%newhash)=@_;
14335:     $mapname=&deversion(&declutter($mapname));
14336:     my %hash;
14337:     if (($env{'request.course.fn'}) && (%newhash)) {
14338:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
14339:                       &GDBM_WRCREAT(),0640)) {
14340: 	    foreach my $url (keys(%newhash)) {
14341: 		next if ($url eq 'last_known'
14342: 			 && $env{'form.no_update_last_known'});
14343: 		$hash{declutter($url)}=&encode_symb($mapname,
14344: 						    $newhash{$url}->[1],
14345: 						    $newhash{$url}->[0]);
14346:             }
14347:             if (untie(%hash)) {
14348: 		return 'ok';
14349:             }
14350:         }
14351:     }
14352:     return 'error';
14353: }
14354: 
14355: # --------------------------------------------------------------- Verify a symb
14356: 
14357: sub symbverify {
14358:     my ($symb,$thisurl,$encstate)=@_;
14359:     my $thisfn=$thisurl;
14360:     $thisfn=&declutter($thisfn);
14361: # direct jump to resource in page or to a sequence - will construct own symbs
14362:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
14363: # check URL part
14364:     my ($map,$resid,$url)=&decode_symb($symb);
14365: 
14366:     unless ($url eq $thisfn) { return 0; }
14367: 
14368:     $symb=&symbclean($symb);
14369:     $thisurl=&deversion($thisurl);
14370:     $thisfn=&deversion($thisfn);
14371: 
14372:     my %bighash;
14373:     my $okay=0;
14374: 
14375:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
14376:                             &GDBM_READER(),0640)) {
14377:         if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
14378:             $thisurl =~ s/\?.+$//;
14379:             if ($map =~ m{^uploaded/.+\.page$}) {
14380:                 $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
14381:                 $thisurl =~ s{^\Qhttp://https://\E}{https://};
14382:             }
14383:         }
14384:         my $ids;
14385:         if ($map =~ m{^uploaded/.+\.page$}) {
14386:             $ids=$bighash{'ids_'.&clutter_with_no_wrapper($thisurl)};
14387:         } else {
14388:             $ids=$bighash{'ids_'.&clutter($thisurl)};
14389:         }
14390:         unless ($ids) {
14391:             my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;  
14392:             $ids=$bighash{$idkey};
14393:         }
14394:         if ($ids) {
14395: # ------------------------------------------------------------------- Has ID(s)
14396:             if ($thisfn =~ m{^/adm/wrapper/ext/}) {
14397:                 $symb =~ s/\?.+$//;
14398:             }
14399: 	    foreach my $id (split(/\,/,$ids)) {
14400: 	       my ($mapid,$resid)=split(/\./,$id);
14401:                if (
14402:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
14403:    eq $symb) {
14404:                    if (ref($encstate)) {
14405:                        $$encstate = $bighash{'encrypted_'.$id};
14406:                    }
14407: 		   if (($env{'request.role.adv'}) ||
14408: 		       ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
14409:                        ($thisurl eq '/adm/navmaps')) {
14410: 		       $okay=1;
14411:                        last;
14412: 		   }
14413: 	       }
14414: 	   }
14415:         }
14416: 	untie(%bighash);
14417:     }
14418:     return $okay;
14419: }
14420: 
14421: # --------------------------------------------------------------- Clean-up symb
14422: 
14423: sub symbclean {
14424:     my $symb=shift;
14425:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
14426: # remove version from map
14427:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
14428: 
14429: # remove version from URL
14430:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
14431: 
14432: # remove wrapper
14433: 
14434:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
14435:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
14436:     return $symb;
14437: }
14438: 
14439: # ---------------------------------------------- Split symb to find map and url
14440: 
14441: sub encode_symb {
14442:     my ($map,$resid,$url)=@_;
14443:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
14444: }
14445: 
14446: sub decode_symb {
14447:     my $symb=shift;
14448:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
14449:     my ($map,$resid,$url)=split(/___/,$symb);
14450:     return (&fixversion($map),$resid,&fixversion($url));
14451: }
14452: 
14453: sub fixversion {
14454:     my $fn=shift;
14455:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
14456:     my %bighash;
14457:     my $uri=&clutter($fn);
14458:     my $key=$env{'request.course.id'}.'_'.$uri;
14459: # is this cached?
14460:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
14461:     if (defined($cached)) { return $result; }
14462: # unfortunately not cached, or expired
14463:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
14464: 	    &GDBM_READER(),0640)) {
14465:  	if ($bighash{'version_'.$uri}) {
14466:  	    my $version=$bighash{'version_'.$uri};
14467:  	    unless (($version eq 'mostrecent') || 
14468: 		    ($version==&getversion($uri))) {
14469:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
14470:  	    }
14471:  	}
14472:  	untie %bighash;
14473:     }
14474:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
14475: }
14476: 
14477: sub deversion {
14478:     my $url=shift;
14479:     $url=~s/\.\d+\.(\w+)$/\.$1/;
14480:     return $url;
14481: }
14482: 
14483: # ------------------------------------------------------ Return symb list entry
14484: 
14485: sub symbread {
14486:     my ($thisfn,$donotrecurse,$ignorecachednull,$checkforblock,$possibles,
14487:         $ignoresymbdb,$noenccheck)=@_;
14488:     my $cache_str='request.symbread.cached.'.$thisfn;
14489:     if (defined($env{$cache_str})) {
14490:         unless (ref($possibles) eq 'HASH') {
14491:             if ($ignorecachednull) {
14492:                 return $env{$cache_str} unless ($env{$cache_str} eq '');
14493:             } else {
14494:                 return $env{$cache_str};
14495:             }
14496:         }
14497:     }
14498: # no filename provided? try from environment
14499:     unless ($thisfn) {
14500:         if ($env{'request.symb'}) {
14501:             return $env{$cache_str}=&symbclean($env{'request.symb'});
14502: 	}
14503: 	$thisfn=$env{'request.filename'};
14504:     }
14505:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
14506: # is that filename actually a symb? Verify, clean, and return
14507:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
14508: 	if (&symbverify($thisfn,$1)) {
14509: 	    return $env{$cache_str}=&symbclean($thisfn);
14510: 	}
14511:     }
14512:     $thisfn=declutter($thisfn);
14513:     my %hash;
14514:     my %bighash;
14515:     my $syval='';
14516:     if (($env{'request.course.fn'}) && ($thisfn)) {
14517:         unless ($ignoresymbdb) {
14518:             if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
14519:                           &GDBM_READER(),0640)) {
14520: 	        $syval=$hash{$thisfn};
14521:                 untie(%hash);
14522:             }
14523:             if ($syval && $checkforblock) {
14524:                 my @blockers = &has_comm_blocking('bre',$syval,$thisfn,$ignoresymbdb,$noenccheck);
14525:                 if (@blockers) {
14526:                     $syval='';
14527:                 }
14528:             }
14529:         }
14530: # ---------------------------------------------------------- There was an entry
14531:         if ($syval) {
14532: 	    #unless ($syval=~/\_\d+$/) {
14533: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
14534: 		    #&appenv({'request.ambiguous' => $thisfn});
14535: 		    #return $env{$cache_str}='';
14536: 		#}    
14537: 		#$syval.=$1;
14538: 	    #}
14539:         } else {
14540: # ------------------------------------------------------- Was not in symb table
14541:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
14542:                             &GDBM_READER(),0640)) {
14543: # ---------------------------------------------- Get ID(s) for current resource
14544:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
14545:               unless ($ids) { 
14546:                  $ids=$bighash{'ids_/'.$thisfn};
14547:               }
14548:               unless ($ids) {
14549: # alias?
14550: 		  $ids=$bighash{'mapalias_'.$thisfn};
14551:               }
14552:               if ($ids) {
14553: # ------------------------------------------------------------------- Has ID(s)
14554:                  my @possibilities=split(/\,/,$ids);
14555:                  if ($#possibilities==0) {
14556: # ----------------------------------------------- There is only one possibility
14557: 		     my ($mapid,$resid)=split(/\./,$ids);
14558: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
14559: 						    $resid,$thisfn);
14560:                      if (ref($possibles) eq 'HASH') {
14561:                          unless ($bighash{'randomout_'.$ids} || $env{'request.role.adv'}) {
14562:                              $possibles->{$syval} = 1;
14563:                          }
14564:                      }
14565:                      if ($checkforblock) {
14566:                          unless ($bighash{'randomout_'.$ids} || $env{'request.role.adv'}) {
14567:                              my @blockers = &has_comm_blocking('bre',$syval,$bighash{'src_'.$ids},'',$noenccheck);
14568:                              if (@blockers) {
14569:                                  $syval = '';
14570:                                  untie(%bighash);
14571:                                  return $env{$cache_str}='';
14572:                              }
14573:                          }
14574:                      }
14575:                  } elsif ((!$donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) { 
14576: # ------------------------------------------ There is more than one possibility
14577:                      my $realpossible=0;
14578:                      foreach my $id (@possibilities) {
14579: 			 my $file=$bighash{'src_'.$id};
14580:                          my $canaccess;
14581:                          if (($donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
14582:                              $canaccess = 1;
14583:                          } else { 
14584:                              $canaccess = &allowed('bre',$file);
14585:                          }
14586:                          if ($canaccess) {
14587:          		     my ($mapid,$resid)=split(/\./,$id);
14588:                              if ($bighash{'map_type_'.$mapid} ne 'page') {
14589:                                  my $poss_syval=&encode_symb($bighash{'map_id_'.$mapid},
14590: 						             $resid,$thisfn);
14591:                                  next if ($bighash{'randomout_'.$id} && !$env{'request.role.adv'});
14592:                                  next unless (($noenccheck) || ($bighash{'encrypted_'.$id} eq $env{'request.enc'}));
14593:                                  if ($checkforblock) {
14594:                                      my @blockers = &has_comm_blocking('bre',$poss_syval,$file,'',$noenccheck);
14595:                                      if (@blockers > 0) {
14596:                                          $syval = '';
14597:                                      } else {
14598:                                          $syval = $poss_syval;
14599:                                          $realpossible++;
14600:                                      }
14601:                                  } else {
14602:                                      $syval = $poss_syval;
14603:                                      $realpossible++;
14604:                                  }
14605:                                  if ($syval) {
14606:                                      if (ref($possibles) eq 'HASH') {
14607:                                          $possibles->{$syval} = 1;
14608:                                      }
14609:                                  }
14610:                              }
14611: 			 }
14612:                      }
14613: 		     if ($realpossible!=1) { $syval=''; }
14614:                  } else {
14615:                      $syval='';
14616:                  }
14617: 	      }
14618:               untie(%bighash);
14619:            }
14620:         }
14621:         if ($syval) {
14622: 	    return $env{$cache_str}=$syval;
14623:         }
14624:     }
14625:     &appenv({'request.ambiguous' => $thisfn});
14626:     return $env{$cache_str}='';
14627: }
14628: 
14629: # ---------------------------------------------------------- Return random seed
14630: 
14631: sub numval {
14632:     my $txt=shift;
14633:     $txt=~tr/A-J/0-9/;
14634:     $txt=~tr/a-j/0-9/;
14635:     $txt=~tr/K-T/0-9/;
14636:     $txt=~tr/k-t/0-9/;
14637:     $txt=~tr/U-Z/0-5/;
14638:     $txt=~tr/u-z/0-5/;
14639:     $txt=~s/\D//g;
14640:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
14641:     return int($txt);
14642: }
14643: 
14644: sub numval2 {
14645:     my $txt=shift;
14646:     $txt=~tr/A-J/0-9/;
14647:     $txt=~tr/a-j/0-9/;
14648:     $txt=~tr/K-T/0-9/;
14649:     $txt=~tr/k-t/0-9/;
14650:     $txt=~tr/U-Z/0-5/;
14651:     $txt=~tr/u-z/0-5/;
14652:     $txt=~s/\D//g;
14653:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
14654:     my $total;
14655:     foreach my $val (@txts) { $total+=$val; }
14656:     if ($_64bit) { if ($total > 2**32) { return -1; } }
14657:     return int($total);
14658: }
14659: 
14660: sub numval3 {
14661:     use integer;
14662:     my $txt=shift;
14663:     $txt=~tr/A-J/0-9/;
14664:     $txt=~tr/a-j/0-9/;
14665:     $txt=~tr/K-T/0-9/;
14666:     $txt=~tr/k-t/0-9/;
14667:     $txt=~tr/U-Z/0-5/;
14668:     $txt=~tr/u-z/0-5/;
14669:     $txt=~s/\D//g;
14670:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
14671:     my $total;
14672:     foreach my $val (@txts) { $total+=$val; }
14673:     if ($_64bit) { $total=(($total<<32)>>32); }
14674:     return $total;
14675: }
14676: 
14677: sub digest {
14678:     my ($data)=@_;
14679:     my $digest=&Digest::MD5::md5($data);
14680:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
14681:     my ($e,$f);
14682:     {
14683:         use integer;
14684:         $e=($a+$b);
14685:         $f=($c+$d);
14686:         if ($_64bit) {
14687:             $e=(($e<<32)>>32);
14688:             $f=(($f<<32)>>32);
14689:         }
14690:     }
14691:     if (wantarray) {
14692: 	return ($e,$f);
14693:     } else {
14694: 	my $g;
14695: 	{
14696: 	    use integer;
14697: 	    $g=($e+$f);
14698: 	    if ($_64bit) {
14699: 		$g=(($g<<32)>>32);
14700: 	    }
14701: 	}
14702: 	return $g;
14703:     }
14704: }
14705: 
14706: sub latest_rnd_algorithm_id {
14707:     return '64bit5';
14708: }
14709: 
14710: sub get_rand_alg {
14711:     my ($courseid)=@_;
14712:     if (!$courseid) { $courseid=(&whichuser())[1]; }
14713:     if ($courseid) {
14714: 	return $env{"course.$courseid.rndseed"};
14715:     }
14716:     return &latest_rnd_algorithm_id();
14717: }
14718: 
14719: sub validCODE {
14720:     my ($CODE)=@_;
14721:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
14722:     return 0;
14723: }
14724: 
14725: sub getCODE {
14726:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
14727:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
14728: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
14729: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
14730: 	return $Apache::lonhomework::history{'resource.CODE'};
14731:     }
14732:     return undef;
14733: }
14734: #
14735: #  Determines the random seed for a specific context:
14736: #
14737: # parameters:
14738: #   symb      - in course context the symb for the seed.
14739: #   course_id - The course id of the form domain_coursenum.
14740: #   domain    - Domain for the user.
14741: #   course    - Course for the user.
14742: #   cenv      - environment of the course.
14743: #
14744: # NOTE:
14745: #   All parameters are picked out of the environment if missing
14746: #   or not defined.
14747: #   If a symb cannot be determined the current time is used instead.
14748: #
14749: #  For a given well defined symb, courside, domain, username,
14750: #  and course environment, the seed is reproducible.
14751: #
14752: sub rndseed {
14753:     my ($symb,$courseid,$domain,$username, $cenv)=@_;
14754:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
14755:     if (!defined($symb)) {
14756: 	unless ($symb=$wsymb) { return time; }
14757:     }
14758:     if (!defined $courseid) { 
14759: 	$courseid=$wcourseid; 
14760:     }
14761:     if (!defined $domain) { $domain=$wdomain; }
14762:     if (!defined $username) { $username=$wusername }
14763: 
14764:     my $which;
14765:     if (defined($cenv->{'rndseed'})) {
14766: 	$which = $cenv->{'rndseed'};
14767:     } else {
14768: 	$which =&get_rand_alg($courseid);
14769:     }
14770:     if (defined(&getCODE())) {
14771: 
14772: 	if ($which eq '64bit5') {
14773: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
14774: 	} elsif ($which eq '64bit4') {
14775: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
14776: 	} else {
14777: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
14778: 	}
14779:     } elsif ($which eq '64bit5') {
14780: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
14781:     } elsif ($which eq '64bit4') {
14782: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
14783:     } elsif ($which eq '64bit3') {
14784: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
14785:     } elsif ($which eq '64bit2') {
14786: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
14787:     } elsif ($which eq '64bit') {
14788: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
14789:     }
14790:     return &rndseed_32bit($symb,$courseid,$domain,$username);
14791: }
14792: 
14793: sub rndseed_32bit {
14794:     my ($symb,$courseid,$domain,$username)=@_;
14795:     {
14796: 	use integer;
14797: 	my $symbchck=unpack("%32C*",$symb) << 27;
14798: 	my $symbseed=numval($symb) << 22;
14799: 	my $namechck=unpack("%32C*",$username) << 17;
14800: 	my $nameseed=numval($username) << 12;
14801: 	my $domainseed=unpack("%32C*",$domain) << 7;
14802: 	my $courseseed=unpack("%32C*",$courseid);
14803: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
14804: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
14805: 	#&logthis("rndseed :$num:$symb");
14806: 	if ($_64bit) { $num=(($num<<32)>>32); }
14807: 	return $num;
14808:     }
14809: }
14810: 
14811: sub rndseed_64bit {
14812:     my ($symb,$courseid,$domain,$username)=@_;
14813:     {
14814: 	use integer;
14815: 	my $symbchck=unpack("%32S*",$symb) << 21;
14816: 	my $symbseed=numval($symb) << 10;
14817: 	my $namechck=unpack("%32S*",$username);
14818: 	
14819: 	my $nameseed=numval($username) << 21;
14820: 	my $domainseed=unpack("%32S*",$domain) << 10;
14821: 	my $courseseed=unpack("%32S*",$courseid);
14822: 	
14823: 	my $num1=$symbchck+$symbseed+$namechck;
14824: 	my $num2=$nameseed+$domainseed+$courseseed;
14825: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
14826: 	#&logthis("rndseed :$num:$symb");
14827: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
14828: 	return "$num1,$num2";
14829:     }
14830: }
14831: 
14832: sub rndseed_64bit2 {
14833:     my ($symb,$courseid,$domain,$username)=@_;
14834:     {
14835: 	use integer;
14836: 	# strings need to be an even # of cahracters long, it it is odd the
14837:         # last characters gets thrown away
14838: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
14839: 	my $symbseed=numval($symb) << 10;
14840: 	my $namechck=unpack("%32S*",$username.' ');
14841: 	
14842: 	my $nameseed=numval($username) << 21;
14843: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
14844: 	my $courseseed=unpack("%32S*",$courseid.' ');
14845: 	
14846: 	my $num1=$symbchck+$symbseed+$namechck;
14847: 	my $num2=$nameseed+$domainseed+$courseseed;
14848: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
14849: 	#&logthis("rndseed :$num:$symb");
14850: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
14851: 	return "$num1,$num2";
14852:     }
14853: }
14854: 
14855: sub rndseed_64bit3 {
14856:     my ($symb,$courseid,$domain,$username)=@_;
14857:     {
14858: 	use integer;
14859: 	# strings need to be an even # of cahracters long, it it is odd the
14860:         # last characters gets thrown away
14861: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
14862: 	my $symbseed=numval2($symb) << 10;
14863: 	my $namechck=unpack("%32S*",$username.' ');
14864: 	
14865: 	my $nameseed=numval2($username) << 21;
14866: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
14867: 	my $courseseed=unpack("%32S*",$courseid.' ');
14868: 	
14869: 	my $num1=$symbchck+$symbseed+$namechck;
14870: 	my $num2=$nameseed+$domainseed+$courseseed;
14871: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
14872: 	#&logthis("rndseed :$num1:$num2:$_64bit");
14873: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
14874: 	
14875: 	return "$num1:$num2";
14876:     }
14877: }
14878: 
14879: sub rndseed_64bit4 {
14880:     my ($symb,$courseid,$domain,$username)=@_;
14881:     {
14882: 	use integer;
14883: 	# strings need to be an even # of cahracters long, it it is odd the
14884:         # last characters gets thrown away
14885: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
14886: 	my $symbseed=numval3($symb) << 10;
14887: 	my $namechck=unpack("%32S*",$username.' ');
14888: 	
14889: 	my $nameseed=numval3($username) << 21;
14890: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
14891: 	my $courseseed=unpack("%32S*",$courseid.' ');
14892: 	
14893: 	my $num1=$symbchck+$symbseed+$namechck;
14894: 	my $num2=$nameseed+$domainseed+$courseseed;
14895: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
14896: 	#&logthis("rndseed :$num1:$num2:$_64bit");
14897: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
14898: 	
14899: 	return "$num1:$num2";
14900:     }
14901: }
14902: 
14903: sub rndseed_64bit5 {
14904:     my ($symb,$courseid,$domain,$username)=@_;
14905:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
14906:     return "$num1:$num2";
14907: }
14908: 
14909: sub rndseed_CODE_64bit {
14910:     my ($symb,$courseid,$domain,$username)=@_;
14911:     {
14912: 	use integer;
14913: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
14914: 	my $symbseed=numval2($symb);
14915: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
14916: 	my $CODEseed=numval(&getCODE());
14917: 	my $courseseed=unpack("%32S*",$courseid.' ');
14918: 	my $num1=$symbseed+$CODEchck;
14919: 	my $num2=$CODEseed+$courseseed+$symbchck;
14920: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
14921: 	#&logthis("rndseed :$num1:$num2:$symb");
14922: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
14923: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
14924: 	return "$num1:$num2";
14925:     }
14926: }
14927: 
14928: sub rndseed_CODE_64bit4 {
14929:     my ($symb,$courseid,$domain,$username)=@_;
14930:     {
14931: 	use integer;
14932: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
14933: 	my $symbseed=numval3($symb);
14934: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
14935: 	my $CODEseed=numval3(&getCODE());
14936: 	my $courseseed=unpack("%32S*",$courseid.' ');
14937: 	my $num1=$symbseed+$CODEchck;
14938: 	my $num2=$CODEseed+$courseseed+$symbchck;
14939: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
14940: 	#&logthis("rndseed :$num1:$num2:$symb");
14941: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
14942: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
14943: 	return "$num1:$num2";
14944:     }
14945: }
14946: 
14947: sub rndseed_CODE_64bit5 {
14948:     my ($symb,$courseid,$domain,$username)=@_;
14949:     my $code = &getCODE();
14950:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
14951:     return "$num1:$num2";
14952: }
14953: 
14954: sub setup_random_from_rndseed {
14955:     my ($rndseed)=@_;
14956:     if ($rndseed =~/([,:])/) {
14957:         my ($num1,$num2) = map { abs($_); } (split(/[,:]/,$rndseed));
14958:         if ((!$num1) || (!$num2) || ($num1 > 2147483562) || ($num2 > 2147483398)) {
14959:             &Math::Random::random_set_seed_from_phrase($rndseed);
14960:         } else {
14961:             &Math::Random::random_set_seed($num1,$num2);
14962:         }
14963:     } else {
14964: 	&Math::Random::random_set_seed_from_phrase($rndseed);
14965:     }
14966: }
14967: 
14968: sub latest_receipt_algorithm_id {
14969:     return 'receipt3';
14970: }
14971: 
14972: sub recunique {
14973:     my $fucourseid=shift;
14974:     my $unique;
14975:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
14976: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
14977: 	$unique=$env{"course.$fucourseid.internal.encseed"};
14978:     } else {
14979: 	$unique=$perlvar{'lonReceipt'};
14980:     }
14981:     return unpack("%32C*",$unique);
14982: }
14983: 
14984: sub recprefix {
14985:     my $fucourseid=shift;
14986:     my $prefix;
14987:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
14988: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
14989: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
14990:     } else {
14991: 	$prefix=$perlvar{'lonHostID'};
14992:     }
14993:     return unpack("%32C*",$prefix);
14994: }
14995: 
14996: sub ireceipt {
14997:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
14998: 
14999:     my $return =&recprefix($fucourseid).'-';
15000: 
15001:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
15002: 	$env{'request.state'} eq 'construct') {
15003: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
15004: 	return $return;
15005:     }
15006: 
15007:     my $cuname=unpack("%32C*",$funame);
15008:     my $cudom=unpack("%32C*",$fudom);
15009:     my $cucourseid=unpack("%32C*",$fucourseid);
15010:     my $cusymb=unpack("%32C*",$fusymb);
15011:     my $cunique=&recunique($fucourseid);
15012:     my $cpart=unpack("%32S*",$part);
15013:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
15014: 
15015: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
15016: 			       
15017: 	$return.= ($cunique%$cuname+
15018: 		   $cunique%$cudom+
15019: 		   $cusymb%$cuname+
15020: 		   $cusymb%$cudom+
15021: 		   $cucourseid%$cuname+
15022: 		   $cucourseid%$cudom+
15023: 		   $cpart%$cuname+
15024: 		   $cpart%$cudom);
15025:     } else {
15026: 	$return.= ($cunique%$cuname+
15027: 		   $cunique%$cudom+
15028: 		   $cusymb%$cuname+
15029: 		   $cusymb%$cudom+
15030: 		   $cucourseid%$cuname+
15031: 		   $cucourseid%$cudom);
15032:     }
15033:     return $return;
15034: }
15035: 
15036: sub receipt {
15037:     my ($part)=@_;
15038:     my ($symb,$courseid,$domain,$name) = &whichuser();
15039:     return &ireceipt($name,$domain,$courseid,$symb,$part);
15040: }
15041: 
15042: sub whichuser {
15043:     my ($passedsymb)=@_;
15044:     my ($symb,$courseid,$domain,$name,$publicuser);
15045:     if (defined($env{'form.grade_symb'})) {
15046: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
15047: 	my $allowed=&allowed('vgr',$tmp_courseid);
15048: 	if (!$allowed &&
15049: 	    exists($env{'request.course.sec'}) &&
15050: 	    $env{'request.course.sec'} !~ /^\s*$/) {
15051: 	    $allowed=&allowed('vgr',$tmp_courseid.
15052: 			      '/'.$env{'request.course.sec'});
15053: 	}
15054: 	if ($allowed) {
15055: 	    ($symb)=&get_env_multiple('form.grade_symb');
15056: 	    $courseid=$tmp_courseid;
15057: 	    ($domain)=&get_env_multiple('form.grade_domain');
15058: 	    ($name)=&get_env_multiple('form.grade_username');
15059: 	    return ($symb,$courseid,$domain,$name,$publicuser);
15060: 	}
15061:     }
15062:     if (!$passedsymb) {
15063: 	$symb=&symbread();
15064:     } else {
15065: 	$symb=$passedsymb;
15066:     }
15067:     $courseid=$env{'request.course.id'};
15068:     $domain=$env{'user.domain'};
15069:     $name=$env{'user.name'};
15070:     if ($name eq 'public' && $domain eq 'public') {
15071: 	if (!defined($env{'form.username'})) {
15072: 	    $env{'form.username'}.=time.rand(10000000);
15073: 	}
15074: 	$name.=$env{'form.username'};
15075:     }
15076:     return ($symb,$courseid,$domain,$name,$publicuser);
15077: 
15078: }
15079: 
15080: # ------------------------------------------------------------ Serves up a file
15081: # returns either the contents of the file or 
15082: # -1 if the file doesn't exist
15083: #
15084: # if the target is a file that was uploaded via DOCS, 
15085: # a check will be made to see if a current copy exists on the local server,
15086: # if it does this will be served, otherwise a copy will be retrieved from
15087: # the home server for the course and stored in /home/httpd/html/userfiles on
15088: # the local server.   
15089: 
15090: sub getfile {
15091:     my ($file) = @_;
15092:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
15093:     &repcopy($file);
15094:     return &readfile($file);
15095: }
15096: 
15097: sub repcopy_userfile {
15098:     my ($file)=@_;
15099:     my $londocroot = $perlvar{'lonDocRoot'};
15100:     if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
15101:     if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
15102:     my ($cdom,$cnum,$filename) = 
15103: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
15104:     my $uri="/uploaded/$cdom/$cnum/$filename";
15105:     if (-e "$file") {
15106: # we already have a local copy, check it out
15107: 	my @fileinfo = stat($file);
15108: 	my $rtncode;
15109: 	my $info;
15110: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
15111: 	if ($lwpresp ne 'ok') {
15112: # there is no such file anymore, even though we had a local copy
15113: 	    if ($rtncode eq '404') {
15114: 		unlink($file);
15115: 	    }
15116: 	    return -1;
15117: 	}
15118: 	if ($info < $fileinfo[9]) {
15119: # nice, the file we have is up-to-date, just say okay
15120: 	    return 'ok';
15121: 	} else {
15122: # the file is outdated, get rid of it
15123: 	    unlink($file);
15124: 	}
15125:     }
15126: # one way or the other, at this point, we don't have the file
15127: # construct the correct path for the file
15128:     my @parts = ($cdom,$cnum); 
15129:     if ($filename =~ m|^(.+)/[^/]+$|) {
15130: 	push @parts, split(/\//,$1);
15131:     }
15132:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
15133:     foreach my $part (@parts) {
15134: 	$path .= '/'.$part;
15135: 	if (!-e $path) {
15136: 	    mkdir($path,0770);
15137: 	}
15138:     }
15139: # now the path exists for sure
15140: # get a user agent
15141:     my $transferfile=$file.'.in.transfer';
15142: # FIXME: this should flock
15143:     if (-e $transferfile) { return 'ok'; }
15144:     my $request;
15145:     $uri=~s/^\///;
15146:     my $homeserver = &homeserver($cnum,$cdom);
15147:     my $hostname = &hostname($homeserver);
15148:     my $protocol = $protocol{$homeserver};
15149:     $protocol = 'http' if ($protocol ne 'https');
15150:     $request=new HTTP::Request('GET',$protocol.'://'.$hostname.'/raw/'.$uri);
15151:     my $response = &LONCAPA::LWPReq::makerequest($homeserver,$request,$transferfile,\%perlvar,'',0,1);
15152: # did it work?
15153:     if ($response->is_error()) {
15154: 	unlink($transferfile);
15155: 	&logthis("Userfile repcopy failed for $uri");
15156: 	return -1;
15157:     }
15158: # worked, rename the transfer file
15159:     rename($transferfile,$file);
15160:     return 'ok';
15161: }
15162: 
15163: sub tokenwrapper {
15164:     my $uri=shift;
15165:     $uri=~s|^https?\://([^/]+)||;
15166:     $uri=~s|^/||;
15167:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
15168:     my $token=$1;
15169:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
15170:     if ($udom && $uname && $file) {
15171: 	$file=~s|(\?\.*)*$||;
15172:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
15173:         my $homeserver = &homeserver($uname,$udom);
15174:         my $hostname = &hostname($homeserver);
15175:         my $protocol = $protocol{$homeserver};
15176:         $protocol = 'http' if ($protocol ne 'https');
15177:         return $protocol.'://'.$hostname.'/'.$uri.
15178:                (($uri=~/\?/)?'&':'?').'token='.$token.
15179:                                '&tokenissued='.$perlvar{'lonHostID'};
15180:     } else {
15181:         return '/adm/notfound.html';
15182:     }
15183: }
15184: 
15185: # call with reqtype HEAD: get last modification time
15186: # call with reqtype GET: get the file contents
15187: # Do not call this with reqtype GET for large files! It loads everything into memory
15188: #
15189: sub getuploaded {
15190:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
15191:     $uri=~s/^\///;
15192:     my $homeserver = &homeserver($cnum,$cdom);
15193:     my $hostname = &hostname($homeserver);
15194:     my $protocol = $protocol{$homeserver};
15195:     $protocol = 'http' if ($protocol ne 'https');
15196:     $uri = $protocol.'://'.$hostname.'/raw/'.$uri;
15197:     my $request=new HTTP::Request($reqtype,$uri);
15198:     my $response=&LONCAPA::LWPReq::makerequest($homeserver,$request,'',\%perlvar,'',0,1);
15199:     $$rtncode = $response->code;
15200:     if (! $response->is_success()) {
15201: 	return 'failed';
15202:     }      
15203:     if ($reqtype eq 'HEAD') {
15204: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
15205:     } elsif ($reqtype eq 'GET') {
15206: 	$$info = $response->content;
15207:     }
15208:     return 'ok';
15209: }
15210: 
15211: sub readfile {
15212:     my $file = shift;
15213:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
15214:     my $fh;
15215:     open($fh,"<",$file);
15216:     my $a='';
15217:     while (my $line = <$fh>) { $a .= $line; }
15218:     return $a;
15219: }
15220: 
15221: sub filelocation {
15222:     my ($dir,$file) = @_;
15223:     my $location;
15224:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
15225: 
15226:     if ($file =~ m-^/adm/-) {
15227: 	$file=~s-^/adm/wrapper/-/-;
15228: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
15229:     }
15230: 
15231:     if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
15232:         $location = $file;
15233:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
15234:         my ($udom,$uname,$filename)=
15235:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
15236:         my $home=&homeserver($uname,$udom);
15237:         my $is_me=0;
15238:         my @ids=&current_machine_ids();
15239:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
15240:         if ($is_me) {
15241:   	    $location=propath($udom,$uname).'/userfiles/'.$filename;
15242:         } else {
15243:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
15244:   	      $udom.'/'.$uname.'/'.$filename;
15245:         }
15246:     } elsif ($file =~ m-^/adm/-) {
15247: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
15248:     } else {
15249:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
15250:         $file=~s:^/(res|priv)/:/:;
15251:         my $space=$1;
15252:         if ( !( $file =~ m:^/:) ) {
15253:             $location = $dir. '/'.$file;
15254:         } else {
15255:             $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
15256:         }
15257:     }
15258:     $location=~s://+:/:g; # remove duplicate /
15259:     while ($location=~m{/\.\./}) {
15260: 	if ($location =~ m{/[^/]+/\.\./}) {
15261: 	    $location=~ s{/[^/]+/\.\./}{/}g;
15262: 	} else {
15263: 	    $location=~ s{/\.\./}{/}g;
15264: 	}
15265:     } #remove dir/..
15266:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
15267:     return $location;
15268: }
15269: 
15270: sub hreflocation {
15271:     my ($dir,$file)=@_;
15272:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
15273: 	$file=filelocation($dir,$file);
15274:     } elsif ($file=~m-^/adm/-) {
15275: 	$file=~s-^/adm/wrapper/-/-;
15276: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
15277:     }
15278:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
15279: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
15280:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
15281: 	$file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
15282: 	        {/uploaded/$1/$2/}x;
15283:     }
15284:     if ($file=~ m{^/userfiles/}) {
15285: 	$file =~ s{^/userfiles/}{/uploaded/};
15286:     }
15287:     return $file;
15288: }
15289: 
15290: 
15291: 
15292: 
15293: 
15294: sub current_machine_domains {
15295:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
15296: }
15297: 
15298: sub machine_domains {
15299:     my ($hostname) = @_;
15300:     my @domains;
15301:     my %hostname = &all_hostnames();
15302:     while( my($id, $name) = each(%hostname)) {
15303: #	&logthis("-$id-$name-$hostname-");
15304: 	if ($hostname eq $name) {
15305: 	    push(@domains,&host_domain($id));
15306: 	}
15307:     }
15308:     return @domains;
15309: }
15310: 
15311: sub current_machine_ids {
15312:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
15313: }
15314: 
15315: sub machine_ids {
15316:     my ($hostname) = @_;
15317:     $hostname ||= &hostname($perlvar{'lonHostID'});
15318:     my @ids;
15319:     my %name_to_host = &all_names();
15320:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
15321: 	return @{ $name_to_host{$hostname} };
15322:     }
15323:     return;
15324: }
15325: 
15326: sub additional_machine_domains {
15327:     my @domains;
15328:     if (-e "$perlvar{'lonTabDir'}/expected_domains.tab") {
15329:         if (open(my $fh,"<","$perlvar{'lonTabDir'}/expected_domains.tab")) {
15330:             while (my $line = <$fh>) {
15331:                 chomp($line);           
15332:                 $line =~ s/\s//g;
15333:                 push(@domains,$line);
15334:             }
15335:             close($fh);
15336:         }
15337:     }
15338:     return @domains;
15339: }
15340: 
15341: sub default_login_domain {
15342:     my $domain = $perlvar{'lonDefDomain'};
15343:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
15344:     foreach my $posdom (&current_machine_domains(),
15345:                         &additional_machine_domains()) {
15346:         if (lc($posdom) eq lc($testdomain)) {
15347:             $domain=$posdom;
15348:             last;
15349:         }
15350:     }
15351:     return $domain;
15352: }
15353: 
15354: sub shared_institution {
15355:     my ($dom,$lonhost) = @_;
15356:     if ($lonhost eq '') {
15357:         $lonhost = $perlvar{'lonHostID'};
15358:     }
15359:     my $same_intdom;
15360:     my $hostintdom = &internet_dom($lonhost);
15361:     if ($hostintdom ne '') {
15362:         my %iphost = &get_iphost();
15363:         my $primary_id = &domain($dom,'primary');
15364:         my $primary_ip = &get_host_ip($primary_id);
15365:         if (ref($iphost{$primary_ip}) eq 'ARRAY') {
15366:             foreach my $id (@{$iphost{$primary_ip}}) {
15367:                 my $intdom = &internet_dom($id);
15368:                 if ($intdom eq $hostintdom) {
15369:                     $same_intdom = 1;
15370:                     last;
15371:                 }
15372:             }
15373:         }
15374:     }
15375:     return $same_intdom;
15376: }
15377: 
15378: sub uses_sts {
15379:     my ($ignore_cache) = @_;
15380:     my $lonhost = $perlvar{'lonHostID'};
15381:     my $hostname = &hostname($lonhost);
15382:     my $sts_on;
15383:     if ($protocol{$lonhost} eq 'https') {
15384:         my $cachetime = 12*3600;
15385:         if (!$ignore_cache) {
15386:             ($sts_on,my $cached)=&is_cached_new('stspolicy',$lonhost);
15387:             if (defined($cached)) {
15388:                 return $sts_on;
15389:             }
15390:         }
15391:         my $url = $protocol{$lonhost}.'://'.$hostname.'/index.html';
15392:         my $request=new HTTP::Request('HEAD',$url);
15393:         my $response=&LONCAPA::LWPReq::makerequest($lonhost,$request,'',\%perlvar,'','','',1);
15394:         if ($response->is_success) {
15395:             my $has_sts = $response->header('Strict-Transport-Security');
15396:             if ($has_sts eq '') {
15397:                 $sts_on = 0;
15398:             } else {
15399:                 if ($has_sts =~ /\Qmax-age=\E(\d+)/) {
15400:                     my $maxage = $1;
15401:                     if ($maxage) {
15402:                         $sts_on = 1;
15403:                     } else {
15404:                         $sts_on = 0;
15405:                     }
15406:                 } else {
15407:                     $sts_on = 0;
15408:                 }
15409:             }
15410:             return &do_cache_new('stspolicy',$lonhost,$sts_on,$cachetime);
15411:         }
15412:     }
15413:     return;
15414: }
15415: 
15416: sub waf_allssl {
15417:     my ($host_name) = @_;
15418:     my $alias = &get_proxy_alias();
15419:     if ($host_name eq '') {
15420:         $host_name = $ENV{'SERVER_NAME'};
15421:     }
15422:     if (($host_name ne '') && ($alias eq $host_name)) {
15423:         my $serverhomedom = &host_domain($perlvar{'lonHostID'});
15424:         my %defdomdefaults = &get_domain_defaults($serverhomedom);
15425:         if ($defdomdefaults{'waf_sslopt'}) {
15426:             return $defdomdefaults{'waf_sslopt'};
15427:         }
15428:     }
15429:     return;
15430: }
15431: 
15432: sub get_requestor_ip {
15433:     my ($r,$nolookup,$noproxy) = @_;
15434:     my $from_ip;
15435:     if (ref($r)) {
15436:         if ($r->can('useragent_ip')) {
15437:             if ($noproxy && $r->can('client_ip')) {
15438:                 $from_ip = $r->client_ip();
15439:             } else {
15440:                 $from_ip = $r->useragent_ip();
15441:             }
15442:         } elsif ($r->connection->can('remote_ip')) {
15443:             $from_ip = $r->connection->remote_ip();
15444:         } else {
15445:             $from_ip = $r->get_remote_host($nolookup);
15446:         }
15447:     } else {
15448:         $from_ip = $ENV{'REMOTE_ADDR'};
15449:     }
15450:     return $from_ip if ($noproxy); 
15451:     # Who controls proxy settings for server
15452:     my $dom_in_use = $Apache::lonnet::perlvar{'lonDefDomain'};
15453:     my $proxyinfo = &get_proxy_settings($dom_in_use);
15454:     if ((ref($proxyinfo) eq 'HASH') && ($from_ip)) {
15455:         if ($proxyinfo->{'vpnint'}) {
15456:             if (&ip_match($from_ip,$proxyinfo->{'vpnint'})) {
15457:                 return $from_ip;
15458:             }
15459:         }
15460:         if ($proxyinfo->{'trusted'}) {
15461:             if (&ip_match($from_ip,$proxyinfo->{'trusted'})) {
15462:                 my $ipheader = $proxyinfo->{'ipheader'};
15463:                 my ($ip,$xfor);
15464:                 if (ref($r)) {
15465:                     if ($ipheader) {
15466:                         $ip = $r->headers_in->{$ipheader};
15467:                     }
15468:                     $xfor = $r->headers_in->{'X-Forwarded-For'};
15469:                 } else {
15470:                     if ($ipheader) {
15471:                         $ip = $ENV{'HTTP_'.uc($ipheader)};
15472:                     }
15473:                     $xfor = $ENV{'HTTP_X_FORWARDED_FOR'};
15474:                 }
15475:                 if (($ip eq '') && ($xfor ne '')) {
15476:                     foreach my $poss_ip (reverse(split(/\s*,\s*/,$xfor))) {
15477:                         unless (&ip_match($poss_ip,$proxyinfo->{'trusted'})) {
15478:                             $ip = $poss_ip;
15479:                             last;
15480:                         }
15481:                     }
15482:                 }
15483:                 if ($ip ne '') {
15484:                     return $ip;
15485:                 }
15486:             }
15487:         }
15488:     }
15489:     return $from_ip;
15490: }
15491: 
15492: sub get_proxy_settings {
15493:     my ($dom_in_use) = @_;
15494:     my %domdefaults = &get_domain_defaults($dom_in_use);
15495:     my $proxyinfo = {
15496:                        ipheader => $domdefaults{'waf_ipheader'},
15497:                        trusted  => $domdefaults{'waf_trusted'},
15498:                        vpnint   => $domdefaults{'waf_vpnint'},
15499:                        vpnext   => $domdefaults{'waf_vpnext'},
15500:                        sslopt   => $domdefaults{'waf_sslopt'},
15501:                     };
15502:     return $proxyinfo;
15503: }
15504: 
15505: sub ip_match {
15506:     my ($ip,$pattern_str) = @_;
15507:     $ip=Net::CIDR::cidrvalidate($ip);
15508:     if ($ip) {
15509:         return Net::CIDR::cidrlookup($ip,split(/\s*,\s*/,$pattern_str));
15510:     }
15511:     return;
15512: }
15513: 
15514: sub get_proxy_alias {
15515:     my ($lonid) = @_;
15516:     if ($lonid eq '') {
15517:         $lonid = $perlvar{'lonHostID'};
15518:     }
15519:     if (!defined(&hostname($lonid))) {
15520:         return;
15521:     }
15522:     if ($lonid ne '') {
15523:         my ($alias,$cached) = &is_cached_new('proxyalias',$lonid);
15524:         if ($cached) {
15525:             return $alias;
15526:         }
15527:         my $dom = &host_domain($lonid);
15528:         if ($dom ne '') {
15529:             my $cachetime = 60*60*24;
15530:             my %domconfig =
15531:                 &get_dom('configuration',['wafproxy'],$dom);
15532:             if (ref($domconfig{'wafproxy'}) eq 'HASH') {
15533:                 if (ref($domconfig{'wafproxy'}{'alias'}) eq 'HASH') {
15534:                     $alias = $domconfig{'wafproxy'}{'alias'}{$lonid};
15535:                 }
15536:             }
15537:             return &do_cache_new('proxyalias',$lonid,$alias,$cachetime);
15538:         }
15539:     }
15540:     return;
15541: }
15542: 
15543: sub use_proxy_alias {
15544:     my ($r,$lonid) = @_;
15545:     my $alias = &get_proxy_alias($lonid);
15546:     if ($alias) {
15547:         my $dom = &host_domain($lonid);
15548:         if ($dom ne '') {
15549:             my $proxyinfo = &get_proxy_settings($dom);
15550:             my ($vpnint,$remote_ip);
15551:             if (ref($proxyinfo) eq 'HASH') {
15552:                 $vpnint = $proxyinfo->{'vpnint'};
15553:                 if ($vpnint) {
15554:                     $remote_ip = &get_requestor_ip($r,1,1);
15555:                 }
15556:             }
15557:             unless ($vpnint && &ip_match($remote_ip,$vpnint)) {
15558:                 return $alias;
15559:             }
15560:         }
15561:     }
15562:     return;
15563: }
15564: 
15565: sub alias_sso {
15566:     my ($lonid) = @_;
15567:     if ($lonid eq '') {
15568:         $lonid = $perlvar{'lonHostID'};
15569:     }
15570:     if (!defined(&hostname($lonid))) {
15571:         return;
15572:     }
15573:     if ($lonid ne '') {
15574:         my ($use_alias,$cached) = &is_cached_new('proxysaml',$lonid);
15575:         if ($cached) {
15576:             return $use_alias;
15577:         }
15578:         my $dom = &host_domain($lonid);
15579:         if ($dom ne '') {
15580:             my $cachetime = 60*60*24;
15581:             my %domconfig =
15582:                 &get_dom('configuration',['wafproxy'],$dom);
15583:             if (ref($domconfig{'wafproxy'}) eq 'HASH') {
15584:                 if (ref($domconfig{'wafproxy'}{'saml'}) eq 'HASH') {
15585:                     $use_alias = $domconfig{'wafproxy'}{'saml'}{$lonid};
15586:                 }
15587:             }
15588:             return &do_cache_new('proxysaml',$lonid,$use_alias,$cachetime);
15589:         }
15590:     }
15591:     return;
15592: }
15593: 
15594: sub get_saml_landing {
15595:     my ($lonid) = @_;
15596:     if ($lonid eq '') {
15597:         my $defdom = &default_login_domain();
15598:         my @hosts = &current_machine_ids();
15599:         if (@hosts > 1) {
15600:             foreach my $hostid (@hosts) {
15601:                 if (&host_domain($hostid) eq $defdom) {
15602:                     $lonid = $hostid;
15603:                     last;
15604:                 }
15605:             }
15606:         } else {
15607:             $lonid = $perlvar{'lonHostID'};
15608:         }
15609:         if ($lonid) {
15610:             unless (&host_domain($lonid) eq $defdom) {
15611:                 return;
15612:             }
15613:         } else {
15614:             return;
15615:         }
15616:     } elsif (!defined(&hostname($lonid))) {
15617:         return;
15618:     }
15619:     my ($landing,$cached) = &is_cached_new('samllanding',$lonid);
15620:     if ($cached) {
15621:         return $landing;
15622:     }
15623:     my $dom = &host_domain($lonid);
15624:     if ($dom ne '') {
15625:         my $cachetime = 60*60*24;
15626:         my %domconfig =
15627:             &get_dom('configuration',['login'],$dom);
15628:         if (ref($domconfig{'login'}) eq 'HASH') {
15629:             if (ref($domconfig{'login'}{'saml'}) eq 'HASH') {
15630:                 if (ref($domconfig{'login'}{'saml'}{$lonid}) eq 'HASH') {
15631:                     $landing = 1;
15632:                 }
15633:             }
15634:         }
15635:         return &do_cache_new('samllanding',$lonid,$landing,$cachetime);
15636:     }
15637:     return;
15638: }
15639: 
15640: # ------------------------------------------------------------- Declutters URLs
15641: 
15642: sub declutter {
15643:     my $thisfn=shift;
15644:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
15645:     unless ($thisfn=~m{^/home/httpd/html/priv/}) {
15646:         $thisfn=~s{^/home/httpd/html}{};
15647:     }
15648:     $thisfn=~s/^\///;
15649:     $thisfn=~s|^adm/wrapper/||;
15650:     $thisfn=~s|^adm/coursedocs/showdoc/||;
15651:     $thisfn=~s/^res\///;
15652:     $thisfn=~s/^priv\///;
15653:     unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
15654:         $thisfn=~s/\?.+$//;
15655:     }
15656:     return $thisfn;
15657: }
15658: 
15659: # ------------------------------------------------------------- Clutter up URLs
15660: 
15661: sub clutter {
15662:     my $thisfn='/'.&declutter(shift);
15663:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
15664: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
15665:        $thisfn='/res'.$thisfn; 
15666:     }
15667:     if ($thisfn !~m|^/adm|) {
15668: 	if ($thisfn =~ m|^/ext/|) {
15669: 	    $thisfn='/adm/wrapper'.$thisfn;
15670: 	} else {
15671: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
15672: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
15673: 	    if ($embstyle eq 'ssi'
15674: 		|| ($embstyle eq 'hdn')
15675: 		|| ($embstyle eq 'rat')
15676: 		|| ($embstyle eq 'prv')
15677: 		|| ($embstyle eq 'ign')) {
15678: 		#do nothing with these
15679: 	    } elsif (($embstyle eq 'img') 
15680: 		|| ($embstyle eq 'emb')
15681: 		|| ($embstyle eq 'wrp')) {
15682: 		$thisfn='/adm/wrapper'.$thisfn;
15683: 	    } elsif ($embstyle eq 'unk'
15684: 		     && $thisfn!~/\.(sequence|page)$/) {
15685: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
15686: 	    } else {
15687: #		&logthis("Got a blank emb style");
15688: 	    }
15689: 	}
15690:     } elsif ($thisfn =~ m{^/adm/$match_domain/$match_courseid/\d+/ext\.tool$}) {
15691:         $thisfn='/adm/wrapper'.$thisfn;
15692:     }
15693:     return $thisfn;
15694: }
15695: 
15696: sub clutter_with_no_wrapper {
15697:     my $uri = &clutter(shift);
15698:     if ($uri =~ m-^/adm/-) {
15699: 	$uri =~ s-^/adm/wrapper/-/-;
15700: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
15701:     }
15702:     return $uri;
15703: }
15704: 
15705: sub freeze_escape {
15706:     my ($value)=@_;
15707:     if (ref($value)) {
15708: 	$value=&nfreeze($value);
15709: 	return '__FROZEN__'.&escape($value);
15710:     }
15711:     return &escape($value);
15712: }
15713: 
15714: 
15715: sub thaw_unescape {
15716:     my ($value)=@_;
15717:     if ($value =~ /^__FROZEN__/) {
15718: 	substr($value,0,10,undef);
15719: 	$value=&unescape($value);
15720: 	return &thaw($value);
15721:     }
15722:     return &unescape($value);
15723: }
15724: 
15725: sub correct_line_ends {
15726:     my ($result)=@_;
15727:     $$result =~s/\r\n/\n/mg;
15728:     $$result =~s/\r/\n/mg;
15729: }
15730: # ================================================================ Main Program
15731: 
15732: sub goodbye {
15733:    &logthis("Starting Shut down");
15734: #not converted to using infrastruture and probably shouldn't be
15735:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
15736: #converted
15737: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
15738:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
15739: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
15740: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
15741: #1.1 only
15742: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
15743: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
15744: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
15745: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
15746:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
15747:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
15748:    &logthis(sprintf("%-20s is %s",'hits',$hits));
15749:    &flushcourselogs();
15750:    &logthis("Shutting down");
15751: }
15752: 
15753: sub get_dns {
15754:     my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
15755:     if (!$ignore_cache) {
15756: 	my ($content,$cached)=
15757: 	    &is_cached_new('dns',$url);
15758: 	if ($cached) {
15759: 	    &$func($content,$hashref);
15760: 	    return;
15761: 	}
15762:     }
15763: 
15764:     my %alldns;
15765:     if (open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab")) {
15766:         foreach my $dns (<$config>) {
15767: 	    next if ($dns !~ /^\^(\S*)/x);
15768:             my $line = $1;
15769:             my ($host,$protocol) = split(/:/,$line);
15770:             if ($protocol ne 'https') {
15771:                 $protocol = 'http';
15772:             }
15773: 	    $alldns{$host} = $protocol;
15774:         }
15775:         close($config);
15776:     }
15777:     while (%alldns) {
15778: 	my ($dns) = sort { $b cmp $a } keys(%alldns);
15779:         my ($contents,@content);
15780:         if ($dns eq Sys::Hostname::FQDN::fqdn()) {
15781:             my $command = (split('/',$url))[3];
15782:             my ($dir,$file) = &parse_getdns_url($command,$url);
15783:             delete($alldns{$dns});
15784:             next if (($dir eq '') || ($file eq ''));
15785:             if (open(my $config,'<',"$dir/$file")) {
15786:                 @content = <$config>;
15787:                 close($config);
15788:             }
15789:             if ($url eq '/adm/dns/loncapaCRL') {
15790:                 $contents = join('',@content);
15791:             }
15792:         } else {
15793: 	    my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
15794:             my $response = &LONCAPA::LWPReq::makerequest('',$request,'',\%perlvar,30,0);
15795:             delete($alldns{$dns});
15796: 	    next if ($response->is_error());
15797:             if ($url eq '/adm/dns/loncapaCRL') {
15798:                 $contents = $response->content;
15799:             } else {
15800:                 @content = split("\n",$response->content);
15801:             }
15802:         }
15803:         if ($url eq '/adm/dns/loncapaCRL') {
15804:             return &$func($contents);
15805:         } else {
15806: 	    unless ($nocache) {
15807: 	        &do_cache_new('dns',$url,\@content,30*24*60*60);
15808: 	    }
15809: 	    &$func(\@content,$hashref);
15810:             return;
15811:         }
15812:     }
15813:     my $which = (split('/',$url,4))[3];
15814:     if ($which eq 'loncapaCRL') {
15815:         my $diskfile = "$perlvar{'lonCertificateDirectory'}/$perlvar{'lonnetCertRevocationList'}";
15816:         if (-e $diskfile) {
15817:             &logthis("unable to contact DNS, on disk file $diskfile not updated");
15818:         } else {
15819:             &logthis("unable to contact DNS, no on disk file $diskfile available");
15820:         }
15821:     } else {
15822:         &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
15823:         if (open(my $config,"<","$perlvar{'lonTabDir'}/dns_$which.tab")) {
15824:             my @content = <$config>;
15825:             close($config);
15826:             &$func(\@content,$hashref);
15827:         }
15828:     }
15829:     return;
15830: }
15831: 
15832: # ------------------------------------------------------Get DNS checksums file
15833: sub parse_dns_checksums_tab {
15834:     my ($lines,$hashref) = @_;
15835:     my $lonhost = $perlvar{'lonHostID'};
15836:     my $machine_dom = &host_domain($lonhost);
15837:     my $loncaparev = &get_server_loncaparev($machine_dom);
15838:     my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
15839:     my $webconfdir = '/etc/httpd/conf';
15840:     if ($distro =~ /^(ubuntu|debian)(\d+)$/) {
15841:         $webconfdir = '/etc/apache2';
15842:     } elsif ($distro =~ /^sles(\d+)$/) {
15843:         if ($1 >= 10) {
15844:             $webconfdir = '/etc/apache2';
15845:         }
15846:     } elsif ($distro =~ /^suse(\d+\.\d+)$/) {
15847:         if ($1 >= 10.0) {
15848:             $webconfdir = '/etc/apache2';
15849:         }
15850:     }
15851:     my ($release,$timestamp) = split(/\-/,$loncaparev);
15852:     my (%chksum,%revnum);
15853:     if (ref($lines) eq 'ARRAY') {
15854:         chomp(@{$lines});
15855:         my $version = shift(@{$lines});
15856:         if ($version eq $release) {  
15857:             foreach my $line (@{$lines}) {
15858:                 my ($file,$version,$shasum) = split(/,/,$line);
15859:                 if ($file =~ m{^/etc/httpd/conf}) {
15860:                     if ($webconfdir eq '/etc/apache2') {
15861:                         $file =~ s{^\Q/etc/httpd/conf/\E}{$webconfdir/};
15862:                     }
15863:                 }
15864:                 $chksum{$file} = $shasum;
15865:                 $revnum{$file} = $version;
15866:             }
15867:             if (ref($hashref) eq 'HASH') {
15868:                 %{$hashref} = (
15869:                                 sums     => \%chksum,
15870:                                 versions => \%revnum,
15871:                               );
15872:             }
15873:         }
15874:     }
15875:     return;
15876: }
15877: 
15878: sub fetch_dns_checksums {
15879:     my %checksums;
15880:     my $machine_dom = &host_domain($perlvar{'lonHostID'});
15881:     my $loncaparev = &get_server_loncaparev($machine_dom,$perlvar{'lonHostID'});
15882:     my ($release,$timestamp) = split(/\-/,$loncaparev);
15883:     &get_dns("/adm/dns/checksums/$release",\&parse_dns_checksums_tab,1,1,
15884:              \%checksums);
15885:     return \%checksums;
15886: }
15887: 
15888: sub fetch_crl_pemfile {
15889:     return &get_dns("/adm/dns/loncapaCRL",\&save_crl_pem,1,1);
15890: }
15891: 
15892: sub save_crl_pem {
15893:     my ($content) = @_;
15894:     my ($msg,$hadchanges);
15895:     if ($content ne '') {
15896:         my $now = time;
15897:         my $lonca = $perlvar{'lonCertificateDirectory'}.'/'.$perlvar{'lonnetCertificateAuthority'};
15898:         my $tmpcrl = $tmpdir.'/'.$perlvar{'lonnetCertRevocationList'}.'_'.$now.'.'.$$.'.tmp';
15899:         if (open(my $fh,'>',"$tmpcrl")) {
15900:             print $fh $content;
15901:             close($fh);
15902:             if (-e $lonca) {
15903:                 if (open(PIPE,"openssl crl -in $tmpcrl -inform pem -CAfile $lonca -noout 2>&1 |")) {
15904:                     my $check = <PIPE>;
15905:                     close(PIPE);
15906:                     chomp($check);
15907:                     if ($check eq 'verify OK') {
15908:                         my $dest = "$perlvar{'lonCertificateDirectory'}/$perlvar{'lonnetCertRevocationList'}";
15909:                         my $backup;
15910:                         if (-e $dest) {
15911:                             if (&File::Copy::move($dest,"$dest.bak")) {
15912:                                 $backup = 'ok';
15913:                             }
15914:                         }
15915:                         if (&File::Copy::move($tmpcrl,$dest)) {
15916:                             $msg = 'ok';
15917:                             if ($backup) {
15918:                                 my (%oldnums,%newnums);
15919:                                 if (open(PIPE, "openssl crl -inform PEM -text -noout -in $dest.bak |grep 'Serial Number' |")) {
15920:                                     while (<PIPE>) {
15921:                                         $oldnums{(split(/:/))[1]} = 1;
15922:                                     }
15923:                                     close(PIPE);
15924:                                 }
15925:                                 if (open(PIPE, "openssl crl -inform PEM -text -noout -in $dest |grep 'Serial Number' |")) {
15926:                                     while(<PIPE>) {
15927:                                         $newnums{(split(/:/))[1]} = 1;
15928:                                     }
15929:                                     close(PIPE);
15930:                                 }
15931:                                 foreach my $key (sort {$b <=> $a } (keys(%newnums))) {
15932:                                     unless (exists($oldnums{$key})) {
15933:                                         $hadchanges = 1;
15934:                                         last;
15935:                                     }
15936:                                 }
15937:                                 unless ($hadchanges) {
15938:                                     foreach my $key (sort {$b <=> $a } (keys(%oldnums))) {
15939:                                         unless (exists($newnums{$key})) {
15940:                                             $hadchanges = 1;
15941:                                             last;
15942:                                         }
15943:                                     }
15944:                                 }
15945:                             }
15946:                         }
15947:                     } else {
15948:                         unlink($tmpcrl);
15949:                     }
15950:                 } else {
15951:                     unlink($tmpcrl);
15952:                 }
15953:             } else {
15954:                 unlink($tmpcrl);
15955:             }
15956:         }
15957:     }
15958:     return ($msg,$hadchanges);
15959: }
15960: 
15961: sub parse_getdns_url {
15962:     my ($command,$url) = @_;
15963:     my $dir = $perlvar{'lonTabDir'};
15964:     my $file;
15965:     if ($command eq 'hosts') {
15966:         $file = 'dns_hosts.tab';
15967:     } elsif ($command eq 'domain') {
15968:         $file = 'dns_domain.tab';
15969:     } elsif ($command eq 'checksums') {
15970:         my $version = (split('/',$url))[4];
15971:         $file = "dns_checksums/$version.tab",
15972:     } elsif ($command eq 'loncapaCRL') {
15973:         $dir = $perlvar{'lonCertificateDirectory'};
15974:         $file = $perlvar{'lonnetCertRevocationList'};
15975:     }
15976:     return ($dir,$file);
15977: }
15978: 
15979: # ------------------------------------------------------------ Read domain file
15980: {
15981:     my $loaded;
15982:     my %domain;
15983: 
15984:     sub parse_domain_tab {
15985: 	my ($lines) = @_;
15986: 	foreach my $line (@$lines) {
15987: 	    next if ($line =~ /^(\#|\s*$ )/x);
15988: 
15989: 	    chomp($line);
15990: 	    my ($name,@elements) = split(/:/,$line,9);
15991: 	    my %this_domain;
15992: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
15993: 			       'lang_def', 'city', 'longi', 'lati',
15994: 			       'primary') {
15995: 		$this_domain{$field} = shift(@elements);
15996: 	    }
15997: 	    $domain{$name} = \%this_domain;
15998: 	}
15999:     }
16000: 
16001:     sub reset_domain_info {
16002: 	undef($loaded);
16003: 	undef(%domain);
16004:     }
16005: 
16006:     sub load_domain_tab {
16007: 	my ($ignore_cache,$nocache) = @_;
16008: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache,$nocache);
16009: 	my $fh;
16010: 	if (open($fh,"<",$perlvar{'lonTabDir'}.'/domain.tab')) {
16011: 	    my @lines = <$fh>;
16012: 	    &parse_domain_tab(\@lines);
16013: 	}
16014: 	close($fh);
16015: 	$loaded = 1;
16016:     }
16017: 
16018:     sub domain {
16019: 	&load_domain_tab() if (!$loaded);
16020: 
16021: 	my ($name,$what) = @_;
16022: 	return if ( !exists($domain{$name}) );
16023: 
16024: 	if (!$what) {
16025: 	    return $domain{$name}{'description'};
16026: 	}
16027: 	return $domain{$name}{$what};
16028:     }
16029: 
16030:     sub domain_info {
16031:         &load_domain_tab() if (!$loaded);
16032:         return %domain;
16033:     }
16034: 
16035: }
16036: 
16037: 
16038: # ------------------------------------------------------------- Read hosts file
16039: {
16040:     my %hostname;
16041:     my %hostdom;
16042:     my %libserv;
16043:     my $loaded;
16044:     my %name_to_host;
16045:     my %internetdom;
16046:     my %LC_dns_serv;
16047: 
16048:     sub parse_hosts_tab {
16049: 	my ($file) = @_;
16050: 	foreach my $configline (@$file) {
16051: 	    next if ($configline =~ /^(\#|\s*$ )/x);
16052:             chomp($configline);
16053: 	    if ($configline =~ /^\^/) {
16054:                 if ($configline =~ /^\^([\w.\-]+)/) {
16055:                     $LC_dns_serv{$1} = 1;
16056:                 }
16057:                 next;
16058:             }
16059: 	    my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
16060: 	    $name=~s/\s//g;
16061: 	    if ($id && $domain && $role && $name) {
16062:                 if ((exists($hostname{$id})) && ($hostname{$id} ne '')) {
16063:                     my $curr = $hostname{$id};
16064:                     my $skip;
16065:                     if (ref($name_to_host{$curr}) eq 'ARRAY') {
16066:                         if (($curr eq $name) && (@{$name_to_host{$curr}} == 1)) {
16067:                             $skip = 1;
16068:                         } else {
16069:                             @{$name_to_host{$curr}} = grep { $_ ne $id } @{$name_to_host{$curr}};
16070:                         }
16071:                     }
16072:                     unless ($skip) {
16073:                         push(@{$name_to_host{$name}},$id);
16074:                     }
16075:                 } else {
16076:                     push(@{$name_to_host{$name}},$id);
16077:                 }
16078: 		$hostname{$id}=$name;
16079: 		$hostdom{$id}=$domain;
16080: 		if ($role eq 'library') { $libserv{$id}=$name; }
16081:                 if (defined($protocol)) {
16082:                     if ($protocol eq 'https') {
16083:                         $protocol{$id} = $protocol;
16084:                     } else {
16085:                         $protocol{$id} = 'http'; 
16086:                     }
16087:                 } else {
16088:                     $protocol{$id} = 'http';
16089:                 }
16090:                 if (defined($intdom)) {
16091:                     $internetdom{$id} = $intdom;
16092:                 }
16093: 	    }
16094: 	}
16095:     }
16096:     
16097:     sub reset_hosts_info {
16098: 	&purge_remembered();
16099: 	&reset_domain_info();
16100: 	&reset_hosts_ip_info();
16101:         undef(%internetdom);
16102: 	undef(%name_to_host);
16103: 	undef(%hostname);
16104: 	undef(%hostdom);
16105: 	undef(%libserv);
16106: 	undef($loaded);
16107:     }
16108: 
16109:     sub load_hosts_tab {
16110: 	my ($ignore_cache,$nocache) = @_;
16111: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache,$nocache);
16112: 	open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab");
16113: 	my @config = <$config>;
16114: 	&parse_hosts_tab(\@config);
16115: 	close($config);
16116: 	$loaded=1;
16117:     }
16118: 
16119:     sub hostname {
16120: 	&load_hosts_tab() if (!$loaded);
16121: 
16122: 	my ($lonid) = @_;
16123: 	return $hostname{$lonid};
16124:     }
16125: 
16126:     sub all_hostnames {
16127: 	&load_hosts_tab() if (!$loaded);
16128: 
16129: 	return %hostname;
16130:     }
16131: 
16132:     sub all_names {
16133:         my ($ignore_cache,$nocache) = @_;
16134: 	&load_hosts_tab($ignore_cache,$nocache) if (!$loaded);
16135: 
16136: 	return %name_to_host;
16137:     }
16138: 
16139:     sub all_host_domain {
16140:         &load_hosts_tab() if (!$loaded);
16141:         return %hostdom;
16142:     }
16143: 
16144:     sub all_host_intdom {
16145:         &load_hosts_tab() if (!$loaded);
16146:         return %internetdom;
16147:     }
16148: 
16149:     sub is_library {
16150: 	&load_hosts_tab() if (!$loaded);
16151: 
16152: 	return exists($libserv{$_[0]});
16153:     }
16154: 
16155:     sub all_library {
16156: 	&load_hosts_tab() if (!$loaded);
16157: 
16158: 	return %libserv;
16159:     }
16160: 
16161:     sub unique_library {
16162: 	#2x reverse removes all hostnames that appear more than once
16163:         my %unique = reverse &all_library();
16164:         return reverse %unique;
16165:     }
16166: 
16167:     sub get_servers {
16168: 	&load_hosts_tab() if (!$loaded);
16169: 
16170: 	my ($domain,$type) = @_;
16171: 	my %possible_hosts = ($type eq 'library') ? %libserv
16172: 	                                          : %hostname;
16173: 	my %result;
16174: 	if (ref($domain) eq 'ARRAY') {
16175: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
16176: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
16177: 		    $result{$host} = $hostname;
16178: 		}
16179: 	    }
16180: 	} else {
16181: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
16182: 		if ($hostdom{$host} eq $domain) {
16183: 		    $result{$host} = $hostname;
16184: 		}
16185: 	    }
16186: 	}
16187: 	return %result;
16188:     }
16189: 
16190:     sub get_unique_servers {
16191:         my %unique = reverse &get_servers(@_);
16192: 	return reverse %unique;
16193:     }
16194: 
16195:     sub host_domain {
16196: 	&load_hosts_tab() if (!$loaded);
16197: 
16198: 	my ($lonid) = @_;
16199: 	return $hostdom{$lonid};
16200:     }
16201: 
16202:     sub all_domains {
16203: 	&load_hosts_tab() if (!$loaded);
16204: 
16205: 	my %seen;
16206: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
16207: 	return @uniq;
16208:     }
16209: 
16210:     sub internet_dom {
16211:         &load_hosts_tab() if (!$loaded);
16212: 
16213:         my ($lonid) = @_;
16214:         return $internetdom{$lonid};
16215:     }
16216: 
16217:     sub is_LC_dns {
16218:         &load_hosts_tab() if (!$loaded);
16219: 
16220:         my ($hostname) = @_;
16221:         return exists($LC_dns_serv{$hostname});
16222:     }
16223: 
16224: }
16225: 
16226: { 
16227:     my %iphost;
16228:     my %name_to_ip;
16229:     my %lonid_to_ip;
16230: 
16231:     sub get_hosts_from_ip {
16232: 	my ($ip) = @_;
16233: 	my %iphosts = &get_iphost();
16234: 	if (ref($iphosts{$ip})) {
16235: 	    return @{$iphosts{$ip}};
16236: 	}
16237: 	return;
16238:     }
16239:     
16240:     sub reset_hosts_ip_info {
16241: 	undef(%iphost);
16242: 	undef(%name_to_ip);
16243: 	undef(%lonid_to_ip);
16244:     }
16245: 
16246:     sub get_host_ip {
16247: 	my ($lonid) = @_;
16248: 	if (exists($lonid_to_ip{$lonid})) {
16249: 	    return $lonid_to_ip{$lonid};
16250: 	}
16251: 	my $name=&hostname($lonid);
16252:    	my $ip = gethostbyname($name);
16253: 	return if (!$ip || length($ip) ne 4);
16254: 	$ip=inet_ntoa($ip);
16255: 	$name_to_ip{$name}   = $ip;
16256: 	$lonid_to_ip{$lonid} = $ip;
16257: 	return $ip;
16258:     }
16259:     
16260:     sub get_iphost {
16261: 	my ($ignore_cache,$nocache) = @_;
16262: 
16263: 	if (!$ignore_cache) {
16264: 	    if (%iphost) {
16265: 		return %iphost;
16266: 	    }
16267: 	    my ($ip_info,$cached)=
16268: 		&is_cached_new('iphost','iphost');
16269: 	    if ($cached) {
16270: 		%iphost      = %{$ip_info->[0]};
16271: 		%name_to_ip  = %{$ip_info->[1]};
16272: 		%lonid_to_ip = %{$ip_info->[2]};
16273: 		return %iphost;
16274: 	    }
16275: 	}
16276: 
16277: 	# get yesterday's info for fallback
16278: 	my %old_name_to_ip;
16279: 	my ($ip_info,$cached)=
16280: 	    &is_cached_new('iphost','iphost');
16281: 	if ($cached) {
16282: 	    %old_name_to_ip = %{$ip_info->[1]};
16283: 	}
16284: 
16285: 	my %name_to_host = &all_names($ignore_cache,$nocache);
16286: 	foreach my $name (keys(%name_to_host)) {
16287: 	    my $ip;
16288: 	    if (!exists($name_to_ip{$name})) {
16289: 		$ip = gethostbyname($name);
16290: 		if (!$ip || length($ip) ne 4) {
16291: 		    if (defined($old_name_to_ip{$name})) {
16292: 			$ip = $old_name_to_ip{$name};
16293: 			&logthis("Can't find $name defaulting to old $ip");
16294: 		    } else {
16295: 			&logthis("Name $name no IP found");
16296: 			next;
16297: 		    }
16298: 		} else {
16299: 		    $ip=inet_ntoa($ip);
16300: 		}
16301: 		$name_to_ip{$name} = $ip;
16302: 	    } else {
16303: 		$ip = $name_to_ip{$name};
16304: 	    }
16305: 	    foreach my $id (@{ $name_to_host{$name} }) {
16306: 		$lonid_to_ip{$id} = $ip;
16307: 	    }
16308: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
16309: 	}
16310:         unless ($nocache) {
16311: 	    &do_cache_new('iphost','iphost',
16312: 		          [\%iphost,\%name_to_ip,\%lonid_to_ip],
16313: 		          48*60*60);
16314:         }
16315: 
16316: 	return %iphost;
16317:     }
16318: 
16319:     #
16320:     #  Given a DNS returns the loncapa host name for that DNS 
16321:     # 
16322:     sub host_from_dns {
16323:         my ($dns) = @_;
16324:         my @hosts;
16325:         my $ip;
16326: 
16327:         if (exists($name_to_ip{$dns})) {
16328:             $ip = $name_to_ip{$dns};
16329:         }
16330:         if (!$ip) {
16331:             $ip = gethostbyname($dns); # Initial translation to IP is in net order.
16332:             if (length($ip) == 4) { 
16333: 	        $ip   = &IO::Socket::inet_ntoa($ip);
16334:             }
16335:         }
16336:         if ($ip) {
16337: 	    @hosts = get_hosts_from_ip($ip);
16338: 	    return $hosts[0];
16339:         }
16340:         return undef;
16341:     }
16342: 
16343:     sub get_internet_names {
16344:         my ($lonid) = @_;
16345:         return if ($lonid eq '');
16346:         my ($idnref,$cached)=
16347:             &is_cached_new('internetnames',$lonid);
16348:         if ($cached) {
16349:             return $idnref;
16350:         }
16351:         my $ip = &get_host_ip($lonid);
16352:         my @hosts = &get_hosts_from_ip($ip);
16353:         my %iphost = &get_iphost();
16354:         my (@idns,%seen);
16355:         foreach my $id (@hosts) {
16356:             my $dom = &host_domain($id);
16357:             my $prim_id = &domain($dom,'primary');
16358:             my $prim_ip = &get_host_ip($prim_id);
16359:             next if ($seen{$prim_ip});
16360:             if (ref($iphost{$prim_ip}) eq 'ARRAY') {
16361:                 foreach my $id (@{$iphost{$prim_ip}}) {
16362:                     my $intdom = &internet_dom($id);
16363:                     unless (grep(/^\Q$intdom\E$/,@idns)) {
16364:                         push(@idns,$intdom);
16365:                     }
16366:                 }
16367:             }
16368:             $seen{$prim_ip} = 1;
16369:         }
16370:         return &do_cache_new('internetnames',$lonid,\@idns,12*60*60);
16371:     }
16372: 
16373: }
16374: 
16375: sub all_loncaparevs {
16376:     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);
16377: }
16378: 
16379: # ---------------------------------------------------------- Read loncaparev table
16380: {
16381:     sub load_loncaparevs { 
16382:         if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
16383:             if (open(my $config,"<","$perlvar{'lonTabDir'}/loncaparevs.tab")) {
16384:                 while (my $configline=<$config>) {
16385:                     chomp($configline);
16386:                     my ($hostid,$loncaparev)=split(/:/,$configline);
16387:                     $loncaparevs{$hostid}=$loncaparev;
16388:                 }
16389:                 close($config);
16390:             }
16391:         }
16392:     }
16393: }
16394: 
16395: # ---------------------------------------------------------- Read serverhostID table
16396: {
16397:     sub load_serverhomeIDs {
16398:         if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
16399:             if (open(my $config,"<","$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
16400:                 while (my $configline=<$config>) {
16401:                     chomp($configline);
16402:                     my ($name,$id)=split(/:/,$configline);
16403:                     $serverhomeIDs{$name}=$id;
16404:                 }
16405:                 close($config);
16406:             }
16407:         }
16408:     }
16409: }
16410: 
16411: 
16412: BEGIN {
16413: 
16414: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
16415:     unless ($readit) {
16416: {
16417:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
16418:     %perlvar = (%perlvar,%{$configvars});
16419: }
16420: 
16421: 
16422: # ------------------------------------------------------ Read spare server file
16423: {
16424:     open(my $config,"<","$perlvar{'lonTabDir'}/spare.tab");
16425: 
16426:     while (my $configline=<$config>) {
16427:        chomp($configline);
16428:        if ($configline) {
16429: 	   my ($host,$type) = split(':',$configline,2);
16430: 	   if (!defined($type) || $type eq '') { $type = 'default' };
16431: 	   push(@{ $spareid{$type} }, $host);
16432:        }
16433:     }
16434:     close($config);
16435: }
16436: # ------------------------------------------------------------ Read permissions
16437: {
16438:     open(my $config,"<","$perlvar{'lonTabDir'}/roles.tab");
16439: 
16440:     while (my $configline=<$config>) {
16441: 	chomp($configline);
16442: 	if ($configline) {
16443: 	    my ($role,$perm)=split(/ /,$configline);
16444: 	    if ($perm ne '') { $pr{$role}=$perm; }
16445: 	}
16446:     }
16447:     close($config);
16448: }
16449: 
16450: # -------------------------------------------- Read plain texts for permissions
16451: {
16452:     open(my $config,"<","$perlvar{'lonTabDir'}/rolesplain.tab");
16453: 
16454:     while (my $configline=<$config>) {
16455: 	chomp($configline);
16456: 	if ($configline) {
16457: 	    my ($short,@plain)=split(/:/,$configline);
16458:             %{$prp{$short}} = ();
16459: 	    if (@plain > 0) {
16460:                 $prp{$short}{'std'} = $plain[0];
16461:                 for (my $i=1; $i<@plain; $i++) {
16462:                     $prp{$short}{'alt'.$i} = $plain[$i];  
16463:                 }
16464:             }
16465: 	}
16466:     }
16467:     close($config);
16468: }
16469: 
16470: # ---------------------------------------------------------- Read package table
16471: {
16472:     open(my $config,"<","$perlvar{'lonTabDir'}/packages.tab");
16473: 
16474:     while (my $configline=<$config>) {
16475: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
16476: 	chomp($configline);
16477: 	my ($short,$plain)=split(/:/,$configline);
16478: 	my ($pack,$name)=split(/\&/,$short);
16479: 	if ($plain ne '') {
16480: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
16481: 	    $packagetab{$short}=$plain; 
16482: 	}
16483:     }
16484:     close($config);
16485: }
16486: 
16487: # ---------------------------------------------------------- Read loncaparev table
16488: 
16489: &load_loncaparevs();
16490: 
16491: # ---------------------------------------------------------- Read serverhostID table
16492: 
16493: &load_serverhomeIDs();
16494: 
16495: # ---------------------------------------------------------- Read releaseslist XML
16496: {
16497:     my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
16498:     if (-e $file) {
16499:         my $parser = HTML::LCParser->new($file);
16500:         while (my $token = $parser->get_token()) {
16501:             if ($token->[0] eq 'S') {
16502:                 my $item = $token->[1];
16503:                 my $name = $token->[2]{'name'};
16504:                 my $value = $token->[2]{'value'};
16505:                 my $valuematch = $token->[2]{'valuematch'};
16506:                 my $namematch = $token->[2]{'namematch'};
16507:                 if ($item eq 'parameter') {
16508:                     if (($namematch ne '') || (($name ne '') && ($value ne '' || $valuematch ne ''))) {
16509:                         my $release = $parser->get_text();
16510:                         $release =~ s/(^\s*|\s*$ )//gx;
16511:                         $needsrelease{$item.':'.$name.':'.$value.':'.$valuematch.':'.$namematch} = $release;
16512:                     }
16513:                 } elsif ($item ne '' && $name ne '') {
16514:                     my $release = $parser->get_text();
16515:                     $release =~ s/(^\s*|\s*$ )//gx;
16516:                     $needsrelease{$item.':'.$name.':'.$value} = $release;
16517:                 }
16518:             }
16519:         }
16520:     }
16521: }
16522: 
16523: # ---------------------------------------------------------- Read managers table
16524: {
16525:     if (-e "$perlvar{'lonTabDir'}/managers.tab") {
16526:         if (open(my $config,"<","$perlvar{'lonTabDir'}/managers.tab")) {
16527:             while (my $configline=<$config>) {
16528:                 chomp($configline);
16529:                 next if ($configline =~ /^\#/);
16530:                 if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
16531:                     $managerstab{$configline} = 1;
16532:                 }
16533:             }
16534:             close($config);
16535:         }
16536:     }
16537: }
16538: 
16539: # ------------- set up temporary directory
16540: {
16541:     $tmpdir = LONCAPA::tempdir();
16542: 
16543: }
16544: 
16545: # ------------- set default texengine (domain default overrides this)
16546: {
16547:     $deftex = LONCAPA::texengine();
16548: }
16549: 
16550: # ------------- set default minimum length for passwords for internal auth users
16551: {
16552:     $passwdmin = LONCAPA::passwd_min();
16553: }
16554: 
16555: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
16556: 				'compress_threshold'=> 20_000,
16557:  			        });
16558: 
16559: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
16560: $dumpcount=0;
16561: $locknum=0;
16562: 
16563: &logtouch();
16564: &logthis('<font color="yellow">INFO: Read configuration</font>');
16565: $readit=1;
16566:     {
16567: 	use integer;
16568: 	my $test=(2**32)+1;
16569: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
16570: 	&logthis(" Detected 64bit platform ($_64bit)");
16571:     }
16572: }
16573: }
16574: 
16575: 1;
16576: __END__
16577: 
16578: =pod
16579: 
16580: =head1 NAME
16581: 
16582: Apache::lonnet - Subroutines to ask questions about things in the network.
16583: 
16584: =head1 SYNOPSIS
16585: 
16586: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
16587: 
16588:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
16589: 
16590: Common parameters:
16591: 
16592: =over 4
16593: 
16594: =item *
16595: 
16596: $uname : an internal username (if $cname expecting a course Id specifically)
16597: 
16598: =item *
16599: 
16600: $udom : a domain (if $cdom expecting a course's domain specifically)
16601: 
16602: =item *
16603: 
16604: $symb : a resource instance identifier
16605: 
16606: =item *
16607: 
16608: $namespace : the name of a .db file that contains the data needed or
16609: being set.
16610: 
16611: =back
16612: 
16613: =head1 OVERVIEW
16614: 
16615: lonnet provides subroutines which interact with the
16616: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
16617: about classes, users, and resources.
16618: 
16619: For many of these objects you can also use this to store data about
16620: them or modify them in various ways.
16621: 
16622: =head2 Symbs
16623: 
16624: To identify a specific instance of a resource, LON-CAPA uses symbols
16625: or "symbs"X<symb>. These identifiers are built from the URL of the
16626: map, the resource number of the resource in the map, and the URL of
16627: the resource itself. The latter is somewhat redundant, but might help
16628: if maps change.
16629: 
16630: An example is
16631: 
16632:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
16633: 
16634: The respective map entry is
16635: 
16636:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
16637:   title="Problem 2">
16638:  </resource>
16639: 
16640: Symbs are used by the random number generator, as well as to store and
16641: restore data specific to a certain instance of for example a problem.
16642: 
16643: =head2 Storing And Retrieving Data
16644: 
16645: X<store()>X<cstore()>X<restore()>Three of the most important functions
16646: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
16647: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
16648: is is the non-critical message twin of cstore. These functions are for
16649: handlers to store a perl hash to a user's permanent data space in an
16650: easy manner, and to retrieve it again on another call. It is expected
16651: that a handler would use this once at the beginning to retrieve data,
16652: and then again once at the end to send only the new data back.
16653: 
16654: The data is stored in the user's data directory on the user's
16655: homeserver under the ID of the course.
16656: 
16657: The hash that is returned by restore will have all of the previous
16658: value for all of the elements of the hash.
16659: 
16660: Example:
16661: 
16662:  #creating a hash
16663:  my %hash;
16664:  $hash{'foo'}='bar';
16665: 
16666:  #storing it
16667:  &Apache::lonnet::cstore(\%hash);
16668: 
16669:  #changing a value
16670:  $hash{'foo'}='notbar';
16671: 
16672:  #adding a new value
16673:  $hash{'bar'}='foo';
16674:  &Apache::lonnet::cstore(\%hash);
16675: 
16676:  #retrieving the hash
16677:  my %history=&Apache::lonnet::restore();
16678: 
16679:  #print the hash
16680:  foreach my $key (sort(keys(%history))) {
16681:    print("\%history{$key} = $history{$key}");
16682:  }
16683: 
16684: Will print out:
16685: 
16686:  %history{1:foo} = bar
16687:  %history{1:keys} = foo:timestamp
16688:  %history{1:timestamp} = 990455579
16689:  %history{2:bar} = foo
16690:  %history{2:foo} = notbar
16691:  %history{2:keys} = foo:bar:timestamp
16692:  %history{2:timestamp} = 990455580
16693:  %history{bar} = foo
16694:  %history{foo} = notbar
16695:  %history{timestamp} = 990455580
16696:  %history{version} = 2
16697: 
16698: Note that the special hash entries C<keys>, C<version> and
16699: C<timestamp> were added to the hash. C<version> will be equal to the
16700: total number of versions of the data that have been stored. The
16701: C<timestamp> attribute will be the UNIX time the hash was
16702: stored. C<keys> is available in every historical section to list which
16703: keys were added or changed at a specific historical revision of a
16704: hash.
16705: 
16706: B<Warning>: do not store the hash that restore returns directly. This
16707: will cause a mess since it will restore the historical keys as if the
16708: were new keys. I.E. 1:foo will become 1:1:foo etc.
16709: 
16710: Calling convention:
16711: 
16712:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname);
16713:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$laststore);
16714: 
16715: For more detailed information, see lonnet specific documentation.
16716: 
16717: =head1 RETURN MESSAGES
16718: 
16719: =over 4
16720: 
16721: =item * B<con_lost>: unable to contact remote host
16722: 
16723: =item * B<con_delayed>: unable to contact remote host, message will be delivered
16724: when the connection is brought back up
16725: 
16726: =item * B<con_failed>: unable to contact remote host and unable to save message
16727: for later delivery
16728: 
16729: =item * B<error:>: an error a occurred, a description of the error follows the :
16730: 
16731: =item * B<no_such_host>: unable to fund a host associated with the user/domain
16732: that was requested
16733: 
16734: =back
16735: 
16736: =head1 PUBLIC SUBROUTINES
16737: 
16738: =head2 Session Environment Functions
16739: 
16740: =over 4
16741: 
16742: =item * 
16743: X<appenv()>
16744: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
16745: the user envirnoment file, and will be restored for each access this
16746: user makes during this session, also modifies the %env for the current
16747: process. Optional rolesarrayref - if defined contains a reference to an array
16748: of roles which are exempt from the restriction on modifying user.role entries 
16749: in the user's environment.db and in %env.    
16750: 
16751: =item *
16752: X<delenv()>
16753: B<delenv($delthis,$regexp)>: removes all items from the session
16754: environment file that begin with $delthis. If the 
16755: optional second arg - $regexp - is true, $delthis is treated as a 
16756: regular expression, otherwise \Q$delthis\E is used. 
16757: The values are also deleted from the current processes %env.
16758: 
16759: =item * get_env_multiple($name) 
16760: 
16761: gets $name from the %env hash, it seemlessly handles the cases where multiple
16762: values may be defined and end up as an array ref.
16763: 
16764: returns an array of values
16765: 
16766: =back
16767: 
16768: =head2 User Information
16769: 
16770: =over 4
16771: 
16772: =item *
16773: X<queryauthenticate()>
16774: B<queryauthenticate($uname,$udom)>: try to determine user's current 
16775: authentication scheme
16776: 
16777: =item *
16778: X<authenticate()>
16779: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
16780: authenticate user from domain's lib servers (first use the current
16781: one). C<$upass> should be the users password.
16782: $checkdefauth is optional (value is 1 if a check should be made to
16783:    authenticate user using default authentication method, and allow
16784:    account creation if username does not have account in the domain).
16785: $clientcancheckhost is optional (value is 1 if checking whether the
16786:    server can host will occur on the client side in lonauth.pm).   
16787: 
16788: =item *
16789: X<homeserver()>
16790: B<homeserver($uname,$udom)>: find the server which has
16791: the user's directory and files (there must be only one), this caches
16792: the answer, and also caches if there is a borken connection.
16793: 
16794: =item *
16795: X<idget()>
16796: B<idget($udom,$idsref,$namespace)>: find the usernames behind either 
16797: a list of student/employee IDs or clicker IDs
16798: (student/employee IDs are a unique resource in a domain, there must be 
16799: only 1 ID per username, and only 1 username per ID in a specific domain).
16800: clickerIDs are not necessarily unique, as students might share clickers.
16801: (returns hash: id=>name,id=>name)
16802: 
16803: =item *
16804: X<idrget()>
16805: B<idrget($udom,@unames)>: find the IDs behind a list of
16806: usernames (returns hash: name=>id,name=>id)
16807: 
16808: =item *
16809: X<idput()>
16810: B<idput($udom,$idsref,$uhome,$namespace)>: store away a list of 
16811: names and associated student/employee IDs or clicker IDs.
16812: 
16813: =item *
16814: X<iddel()>
16815: B<iddel($udom,$idshashref,$uhome,$namespace)>: delete unwanted 
16816: student/employee ID or clicker ID username look-ups from domain.
16817: The homeserver ($uhome) and namespace ($namespace) are optional.
16818: If no $uhome is provided, it will be determined usig &homeserver()
16819: for each user.  If no $namespace is provided, the default is ids.
16820: 
16821: =item *
16822: X<updateclickers()>
16823: B<updateclickers($udom,$action,$idshashref,$uhome,$critical)>: update 
16824: clicker ID-to-username look-ups in clickers.db on library server.
16825: Permitted actions are add or del (i.e., add or delete). The 
16826: clickers.db contains clickerID as keys (escaped), and each corresponding
16827: value is an escaped comma-separated list of usernames (for whom the
16828: library server is the homeserver), who registered that particular ID.
16829: If $critical is true, the update will be sent via &critical, otherwise
16830: &reply() will be used.
16831: 
16832: =item *
16833: X<rolesinit()>
16834: B<rolesinit($udom,$username)>: get user privileges.
16835: returns user role, first access and timer interval hashes
16836: 
16837: =item *
16838: X<privileged()>
16839: B<privileged($username,$domain)>: returns a true if user has a
16840: privileged and active role (i.e. su or dc), false otherwise.
16841: 
16842: =item *
16843: X<getsection()>
16844: B<getsection($udom,$uname,$cname)>: finds the section of student in the
16845: course $cname, return section name/number or '' for "not in course"
16846: and '-1' for "no section"
16847: 
16848: =item *
16849: X<userenvironment()>
16850: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
16851: passed in @what from the requested user's environment, returns a hash
16852: 
16853: =item * 
16854: X<userlog_query()>
16855: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
16856: activity.log file. %filters defines filters applied when parsing the
16857: log file. These can be start or end timestamps, or the type of action
16858: - log to look for Login or Logout events, check for Checkin or
16859: Checkout, role for role selection. The response is in the form
16860: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
16861: escaped strings of the action recorded in the activity.log file.
16862: 
16863: =back
16864: 
16865: =head2 User Roles
16866: 
16867: =over 4
16868: 
16869: =item *
16870: 
16871: allowed($priv,$uri,$symb,$role,$clientip,$noblockcheck) : check for a user privilege; 
16872: returns codes for allowed actions.
16873: 
16874: The first argument is required, all others are optional.
16875: 
16876: $priv is the privilege being checked.
16877: $uri contains additional information about what is being checked for access (e.g.,
16878: URL, course ID etc.). 
16879: $symb is the unique resource instance identifier in a course; if needed,
16880: but not provided, it will be retrieved via a call to &symbread(). 
16881: $role is the role for which a priv is being checked (only used if priv is evb). 
16882: $clientip is the user's IP address (only used when checking for access to portfolio 
16883: files).
16884: $noblockcheck, if true, skips calls to &has_comm_blocking() for the bre priv. This 
16885: prevents recursive calls to &allowed.
16886: 
16887:  F: full access
16888:  U,I,K: authentication modes (cxx only)
16889:  '': forbidden
16890:  1: user needs to choose course
16891:  2: browse allowed
16892:  A: passphrase authentication needed
16893:  B: access temporarily blocked because of a blocking event in a course.
16894:  D: access blocked because access is required via session initiated via deep-link 
16895: 
16896: =item *
16897: 
16898: constructaccess($url,$setpriv) : check for access to construction space URL
16899: 
16900: See if the owner domain and name in the URL match those in the
16901: expected environment.  If so, return three element list
16902: ($ownername,$ownerdomain,$ownerhome).
16903: 
16904: Otherwise return the null string.
16905: 
16906: If second argument 'setpriv' is true, it assigns the privileges,
16907: and returns the same three element list, unless the owner has
16908: blocked "ad hoc" Domain Coordinator access to the Author Space,
16909: in which case the null string is returned.
16910: 
16911: =item *
16912: 
16913: definerole($rolename,$sysrole,$domrole,$courole,$uname,$udom) : define role;
16914: define a custom role rolename set privileges in format of lonTabs/roles.tab
16915: for system, domain, and course level. $uname and $udom are optional (current
16916: user's username and domain will be used when either of $uname or $udom are absent.
16917: 
16918: =item *
16919: 
16920: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
16921: (rolesplain.tab); plain text explanation of a user role term.
16922: $type is Course (default) or Community.
16923: If $forcedefault evaluates to true, text returned will be default 
16924: text for $type. Otherwise, if this is a course, the text returned 
16925: will be a custom name for the role (if defined in the course's 
16926: environment).  If no custom name is defined the default is returned.
16927:    
16928: =item *
16929: 
16930: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv) :
16931: All arguments are optional. Returns a hash of a roles, either for
16932: co-author/assistant author roles for a user's Construction Space
16933: (default), or if $context is 'userroles', roles for the user himself,
16934: In the hash, keys are set to colon-separated $uname,$udom,$role, and
16935: (optionally) if $withsec is true, a fourth colon-separated item - $section.
16936: For each key, value is set to colon-separated start and end times for
16937: the role.  If no username and domain are specified, will default to
16938: current user/domain. Types, roles, and roledoms are references to arrays
16939: of role statuses (active, future or previous), roles 
16940: (e.g., cc,in, st etc.) and domains of the roles which can be used
16941: to restrict the list of roles reported. If no array ref is 
16942: provided for types, will default to return only active roles.
16943: 
16944: =item *
16945: 
16946: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
16947: user: $uname:$udom has a role in the course: $cdom_$cnum. 
16948: 
16949: Additional optional arguments are: $type (if role checking is to be restricted 
16950: to certain user status types -- previous (expired roles), active (currently
16951: available roles) or future (roles available in the future), and
16952: $hideprivileged -- if true will not report course roles for users who
16953: have active Domain Coordinator role in course's domain or in additional
16954: domains (specified in 'Domains to check for privileged users' in course
16955: environment -- set via:  Course Settings -> Classlists and staff listing).
16956: 
16957: =item *
16958: 
16959: privileged($username,$domain,$possdomains,$possroles) : returns 1 if user
16960: $username:$domain is a privileged user (e.g., Domain Coordinator or Super User)
16961: $possdomains and $possroles are optional array refs -- to domains to check and
16962: roles to check.  If $possdomains is not specified, a dump will be done of the
16963: users' roles.db to check for a dc or su role in any domain. This can be
16964: time consuming if &privileged is called repeatedly (e.g., when displaying a
16965: classlist), so in such cases, supplying a $possdomains array is preferred, as
16966: this then allows &privileged_by_domain() to be used, which caches the identity
16967: of privileged users, eliminating the need for repeated calls to &dump().
16968: 
16969: =item *
16970: 
16971: privileged_by_domain($possdomains,$roles) : returns a hash of a hash of a hash,
16972: where the outer hash keys are domains specified in the $possdomains array ref,
16973: next inner hash keys are privileged roles specified in the $roles array ref,
16974: and the innermost hash contains key = value pairs for username:domain = end:start
16975: for active or future "privileged" users with that role in that domain. To avoid
16976: repeated dumps of domain roles -- via &get_domain_roles() -- contents of the
16977: innerhash are cached using priv_$role and $dom as the identifiers.
16978: 
16979: =back
16980: 
16981: =head2 User Modification
16982: 
16983: =over 4
16984: 
16985: =item *
16986: 
16987: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
16988: user for the level given by URL.  Optional start and end dates (leave empty
16989: string or zero for "no date")
16990: 
16991: =item *
16992: 
16993: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
16994: change a users, password, possible return values are: ok,
16995: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
16996: refused
16997: 
16998: =item *
16999: 
17000: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
17001: 
17002: =item *
17003: 
17004: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
17005:            $forceid,$desiredhome,$email,$inststatus,$candelete) :
17006: 
17007: will update user information (firstname,middlename,lastname,generation,
17008: permanentemail), and if forceid is true, student/employee ID also.
17009: A user's institutional affiliation(s) can also be updated.
17010: User information fields will not be overwritten with empty entries 
17011: unless the field is included in the $candelete array reference.
17012: This array is included when a single user is modified via "Manage Users",
17013: or when Autoupdate.pl is run by cron in a domain.
17014: 
17015: =item *
17016: 
17017: modifystudent
17018: 
17019: modify a student's enrollment and identification information.
17020: The course id is resolved based on the current user's environment.  
17021: This means the invoking user must be a course coordinator or otherwise
17022: associated with a course.
17023: 
17024: This call is essentially a wrapper for lonnet::modifyuser and
17025: lonnet::modify_student_enrollment
17026: 
17027: Inputs: 
17028: 
17029: =over 4
17030: 
17031: =item B<$udom> Student's loncapa domain
17032: 
17033: =item B<$uname> Student's loncapa login name
17034: 
17035: =item B<$uid> Student/Employee ID
17036: 
17037: =item B<$umode> Student's authentication mode
17038: 
17039: =item B<$upass> Student's password
17040: 
17041: =item B<$first> Student's first name
17042: 
17043: =item B<$middle> Student's middle name
17044: 
17045: =item B<$last> Student's last name
17046: 
17047: =item B<$gene> Student's generation
17048: 
17049: =item B<$usec> Student's section in course
17050: 
17051: =item B<$end> Unix time of the roles expiration
17052: 
17053: =item B<$start> Unix time of the roles start date
17054: 
17055: =item B<$forceid> If defined, allow $uid to be changed
17056: 
17057: =item B<$desiredhome> server to use as home server for student
17058: 
17059: =item B<$email> Student's permanent e-mail address
17060: 
17061: =item B<$type> Type of enrollment (auto or manual)
17062: 
17063: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
17064: 
17065: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
17066: 
17067: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
17068: 
17069: =item B<$context> role change context (shown in User Management Logs display in a course)
17070: 
17071: =item B<$inststatus> institutional status of user - : separated string of escaped status types
17072: 
17073: =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.
17074: 
17075: =back
17076: 
17077: =item *
17078: 
17079: modify_student_enrollment
17080: 
17081: Change a student's enrollment status in a class.  The environment variable
17082: 'role.request.course' must be defined for this function to proceed.
17083: 
17084: Inputs:
17085: 
17086: =over 4
17087: 
17088: =item $udom, student's domain
17089: 
17090: =item $uname, student's name
17091: 
17092: =item $uid, student's user id
17093: 
17094: =item $first, student's first name
17095: 
17096: =item $middle
17097: 
17098: =item $last
17099: 
17100: =item $gene
17101: 
17102: =item $usec
17103: 
17104: =item $end
17105: 
17106: =item $start
17107: 
17108: =item $type
17109: 
17110: =item $locktype
17111: 
17112: =item $cid
17113: 
17114: =item $selfenroll
17115: 
17116: =item $context
17117: 
17118: =item $credits, number of credits student will earn from this class
17119: 
17120: =item $instsec, institutional course section code for student
17121: 
17122: =back
17123: 
17124: 
17125: =item *
17126: 
17127: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
17128: custom role; give a custom role to a user for the level given by URL.  Specify
17129: name and domain of role author, and role name
17130: 
17131: =item *
17132: 
17133: revokerole($udom,$uname,$url,$role) : revoke a role for url
17134: 
17135: =item *
17136: 
17137: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
17138: 
17139: =back
17140: 
17141: =head2 Course Infomation
17142: 
17143: =over 4
17144: 
17145: =item *
17146: 
17147: coursedescription($courseid,$options) : returns a hash of information about the
17148: specified course id, including all environment settings for the
17149: course, the description of the course will be in the hash under the
17150: key 'description'
17151: 
17152: $options is an optional parameter that if supplied is a hash reference that controls
17153: what how this function works.  It has the following key/values:
17154: 
17155: =over 4
17156: 
17157: =item freshen_cache
17158: 
17159: If defined, and the environment cache for the course is valid, it is 
17160: returned in the returned hash.
17161: 
17162: =item one_time
17163: 
17164: If defined, the last cache time is set to _now_
17165: 
17166: =item user
17167: 
17168: If defined, the supplied username is used instead of the current user.
17169: 
17170: 
17171: =back
17172: 
17173: =item *
17174: 
17175: resdata($name,$domain,$type,@which) : request for current parameter
17176: setting for a specific $type, where $type is either 'course' or 'user',
17177: @what should be a list of parameters to ask about. This routine caches
17178: answers for 10 minutes.
17179: 
17180: =item *
17181: 
17182: get_courseresdata($courseid, $domain) : dump the entire course resource
17183: data base, returning a hash that is keyed by the resource name and has
17184: values that are the resource value.  I believe that the timestamps and
17185: versions are also returned.
17186: 
17187: =back
17188: 
17189: =head2 Course Modification
17190: 
17191: =over 4
17192: 
17193: =item *
17194: 
17195: writecoursepref($courseid,%prefs) : write preferences (environment
17196: database) for a course
17197: 
17198: =item *
17199: 
17200: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
17201: 
17202: =item *
17203: 
17204: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
17205: 
17206: =item *
17207: 
17208: is_course($courseid), is_course($cdom, $cnum)
17209: 
17210: Accepts either a combined $courseid (in the form of domain_courseid) or the
17211: two component version $cdom, $cnum. It checks if the specified course exists.
17212: 
17213: Returns:
17214:     undef if the course doesn't exist, otherwise
17215:     in scalar context the combined courseid.
17216:     in list context the two components of the course identifier, domain and 
17217:     courseid.    
17218: 
17219: =back
17220: 
17221: =head2 Bubblesheet Configuration
17222: 
17223: =over 4
17224: 
17225: =item *
17226: 
17227: get_scantron_config($which)
17228: 
17229: $which - the name of the configuration to parse from the file.
17230: 
17231: Parses and returns the bubblesheet configuration line selected as a
17232: hash of configuration file fields.
17233: 
17234: 
17235: Returns:
17236:     If the named configuration is not in the file, an empty
17237:     hash is returned.
17238: 
17239:     a hash with the fields
17240:       name         - internal name for the this configuration setup
17241:       description  - text to display to operator that describes this config
17242:       CODElocation - if 0 or the string 'none'
17243:                           - no CODE exists for this config
17244:                      if -1 || the string 'letter'
17245:                           - a CODE exists for this config and is
17246:                             a string of letters
17247:                      Unsupported value (but planned for future support)
17248:                           if a positive integer
17249:                                - The CODE exists as the first n items from
17250:                                  the question section of the form
17251:                           if the string 'number'
17252:                                - The CODE exists for this config and is
17253:                                  a string of numbers
17254:       CODEstart   - (only matter if a CODE exists) column in the line where
17255:                      the CODE starts
17256:       CODElength  - length of the CODE
17257:       IDstart     - column where the student/employee ID starts
17258:       IDlength    - length of the student/employee ID info
17259:       Qstart      - column where the information from the bubbled
17260:                     'questions' start
17261:       Qlength     - number of columns comprising a single bubble line from
17262:                     the sheet. (usually either 1 or 10)
17263:       Qon         - either a single character representing the character used
17264:                     to signal a bubble was chosen in the positional setup, or
17265:                     the string 'letter' if the letter of the chosen bubble is
17266:                     in the final, or 'number' if a number representing the
17267:                     chosen bubble is in the file (1->A 0->J)
17268:       Qoff        - the character used to represent that a bubble was
17269:                     left blank
17270:       PaperID     - if the scanning process generates a unique number for each
17271:                     sheet scanned the column that this ID number starts in
17272:       PaperIDlength - number of columns that comprise the unique ID number
17273:                       for the sheet of paper
17274:       FirstName   - column that the first name starts in
17275:       FirstNameLength - number of columns that the first name spans
17276:       LastName    - column that the last name starts in
17277:       LastNameLength - number of columns that the last name spans
17278:       BubblesPerRow - number of bubbles available in each row used to
17279:                       bubble an answer. (If not specified, 10 assumed).
17280: 
17281: 
17282: =item *
17283: 
17284: get_scantronformat_file($cdom)
17285: 
17286: $cdom - the course's domain (optional); if not supplied, uses
17287: domain for current $env{'request.course.id'}.
17288: 
17289: Returns an array containing lines from the scantron format file for
17290: the domain of the course.
17291: 
17292: If a url for a custom.tab file is listed in domain's configuration.db,
17293: lines are from this file.
17294: 
17295: Otherwise, if a default.tab has been published in RES space by the
17296: domainconfig user, lines are from this file.
17297: 
17298: Otherwise, fall back to getting lines from the legacy file on the
17299: local server:  /home/httpd/lonTabs/default_scantronformat.tab
17300: 
17301: =back
17302: 
17303: =head2 Resource Subroutines
17304: 
17305: =over 4
17306: 
17307: =item *
17308: 
17309: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
17310: 
17311: =item *
17312: 
17313: repcopy($filename) : subscribes to the requested file, and attempts to
17314: replicate from the owning library server, Might return
17315: 'unavailable', 'not_found', 'forbidden', 'ok', or
17316: 'bad_request', also attempts to grab the metadata for the
17317: resource. Expects the local filesystem pathname
17318: (/home/httpd/html/res/....)
17319: 
17320: =back
17321: 
17322: =head2 Resource Information
17323: 
17324: =over 4
17325: 
17326: =item *
17327: 
17328: EXT($varname,$symb,$udom,$uname,$usection,$recurse,$cid) : evaluates 
17329: and returns the value of a variety of different possible values,
17330: $varname should be a request string, and the other parameters can be
17331: used to specify who and what one is asking about. Ordinarily, $cid 
17332: does not need to be specified, as it is retrived from 
17333: $env{'request.course.id'}, but &Apache::lonnet::EXT() is called
17334: within lonuserstate::loadmap() when initializing a course, before
17335: $env{'request.course.id'} has been set, so it needs to be provided
17336: in that one case.
17337: 
17338: Possible values for $varname are environment.lastname (or other item
17339: from the envirnment hash), user.name (or someother aspect about the
17340: user), resource.0.maxtries (or some other part and parameter of a
17341: resource)
17342: 
17343: =item *
17344: 
17345: directcondval($number) : get current value of a condition; reads from a state
17346: string
17347: 
17348: =item *
17349: 
17350: condval($condidx) : value of condition index based on state
17351: 
17352: =item *
17353: 
17354: metadata($uri,$what,$toolsymb,$liburi,$prefix,$depthcount) : request a
17355: resource's metadata, $what should be either a specific key, or either
17356: 'keys' (to get a list of possible keys) or 'packages' to get a list of
17357: packages that this resource currently uses, the last 3 arguments are 
17358: only used internally for recursive metadata.
17359: 
17360: the toolsymb is only used where the uri is for an external tool (for which
17361: the uri as well as the symb are guaranteed to be unique).
17362: 
17363: this function automatically caches all requests except any made recursively
17364: to retrieve a list of metadata keys for an imported library file ($liburi is 
17365: defined).
17366: 
17367: =item *
17368: 
17369: metadata_query($query,$custom,$customshow) : make a metadata query against the
17370: network of library servers; returns file handle of where SQL and regex results
17371: will be stored for query
17372: 
17373: =item *
17374: 
17375: symbread($filename,$donotrecurse,$ignorecachednull,$checkforblock,$possibles) : 
17376: return symbolic list entry (all arguments optional). 
17377: 
17378: Args: filename is the filename (including path) for the file for which a symb 
17379: is required; donotrecurse, if true will prevent calls to allowed() being made 
17380: to check access status if more than one resource was found in the bighash 
17381: (see rev. 1.249) to avoid an infinite loop if an ambiguous resource is part of 
17382: a randompick); ignorecachednull, if true will prevent a symb of '' being 
17383: returned if $env{$cache_str} is defined as ''; checkforblock if true will
17384: cause possible symbs to be checked to determine if they are subject to content
17385: blocking, if so they will not be included as possible symbs; possibles is a
17386: ref to a hash, which, as a side effect, will be populated with all possible 
17387: symbs (content blocking not tested).
17388:  
17389: returns the data handle
17390: 
17391: =item *
17392: 
17393: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
17394: and is a possible symb for the URL in $thisfn, and if is an encrypted
17395: resource that the user accessed using /enc/ returns a 1 on success, 0
17396: on failure, user must be in a course, as it assumes the existence of
17397: the course initial hash, and uses $env('request.course.id'}.  The third
17398: arg is an optional reference to a scalar.  If this arg is passed in the 
17399: call to symbverify, it will be set to 1 if the symb has been set to be 
17400: encrypted; otherwise it will be null.  
17401: 
17402: =item *
17403: 
17404: symbclean($symb) : removes versions numbers from a symb, returns the
17405: cleaned symb
17406: 
17407: =item *
17408: 
17409: is_on_map($uri) : checks if the $uri is somewhere on the current
17410: course map, user must be in a course for it to work.
17411: 
17412: =item *
17413: 
17414: numval($salt) : return random seed value (addend for rndseed)
17415: 
17416: =item *
17417: 
17418: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
17419: a random seed, all arguments are optional, if they aren't sent it uses the
17420: environment to derive them. Note: if symb isn't sent and it can't get one
17421: from &symbread it will use the current time as its return value
17422: 
17423: =item *
17424: 
17425: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
17426: unfakeable, receipt
17427: 
17428: =item *
17429: 
17430: receipt() : API to ireceipt working off of env values; given out to users
17431: 
17432: =item *
17433: 
17434: countacc($url) : count the number of accesses to a given URL
17435: 
17436: =item *
17437: 
17438: 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
17439: 
17440: =item *
17441: 
17442: 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)
17443: 
17444: =item *
17445: 
17446: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
17447: 
17448: =item *
17449: 
17450: devalidate($symb) : devalidate temporary spreadsheet calculations,
17451: forcing spreadsheet to reevaluate the resource scores next time.
17452: 
17453: =item * 
17454: 
17455: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
17456: when viewing in course context.
17457: 
17458:  input: six args -- filename (decluttered), course number, course domain,
17459:                     url, symb (if registered) and group (if this is a 
17460:                     group item -- e.g., bulletin board, group page etc.).
17461: 
17462:  output: array of five scalars --
17463:          $cfile -- url for file editing if editable on current server
17464:          $home -- homeserver of resource (i.e., for author if published,
17465:                                           or course if uploaded.).
17466:          $switchserver --  1 if server switch will be needed.
17467:          $forceedit -- 1 if icon/link should be to go to edit mode 
17468:          $forceview -- 1 if icon/link should be to go to view mode
17469: 
17470: =item *
17471: 
17472: is_course_upload($file,$cnum,$cdom)
17473: 
17474: Used in course context to determine if current file was uploaded to 
17475: the course (i.e., would be found in /userfiles/docs on the course's 
17476: homeserver.
17477: 
17478:   input: 3 args -- filename (decluttered), course number and course domain.
17479:   output: boolean -- 1 if file was uploaded.
17480: 
17481: =back
17482: 
17483: =head2 Storing/Retreiving Data
17484: 
17485: =over 4
17486: 
17487: =item *
17488: 
17489: store($storehash,$symb,$namespace,$udom,$uname,$laststore) : stores hash
17490: permanently for this url; hashref needs to be given and should be a \%hashname;
17491: the remaining args aren't required and if they aren't passed or are '' they will
17492: be derived from the env (with the exception of $laststore, which is an 
17493: optional arg used when a user's submission is stored in grading).
17494: $laststore is $version=$timestamp, where $version is the most recent version
17495: number retrieved for the corresponding $symb in the $namespace db file, and
17496: $timestamp is the timestamp for that transaction (UNIX time).
17497: $laststore is currently only passed when cstore() is called by 
17498: structuretags::finalize_storage().
17499: 
17500: =item *
17501: 
17502: cstore($storehash,$symb,$namespace,$udom,$uname,$laststore) : same as store
17503: but uses critical subroutine
17504: 
17505: =item *
17506: 
17507: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
17508: all args are optional
17509: 
17510: =item *
17511: 
17512: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
17513: dumps the complete (or key matching regexp) namespace into a hash
17514: ($udom, $uname, $regexp, $range are optional) for a namespace that is
17515: normally &store()ed into
17516: 
17517: $range should be either an integer '100' (give me the first 100
17518:                                            matching records)
17519:               or be  two integers sperated by a - with no spaces
17520:                  '30-50' (give me the 30th through the 50th matching
17521:                           records)
17522: 
17523: 
17524: =item *
17525: 
17526: putstore($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog) :
17527: replaces a &store() version of data with a replacement set of data
17528: for a particular resource in a namespace passed in the $storehash hash 
17529: reference. If $tolog is true, the transaction is logged in the courselog
17530: with an action=PUTSTORE.
17531: 
17532: =item *
17533: 
17534: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
17535: works very similar to store/cstore, but all data is stored in a
17536: temporary location and can be reset using tmpreset, $storehash should
17537: be a hash reference, returns nothing on success
17538: 
17539: =item *
17540: 
17541: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
17542: similar to restore, but all data is stored in a temporary location and
17543: can be reset using tmpreset. Returns a hash of values on success,
17544: error string otherwise.
17545: 
17546: =item *
17547: 
17548: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
17549: deltes all keys for $symb form the temporary storage hash.
17550: 
17551: =item *
17552: 
17553: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
17554: reference filled in from namesp ($udom and $uname are optional)
17555: 
17556: =item *
17557: 
17558: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
17559: namesp ($udom and $uname are optional)
17560: 
17561: =item *
17562: 
17563: dump($namespace,$udom,$uname,$regexp,$range) : 
17564: dumps the complete (or key matching regexp) namespace into a hash
17565: ($udom, $uname, $regexp, $range are optional)
17566: 
17567: $range should be either an integer '100' (give me the first 100
17568:                                            matching records)
17569:               or be  two integers sperated by a - with no spaces
17570:                  '30-50' (give me the 30th through the 50th matching
17571:                           records)
17572: =item *
17573: 
17574: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
17575: $store can be a scalar, an array reference, or if the amount to be 
17576: incremented is > 1, a hash reference.
17577: 
17578: ($udom and $uname are optional)
17579: 
17580: =item *
17581: 
17582: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
17583: ($udom and $uname are optional)
17584: 
17585: =item *
17586: 
17587: cput($namespace,$storehash,$udom,$uname) : critical put
17588: ($udom and $uname are optional)
17589: 
17590: =item *
17591: 
17592: newput($namespace,$storehash,$udom,$uname) :
17593: 
17594: Attempts to store the items in the $storehash, but only if they don't
17595: currently exist, if this succeeds you can be certain that you have 
17596: successfully created a new key value pair in the $namespace db.
17597: 
17598: 
17599: Args:
17600:  $namespace: name of database to store values to
17601:  $storehash: hashref to store to the db
17602:  $udom: (optional) domain of user containing the db
17603:  $uname: (optional) name of user caontaining the db
17604: 
17605: Returns:
17606:  'ok' -> succeeded in storing all keys of $storehash
17607:  'key_exists: <key>' -> failed to anything out of $storehash, as at
17608:                         least <key> already existed in the db (other
17609:                         requested keys may also already exist)
17610:  'error: <msg>' -> unable to tie the DB or other error occurred
17611:  'con_lost' -> unable to contact request server
17612:  'refused' -> action was not allowed by remote machine
17613: 
17614: 
17615: =item *
17616: 
17617: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
17618: reference filled in from namesp (encrypts the return communication)
17619: ($udom and $uname are optional)
17620: 
17621: =item *
17622: 
17623: log($udom,$name,$home,$message) : write to permanent log for user; use
17624: critical subroutine
17625: 
17626: =item *
17627: 
17628: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
17629: array reference filled in from namespace found in domain level on either
17630: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
17631: 
17632: =item *
17633: 
17634: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
17635: domain level either on specified domain server ($uhome) or primary domain 
17636: server ($udom and $uhome are optional)
17637: 
17638: =item * 
17639: 
17640: get_domain_defaults($target_domain,$ignore_cache) : returns hash with defaults 
17641: for: authentication, language, quotas, timezone, date locale, and portal URL in
17642: the target domain.
17643: 
17644: May also include additional key => value pairs for the following groups:
17645: 
17646: =over
17647: 
17648: =item
17649: disk quotas (MB allocated by default to portfolios and authoring spaces).
17650: 
17651: =over
17652: 
17653: =item defaultquota, authorquota
17654: 
17655: =back
17656: 
17657: =item
17658: tools (availability of aboutme page, blog, webDAV access for authoring spaces,
17659: portfolio for users).
17660: 
17661: =over
17662: 
17663: =item
17664: aboutme, blog, webdav, portfolio
17665: 
17666: =back
17667: 
17668: =item
17669: requestcourses: ability to request courses, and how requests are processed.
17670: 
17671: =over
17672: 
17673: =item
17674: official, unofficial, community, textbook, placement
17675: 
17676: =back
17677: 
17678: =item
17679: inststatus: types of institutional affiliation, and order in which they are displayed.
17680: 
17681: =over
17682: 
17683: =item
17684: inststatustypes, inststatusorder, inststatusguest
17685: 
17686: =back
17687: 
17688: =item
17689: coursedefaults: can PDF forms can be created, default credits for courses, default quotas (MB)
17690: for course's uploaded content.
17691: 
17692: =over
17693: 
17694: =item
17695: canuse_pdfforms, officialcredits, unofficialcredits, textbookcredits, officialquota, unofficialquota, 
17696: communityquota, textbookquota, placementquota
17697: 
17698: =back
17699: 
17700: =item
17701: usersessions: set options for hosting of your users in other domains, and hosting of users from other domains
17702: on your servers.
17703: 
17704: =over
17705: 
17706: =item 
17707: remotesessions, hostedsessions
17708: 
17709: =back
17710: 
17711: =back
17712: 
17713: In cases where a domain coordinator has never used the "Set Domain Configuration"
17714: utility to create a configuration.db file on a domain's primary library server 
17715: only the following domain defaults: auth_def, auth_arg_def, lang_def
17716: -- corresponding values are authentication type (internal, krb4, krb5,
17717: or localauth), initial password or a kerberos realm, language (e.g., en-us) -- 
17718: will be available. Values are retrieved from cache (if current), unless the
17719: optional $ignore_cache arg is true, or from domain's configuration.db (if available),
17720: or lastly from values in lonTabs/dns_domain,tab, or lonTabs/domain.tab.
17721: 
17722: Typical usage:
17723: 
17724: %domdefaults = &get_domain_defaults($target_domain);
17725: 
17726: =back
17727: 
17728: =head2 Network Status Functions
17729: 
17730: =over 4
17731: 
17732: =item *
17733: 
17734: dirlist() : return directory list based on URI (first arg).
17735: 
17736: Inputs: 1 required, 5 optional.
17737: 
17738: =over
17739: 
17740: =item 
17741: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
17742: 
17743: =item
17744: $userdomain - domain of user/course to be listed. Extracted from $uri if absent. 
17745: 
17746: =item
17747: $username -  username of user/course to be listed. Extracted from $uri if absent. 
17748: 
17749: =item
17750: $getpropath - boolean: 1 if prepend path using &propath(). 
17751: 
17752: =item
17753: $getuserdir - boolean: 1 if prepend path for "userfiles".
17754: 
17755: =item 
17756: $alternateRoot - path to prepend in place of path from $uri.
17757: 
17758: =back
17759: 
17760: Returns: Array of up to two items.
17761: 
17762: =over
17763: 
17764: a reference to an array of files/subdirectories
17765: 
17766: =over
17767: 
17768: Each element in the array of files/subdirectories is a & separated list of
17769: item name and the result of running stat on the item.  If dirlist was requested
17770: for a file instead of a directory, the item name will be ''. For a directory 
17771: listing, if the item is a metadata file, the element will end &N&M 
17772: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
17773: default copyright set (1).  
17774: 
17775: =back
17776: 
17777: a scalar containing error condition (if encountered).
17778: 
17779: =over
17780: 
17781: =item 
17782: no_host (no homeserver identified for $username:$domain).
17783: 
17784: =item 
17785: no_such_host (server contacted for listing not identified as valid host).
17786: 
17787: =item 
17788: con_lost (connection to remote server failed).
17789: 
17790: =item 
17791: refused (invalid $username:$domain received on lond side).
17792: 
17793: =item 
17794: no_such_dir (directory at specified path on lond side does not exist). 
17795: 
17796: =item 
17797: empty (directory at specified path on lond side is empty).
17798: 
17799: =over
17800: 
17801: This is currently not encountered because the &ls3, &ls2, 
17802: &ls (_handler) routines on the lond side do not filter out
17803: . and .. from a directory listing. 
17804: 
17805: =back
17806: 
17807: =back
17808: 
17809: =back
17810: 
17811: =item *
17812: 
17813: spareserver() : find server with least workload from spare.tab
17814: 
17815: 
17816: =item *
17817: 
17818: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
17819: if there is no corresponding loncapa host.
17820: 
17821: =back
17822: 
17823: 
17824: =head2 Apache Request
17825: 
17826: =over 4
17827: 
17828: =item *
17829: 
17830: ssi($url,%hash) : server side include, does a complete request cycle on url to
17831: localhost, posts hash
17832: 
17833: =back
17834: 
17835: =head2 Data to String to Data
17836: 
17837: =over 4
17838: 
17839: =item *
17840: 
17841: hash2str(%hash) : convert a hash into a string complete with escaping and '='
17842: and '&' separators, supports elements that are arrayrefs and hashrefs
17843: 
17844: =item *
17845: 
17846: hashref2str($hashref) : convert a hashref into a string complete with
17847: escaping and '=' and '&' separators, supports elements that are
17848: arrayrefs and hashrefs
17849: 
17850: =item *
17851: 
17852: arrayref2str($arrayref) : convert an arrayref into a string complete
17853: with escaping and '&' separators, supports elements that are arrayrefs
17854: and hashrefs
17855: 
17856: =item *
17857: 
17858: str2hash($string) : convert string to hash using unescaping and
17859: splitting on '=' and '&', supports elements that are arrayrefs and
17860: hashrefs
17861: 
17862: =item *
17863: 
17864: str2array($string) : convert string to hash using unescaping and
17865: splitting on '&', supports elements that are arrayrefs and hashrefs
17866: 
17867: =back
17868: 
17869: =head2 Logging Routines
17870: 
17871: 
17872: These routines allow one to make log messages in the lonnet.log and
17873: lonnet.perm logfiles.
17874: 
17875: =over 4
17876: 
17877: =item *
17878: 
17879: logtouch() : make sure the logfile, lonnet.log, exists
17880: 
17881: =item *
17882: 
17883: logthis() : append message to the normal lonnet.log file, it gets
17884: preiodically rolled over and deleted.
17885: 
17886: =item *
17887: 
17888: logperm() : append a permanent message to lonnet.perm.log, this log
17889: file never gets deleted by any automated portion of the system, only
17890: messages of critical importance should go in here.
17891: 
17892: 
17893: =back
17894: 
17895: =head2 General File Helper Routines
17896: 
17897: =over 4
17898: 
17899: =item *
17900: 
17901: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
17902: (a) files in /uploaded
17903:   (i) If a local copy of the file exists - 
17904:       compares modification date of local copy with last-modified date for 
17905:       definitive version stored on home server for course. If local copy is 
17906:       stale, requests a new version from the home server and stores it. 
17907:       If the original has been removed from the home server, then local copy 
17908:       is unlinked.
17909:   (ii) If local copy does not exist -
17910:       requests the file from the home server and stores it. 
17911:   
17912:   If $caller is 'uploadrep':  
17913:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
17914:     for request for files originally uploaded via DOCS. 
17915:      - returns 'ok' if fresh local copy now available, -1 otherwise.
17916:   
17917:   Otherwise:
17918:      This indicates a call from the content generation phase of the request.
17919:      -  returns the entire contents of the file or -1.
17920:      
17921: (b) files in /res
17922:    - returns the entire contents of a file or -1; 
17923:    it properly subscribes to and replicates the file if neccessary.
17924: 
17925: 
17926: =item *
17927: 
17928: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
17929:                   reference
17930: 
17931: returns either a stat() list of data about the file or an empty list
17932: if the file doesn't exist or couldn't find out about it (connection
17933: problems or user unknown)
17934: 
17935: =item *
17936: 
17937: filelocation($dir,$file) : returns file system location of a file
17938: based on URI; meant to be "fairly clean" absolute reference, $dir is a
17939: directory that relative $file lookups are to looked in ($dir of /a/dir
17940: and a file of ../bob will become /a/bob)
17941: 
17942: =item *
17943: 
17944: hreflocation($dir,$file) : returns file system location or a URL; same as
17945: filelocation except for hrefs
17946: 
17947: =item *
17948: 
17949: declutter() : declutters URLs -- remove beginning slashes, 'res' etc.
17950: also removes beginning /home/httpd/html unless /priv/ follows it.
17951: 
17952: =back
17953: 
17954: =head2 Usererfile file routines (/uploaded*)
17955: 
17956: =over 4
17957: 
17958: =item *
17959: 
17960: userfileupload(): main rotine for putting a file in a user or course's
17961:                   filespace, arguments are,
17962: 
17963:  formname - required - this is the name of the element in $env where the
17964:            filename, and the contents of the file to create/modifed exist
17965:            the filename is in $env{'form.'.$formname.'.filename'} and the
17966:            contents of the file is located in $env{'form.'.$formname}
17967:  context - if coursedoc, store the file in the course of the active role
17968:              of the current user; 
17969:            if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
17970:            if 'canceloverwrite': delete file in tmp/overwrites directory
17971:  subdir - required - subdirectory to put the file in under ../userfiles/
17972:          if undefined, it will be placed in "unknown"
17973: 
17974:  (This routine calls clean_filename() to remove any dangerous
17975:  characters from the filename, and then calls finuserfileupload() to
17976:  complete the transaction)
17977: 
17978:  returns either the url of the uploaded file (/uploaded/....) if successful
17979:  and /adm/notfound.html if unsuccessful
17980: 
17981: =item *
17982: 
17983: clean_filename(): routine for cleaing a filename up for storage in
17984:                  userfile space, argument is:
17985: 
17986:  filename - proposed filename
17987: 
17988: returns: the new clean filename
17989: 
17990: =item *
17991: 
17992: finishuserfileupload(): routine that creates and sends the file to
17993: userspace, probably shouldn't be called directly
17994: 
17995:   docuname: username or courseid of destination for the file
17996:   docudom: domain of user/course of destination for the file
17997:   formname: same as for userfileupload()
17998:   fname: filename (including subdirectories) for the file
17999:   parser: if 'parse', will parse (html) file to extract references to objects, links etc.
18000:           if hashref, and context is scantron, will convert csv format to standard format
18001:   allfiles: reference to hash used to store objects found by parser
18002:   codebase: reference to hash used for codebases of java objects found by parser
18003:   thumbwidth: width (pixels) of thumbnail to be created for uploaded image
18004:   thumbheight: height (pixels) of thumbnail to be created for uploaded image
18005:   resizewidth: width to be used to resize image using resizeImage from ImageMagick
18006:   resizeheight: height to be used to resize image using resizeImage from ImageMagick
18007:   context: if 'overwrite', will move the uploaded file from its temporary location to
18008:             userfiles to facilitate overwriting a previously uploaded file with same name.
18009:   mimetype: reference to scalar to accommodate mime type determined
18010:             from File::MMagic if $parser = parse.
18011: 
18012:  returns either the url of the uploaded file (/uploaded/....) if successful
18013:  and /adm/notfound.html if unsuccessful (or an error message if context 
18014:  was 'overwrite').
18015:  
18016: 
18017: =item *
18018: 
18019: renameuserfile(): renames an existing userfile to a new name
18020: 
18021:   Args:
18022:    docuname: username or courseid of destination for the file
18023:    docudom: domain of user/course of destination for the file
18024:    old: current file name (including any subdirs under userfiles)
18025:    new: desired file name (including any subdirs under userfiles)
18026: 
18027: =item *
18028: 
18029: mkdiruserfile(): creates a directory is a userfiles dir
18030: 
18031:   Args:
18032:    docuname: username or courseid of destination for the file
18033:    docudom: domain of user/course of destination for the file
18034:    dir: dir to create (including any subdirs under userfiles)
18035: 
18036: =item *
18037: 
18038: removeuserfile(): removes a file that exists in userfiles
18039: 
18040:   Args:
18041:    docuname: username or courseid of destination for the file
18042:    docudom: domain of user/course of destination for the file
18043:    fname: filname to delete (including any subdirs under userfiles)
18044: 
18045: =item *
18046: 
18047: removeuploadedurl(): convience function for removeuserfile()
18048: 
18049:   Args:
18050:    url:  a full /uploaded/... url to delete
18051: 
18052: =item * 
18053: 
18054: get_portfile_permissions():
18055:   Args:
18056:     domain: domain of user or course contain the portfolio files
18057:     user: name of user or num of course contain the portfolio files
18058:   Returns:
18059:     hashref of a dump of the proper file_permissions.db
18060:    
18061: 
18062: =item * 
18063: 
18064: get_access_controls():
18065: 
18066: Args:
18067:   current_permissions: the hash ref returned from get_portfile_permissions()
18068:   group: (optional) the group you want the files associated with
18069:   file: (optional) the file you want access info on
18070: 
18071: Returns:
18072:     a hash (keys are file names) of hashes containing
18073:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
18074:         values are XML containing access control settings (see below) 
18075: 
18076: Internal notes:
18077: 
18078:  access controls are stored in file_permissions.db as key=value pairs.
18079:     key -> path to file/file_name\0uniqueID:scope_end_start
18080:         where scope -> public,guest,course,group,domains or users.
18081:               end -> UNIX time for end of access (0 -> no end date)
18082:               start -> UNIX time for start of access
18083: 
18084:     value -> XML description of access control
18085:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
18086:             <start></start>
18087:             <end></end>
18088: 
18089:             <password></password>  for scope type = guest
18090: 
18091:             <domain></domain>     for scope type = course or group
18092:             <number></number>
18093:             <roles id="">
18094:              <role></role>
18095:              <access></access>
18096:              <section></section>
18097:              <group></group>
18098:             </roles>
18099: 
18100:             <dom></dom>         for scope type = domains
18101: 
18102:             <users>             for scope type = users
18103:              <user>
18104:               <uname></uname>
18105:               <udom></udom>
18106:              </user>
18107:             </users>
18108:            </scope> 
18109:               
18110:  Access data is also aggregated for each file in an additional key=value pair:
18111:  key -> path to file/file_name\0accesscontrol 
18112:  value -> reference to hash
18113:           hash contains key = value pairs
18114:           where key = uniqueID:scope_end_start
18115:                 value = UNIX time record was last updated
18116: 
18117:           Used to improve speed of look-ups of access controls for each file.  
18118:  
18119:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
18120: 
18121: =item *
18122: 
18123: modify_access_controls():
18124: 
18125: Modifies access controls for a portfolio file
18126: Args
18127: 1. file name
18128: 2. reference to hash of required changes,
18129: 3. domain
18130: 4. username
18131:   where domain,username are the domain of the portfolio owner 
18132:   (either a user or a course) 
18133: 
18134: Returns:
18135: 1. result of additions or updates ('ok' or 'error', with error message). 
18136: 2. result of deletions ('ok' or 'error', with error message).
18137: 3. reference to hash of any new or updated access controls.
18138: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
18139:    key = integer (inbound ID)
18140:    value = uniqueID
18141: 
18142: =item *
18143: 
18144: get_timebased_id():
18145: 
18146: Attempts to get a unique timestamp-based suffix for use with items added to a 
18147: course via the Course Editor (e.g., folders, composite pages, 
18148: group bulletin boards).
18149: 
18150: Args: (first three required; six others optional)
18151: 
18152: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
18153:    docssequence, or name of group
18154: 
18155: 2. keyid (alphanumeric): name of temporary locking key in hash,
18156:    e.g., num, boardids
18157: 
18158: 3. namespace: name of gdbm file used to store suffixes already assigned;  
18159:    file will be named nohist_namespace.db
18160: 
18161: 4. cdom: domain of course; default is current course domain from %env
18162: 
18163: 5. cnum: course number; default is current course number from %env
18164: 
18165: 6. idtype: set to concat if an additional digit is to be appended to the 
18166:    unix timestamp to form the suffix, if the plain timestamp is already
18167:    in use.  Default is to not do this, but simply increment the unix 
18168:    timestamp by 1 until a unique key is obtained.
18169: 
18170: 7. who: holder of locking key; defaults to user:domain for user.
18171: 
18172: 8. locktries: number of attempts to obtain a lock (sleep of 1s before 
18173:    retrying); default is 3.
18174: 
18175: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.  
18176: 
18177: Returns:
18178: 
18179: 1. suffix obtained (numeric)
18180: 
18181: 2. result of deleting locking key (ok if deleted, or lock never obtained)
18182: 
18183: 3. error: contains (localized) error message if an error occurred.
18184: 
18185: 
18186: =back
18187: 
18188: =head2 HTTP Helper Routines
18189: 
18190: =over 4
18191: 
18192: =item *
18193: 
18194: escape() : unpack non-word characters into CGI-compatible hex codes
18195: 
18196: =item *
18197: 
18198: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
18199: 
18200: =back
18201: 
18202: =head1 PRIVATE SUBROUTINES
18203: 
18204: =head2 Underlying communication routines (Shouldn't call)
18205: 
18206: =over 4
18207: 
18208: =item *
18209: 
18210: subreply() : tries to pass a message to lonc, returns con_lost if incapable
18211: 
18212: =item *
18213: 
18214: reply() : uses subreply to send a message to remote machine, logs all failures
18215: 
18216: =item *
18217: 
18218: critical() : passes a critical message to another server; if cannot
18219: get through then place message in connection buffer directory and
18220: returns con_delayed, if incapable of saving message, returns
18221: con_failed
18222: 
18223: =item *
18224: 
18225: reconlonc() : tries to reconnect lonc client processes.
18226: 
18227: =back
18228: 
18229: =head2 Resource Access Logging
18230: 
18231: =over 4
18232: 
18233: =item *
18234: 
18235: flushcourselogs() : flush (save) buffer logs and access logs
18236: 
18237: =item *
18238: 
18239: courselog($what) : save message for course in hash
18240: 
18241: =item *
18242: 
18243: courseacclog($what) : save message for course using &courselog().  Perform
18244: special processing for specific resource types (problems, exams, quizzes, etc).
18245: 
18246: =item *
18247: 
18248: goodbye() : flush course logs and log shutting down; it is called in srm.conf
18249: as a PerlChildExitHandler
18250: 
18251: =back
18252: 
18253: =head2 Other
18254: 
18255: =over 4
18256: 
18257: =item *
18258: 
18259: symblist($mapname,%newhash) : update symbolic storage links
18260: 
18261: =back
18262: 
18263: =cut
18264: 

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