File:  [LON-CAPA] / loncom / lonnet / perl / lonnet.pm
Revision 1.1536: download - view: text, annotated - select for diffs
Tue Feb 18 19:30:43 2025 UTC (3 days, 22 hours ago) by raeburn
Branches: MAIN
CVS tags: version_2_12_X, HEAD
- Commit log entry for lonxml.pm rev. 1.245 (4/3/2003) falsely claimed:
  "lonxml::whichuser, now says if the user is public". This was still false
  after whichuser() moved to lonnet.pm (rev. 1.790; 10/12/2006).

    1: # The LearningOnline Network
    2: # TCP networking package
    3: #
    4: # $Id: lonnet.pm,v 1.1536 2025/02/18 19:30:43 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_cmd' || $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:         if (ref($domconfig{'coursedefaults'}{'crseditors'}) eq 'ARRAY') {
 2833:             $domdefaults{'crseditors'}=join(',',@{$domconfig{'coursedefaults'}{'crseditors'}});
 2834:         }
 2835:         foreach my $type (@coursetypes) {
 2836:             if (ref($domconfig{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
 2837:                 unless ($type eq 'community') {
 2838:                     $domdefaults{$type.'credits'} = $domconfig{'coursedefaults'}{'coursecredits'}{$type};
 2839:                 }
 2840:             }
 2841:             if (ref($domconfig{'coursedefaults'}{'uploadquota'}) eq 'HASH') {
 2842:                 $domdefaults{$type.'quota'} = $domconfig{'coursedefaults'}{'uploadquota'}{$type};
 2843:             }
 2844:             if (ref($domconfig{'coursedefaults'}{'coursequota'}) eq 'HASH') {
 2845:                 $domdefaults{$type.'coursequota'} = $domconfig{'coursedefaults'}{'coursequota'}{$type};
 2846:             }
 2847:             if ($domdefaults{'postsubmit'} eq 'on') {
 2848:                 if (ref($domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}) eq 'HASH') {
 2849:                     $domdefaults{$type.'postsubtimeout'} = 
 2850:                         $domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}{$type}; 
 2851:                 }
 2852:             }
 2853:             if (ref($domconfig{'coursedefaults'}{'domexttool'}) eq 'HASH') {
 2854:                 $domdefaults{$type.'domexttool'} = $domconfig{'coursedefaults'}{'domexttool'}{$type};
 2855:             } else {
 2856:                 $domdefaults{$type.'domexttool'} = 1;
 2857:             }
 2858:             if (ref($domconfig{'coursedefaults'}{'exttool'}) eq 'HASH') {
 2859:                 $domdefaults{$type.'exttool'} = $domconfig{'coursedefaults'}{'exttool'}{$type};
 2860:             } else {
 2861:                 $domdefaults{$type.'exttool'} = 0;
 2862:             }
 2863:             if (ref($domconfig{'coursedefaults'}{'crsauthor'}) eq 'HASH') {
 2864:                 $domdefaults{$type.'crsauthor'} = $domconfig{'coursedefaults'}{'crsauthor'}{$type};
 2865:             } else {
 2866:                 $domdefaults{$type.'crsauthor'} = 1;
 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:         if (ref($domconfig{'privacy'}{'othdom'}) eq 'HASH') {
 3023:             $domdefaults{'privacyothdom'} = $domconfig{'privacy'}{'othdom'};
 3024:         }
 3025:     }
 3026:     &do_cache_new('domdefaults',$domain,\%domdefaults,$cachetime);
 3027:     return %domdefaults;
 3028: }
 3029: 
 3030: sub get_dom_cats {
 3031:     my ($dom) = @_;
 3032:     return unless (&domain($dom));
 3033:     my ($cats,$cached)=&is_cached_new('cats',$dom);
 3034:     unless (defined($cached)) {
 3035:         my %domconfig = &get_dom('configuration',['coursecategories'],$dom);
 3036:         if (ref($domconfig{'coursecategories'}) eq 'HASH') {
 3037:             if (ref($domconfig{'coursecategories'}{'cats'}) eq 'HASH') {
 3038:                 %{$cats} = %{$domconfig{'coursecategories'}{'cats'}};
 3039:             } else {
 3040:                 $cats = {};
 3041:             }
 3042:         } else {
 3043:             $cats = {};
 3044:         }
 3045:         &do_cache_new('cats',$dom,$cats,3600);
 3046:     }
 3047:     return $cats;
 3048: }
 3049: 
 3050: sub get_dom_instcats {
 3051:     my ($dom) = @_;
 3052:     return unless (&domain($dom));
 3053:     my ($instcats,$cached)=&is_cached_new('instcats',$dom);
 3054:     unless (defined($cached)) {
 3055:         my (%coursecodes,%codes,@codetitles,%cat_titles,%cat_order);
 3056:         my $totcodes = &retrieve_instcodes(\%coursecodes,$dom);
 3057:         if ($totcodes > 0) {
 3058:             my $caller = 'global';
 3059:             if (&auto_instcode_format($caller,$dom,\%coursecodes,\%codes,
 3060:                                       \@codetitles,\%cat_titles,\%cat_order) eq 'ok') {
 3061:                 $instcats = {
 3062:                                 totcodes => $totcodes,
 3063:                                 codes => \%codes,
 3064:                                 codetitles => \@codetitles,
 3065:                                 cat_titles => \%cat_titles,
 3066:                                 cat_order => \%cat_order,
 3067:                             };
 3068:                 &do_cache_new('instcats',$dom,$instcats,3600);
 3069:             }
 3070:         }
 3071:     }
 3072:     return $instcats;
 3073: }
 3074: 
 3075: sub retrieve_instcodes {
 3076:     my ($coursecodes,$dom) = @_;
 3077:     my $totcodes;
 3078:     my %courses = &courseiddump($dom,'.',1,'.','.','.',undef,undef,'Course');
 3079:     foreach my $course (keys(%courses)) {
 3080:         if (ref($courses{$course}) eq 'HASH') {
 3081:             if ($courses{$course}{'inst_code'} ne '') {
 3082:                 $$coursecodes{$course} = $courses{$course}{'inst_code'};
 3083:                 $totcodes ++;
 3084:             }
 3085:         }
 3086:     }
 3087:     return $totcodes;
 3088: }
 3089: 
 3090: sub course_portal_url {
 3091:     my ($cnum,$cdom,$r) = @_;
 3092:     my $chome = &homeserver($cnum,$cdom);
 3093:     my $hostname = &hostname($chome);
 3094:     my $protocol = $protocol{$chome};
 3095:     $protocol = 'http' if ($protocol ne 'https');
 3096:     my %domdefaults = &get_domain_defaults($cdom);
 3097:     my $firsturl;
 3098:     if ($domdefaults{'portal_def'}) {
 3099:         $firsturl = $domdefaults{'portal_def'};
 3100:     } else {
 3101:         my $alias = &use_proxy_alias($r,$chome);
 3102:         $hostname = $alias if ($alias ne '');
 3103:         $firsturl = $protocol.'://'.$hostname;
 3104:     }
 3105:     return $firsturl;
 3106: }
 3107: 
 3108: sub url_prefix {
 3109:     my ($r,$dom,$home,$context) = @_;
 3110:     my $prefix;
 3111:     my %domdefs = &get_domain_defaults($dom);
 3112:     if ($domdefs{'portal_def'} && $domdefs{'portal_def_'.$context}) {
 3113:         if ($domdefs{'portal_def'} =~ m{^(https?://[^/]+)}) {
 3114:             $prefix = $1;
 3115:         }
 3116:     }
 3117:     if ($prefix eq '') {
 3118:         my $hostname = &hostname($home);
 3119:         my $protocol = $protocol{$home};
 3120:         $protocol = 'http' if ($protocol{$home} ne 'https');
 3121:         my $alias = &use_proxy_alias($r,$home);
 3122:         $hostname = $alias if ($alias ne '');
 3123:         $prefix = $protocol.'://'.$hostname;
 3124:     }
 3125:     return $prefix;
 3126: }
 3127: 
 3128: # --------------------------------------------- Get domain config for passwords
 3129: 
 3130: sub get_passwdconf {
 3131:     my ($dom) = @_;
 3132:     my (%passwdconf,$gotconf,$lookup);
 3133:     my ($result,$cached)=&is_cached_new('passwdconf',$dom);
 3134:     if (defined($cached)) {
 3135:         if (ref($result) eq 'HASH') {
 3136:             %passwdconf = %{$result};
 3137:             $gotconf = 1;
 3138:         }
 3139:     }
 3140:     unless ($gotconf) {
 3141:         my %domconfig = &get_dom('configuration',['passwords'],$dom);
 3142:         if (ref($domconfig{'passwords'}) eq 'HASH') {
 3143:             %passwdconf = %{$domconfig{'passwords'}};
 3144:         }
 3145:         my $cachetime = 24*60*60;
 3146:         &do_cache_new('passwdconf',$dom,\%passwdconf,$cachetime);
 3147:     }
 3148:     return %passwdconf;
 3149: }
 3150: 
 3151: # --------------------------------------------------- Assign a key to a student
 3152: 
 3153: sub assign_access_key {
 3154: #
 3155: # a valid key looks like uname:udom#comments
 3156: # comments are being appended
 3157: #
 3158:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
 3159:     $kdom=
 3160:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
 3161:     $knum=
 3162:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
 3163:     $cdom=
 3164:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 3165:     $cnum=
 3166:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 3167:     $udom=$env{'user.name'} unless (defined($udom));
 3168:     $uname=$env{'user.domain'} unless (defined($uname));
 3169:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
 3170:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
 3171:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
 3172:                                                   # assigned to this person
 3173:                                                   # - this should not happen,
 3174:                                                   # unless something went wrong
 3175:                                                   # the first time around
 3176: # ready to assign
 3177:         $logentry=$1.'; '.$logentry;
 3178:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
 3179:                                                  $kdom,$knum) eq 'ok') {
 3180: # key now belongs to user
 3181: 	    my $envkey='key.'.$cdom.'_'.$cnum;
 3182:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
 3183:                 &appenv({'environment.'.$envkey => $ckey});
 3184:                 return 'ok';
 3185:             } else {
 3186:                 return 
 3187:   'error: Count not permanently assign key, will need to be re-entered later.';
 3188: 	    }
 3189:         } else {
 3190:             return 'error: Could not assign key, try again later.';
 3191:         }
 3192:     } elsif (!$existing{$ckey}) {
 3193: # the key does not exist
 3194: 	return 'error: The key does not exist';
 3195:     } else {
 3196: # the key is somebody else's
 3197: 	return 'error: The key is already in use';
 3198:     }
 3199: }
 3200: 
 3201: # ------------------------------------------ put an additional comment on a key
 3202: 
 3203: sub comment_access_key {
 3204: #
 3205: # a valid key looks like uname:udom#comments
 3206: # comments are being appended
 3207: #
 3208:     my ($ckey,$cdom,$cnum,$logentry)=@_;
 3209:     $cdom=
 3210:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 3211:     $cnum=
 3212:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 3213:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
 3214:     if ($existing{$ckey}) {
 3215:         $existing{$ckey}.='; '.$logentry;
 3216: # ready to assign
 3217:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
 3218:                                                  $cdom,$cnum) eq 'ok') {
 3219: 	    return 'ok';
 3220:         } else {
 3221: 	    return 'error: Count not store comment.';
 3222:         }
 3223:     } else {
 3224: # the key does not exist
 3225: 	return 'error: The key does not exist';
 3226:     }
 3227: }
 3228: 
 3229: # ------------------------------------------------------ Generate a set of keys
 3230: 
 3231: sub generate_access_keys {
 3232:     my ($number,$cdom,$cnum,$logentry)=@_;
 3233:     $cdom=
 3234:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 3235:     $cnum=
 3236:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 3237:     unless (&allowed('mky',$cdom)) { return 0; }
 3238:     unless (($cdom) && ($cnum)) { return 0; }
 3239:     if ($number>10000) { return 0; }
 3240:     sleep(2); # make sure don't get same seed twice
 3241:     srand(time()^($$+($$<<15))); # from "Programming Perl"
 3242:     my $total=0;
 3243:     for (my $i=1;$i<=$number;$i++) {
 3244:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
 3245:                   sprintf("%lx",int(100000*rand)).'-'.
 3246:                   sprintf("%lx",int(100000*rand));
 3247:        $newkey=~s/1/g/g; # folks mix up 1 and l
 3248:        $newkey=~s/0/h/g; # and also 0 and O
 3249:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
 3250:        if ($existing{$newkey}) {
 3251:            $i--;
 3252:        } else {
 3253: 	  if (&put('accesskeys',
 3254:               { $newkey => '# generated '.localtime().
 3255:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
 3256:                            '; '.$logentry },
 3257: 		   $cdom,$cnum) eq 'ok') {
 3258:               $total++;
 3259: 	  }
 3260:        }
 3261:     }
 3262:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
 3263:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
 3264:     return $total;
 3265: }
 3266: 
 3267: # ------------------------------------------------------- Validate an accesskey
 3268: 
 3269: sub validate_access_key {
 3270:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
 3271:     $cdom=
 3272:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 3273:     $cnum=
 3274:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 3275:     $udom=$env{'user.domain'} unless (defined($udom));
 3276:     $uname=$env{'user.name'} unless (defined($uname));
 3277:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
 3278:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
 3279: }
 3280: 
 3281: # ------------------------------------- Find the section of student in a course
 3282: sub devalidate_getsection_cache {
 3283:     my ($udom,$unam,$courseid)=@_;
 3284:     my $hashid="$udom:$unam:$courseid";
 3285:     &devalidate_cache_new('getsection',$hashid);
 3286: }
 3287: 
 3288: sub courseid_to_courseurl {
 3289:     my ($courseid) = @_;
 3290:     #already url style courseid
 3291:     return $courseid if ($courseid =~ m{^/});
 3292: 
 3293:     if (exists($env{'course.'.$courseid.'.num'})) {
 3294: 	my $cnum = $env{'course.'.$courseid.'.num'};
 3295: 	my $cdom = $env{'course.'.$courseid.'.domain'};
 3296: 	return "/$cdom/$cnum";
 3297:     }
 3298: 
 3299:     my %courseinfo=&coursedescription($courseid);
 3300:     if (exists($courseinfo{'num'})) {
 3301: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
 3302:     }
 3303: 
 3304:     return undef;
 3305: }
 3306: 
 3307: sub getsection {
 3308:     my ($udom,$unam,$courseid)=@_;
 3309:     my $cachetime=1800;
 3310: 
 3311:     my $hashid="$udom:$unam:$courseid";
 3312:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
 3313:     if (defined($cached)) { return $result; }
 3314: 
 3315:     my %Pending; 
 3316:     my %Expired;
 3317:     #
 3318:     # Each role can either have not started yet (pending), be active, 
 3319:     #    or have expired.
 3320:     #
 3321:     # If there is an active role, we are done.
 3322:     #
 3323:     # If there is more than one role which has not started yet, 
 3324:     #     choose the one which will start sooner
 3325:     # If there is one role which has not started yet, return it.
 3326:     #
 3327:     # If there is more than one expired role, choose the one which ended last.
 3328:     # If there is a role which has expired, return it.
 3329:     #
 3330:     $courseid = &courseid_to_courseurl($courseid);
 3331:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
 3332:     foreach my $key (keys(%roleshash)) {
 3333:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
 3334:         my $section=$1;
 3335:         if ($key eq $courseid.'_st') { $section=''; }
 3336:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
 3337:         my $now=time;
 3338:         if (defined($end) && $end && ($now > $end)) {
 3339:             $Expired{$end}=$section;
 3340:             next;
 3341:         }
 3342:         if (defined($start) && $start && ($now < $start)) {
 3343:             $Pending{$start}=$section;
 3344:             next;
 3345:         }
 3346:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
 3347:     }
 3348:     #
 3349:     # Presumedly there will be few matching roles from the above
 3350:     # loop and the sorting time will be negligible.
 3351:     if (scalar(keys(%Pending))) {
 3352:         my ($time) = sort {$a <=> $b} keys(%Pending);
 3353:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
 3354:     } 
 3355:     if (scalar(keys(%Expired))) {
 3356:         my @sorted = sort {$a <=> $b} keys(%Expired);
 3357:         my $time = pop(@sorted);
 3358:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
 3359:     }
 3360:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
 3361: }
 3362: 
 3363: sub save_cache {
 3364:     &purge_remembered();
 3365:     #&Apache::loncommon::validate_page();
 3366:     undef(%env);
 3367:     undef($env_loaded);
 3368: }
 3369: 
 3370: my $to_remember=-1;
 3371: my %remembered;
 3372: my %accessed;
 3373: my $kicks=0;
 3374: my $hits=0;
 3375: sub make_key {
 3376:     my ($name,$id) = @_;
 3377:     if (length($id) > 65 
 3378: 	&& length(&escape($id)) > 200) {
 3379: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
 3380:     }
 3381:     return &escape($name.':'.$id);
 3382: }
 3383: 
 3384: sub devalidate_cache_new {
 3385:     my ($name,$id,$debug) = @_;
 3386:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
 3387:     my $remembered_id=$name.':'.$id;
 3388:     $id=&make_key($name,$id);
 3389:     $memcache->delete($id);
 3390:     delete($remembered{$remembered_id});
 3391:     delete($accessed{$remembered_id});
 3392: }
 3393: 
 3394: sub is_cached_new {
 3395:     my ($name,$id,$debug) = @_;
 3396:     my $remembered_id=$name.':'.$id; # this is to avoid make_key (which is slow) whenever possible
 3397:     if (exists($remembered{$remembered_id})) {
 3398: 	if ($debug) { &Apache::lonnet::logthis("Early return $remembered_id of $remembered{$remembered_id} "); }
 3399: 	$accessed{$remembered_id}=[&gettimeofday()];
 3400: 	$hits++;
 3401: 	return ($remembered{$remembered_id},1);
 3402:     }
 3403:     $id=&make_key($name,$id);
 3404:     my $value = $memcache->get($id);
 3405:     if (!(defined($value))) {
 3406: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
 3407: 	return (undef,undef);
 3408:     }
 3409:     if ($value eq '__undef__') {
 3410: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
 3411: 	$value=undef;
 3412:     }
 3413:     &make_room($remembered_id,$value,$debug);
 3414:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
 3415:     return ($value,1);
 3416: }
 3417: 
 3418: sub do_cache_new {
 3419:     my ($name,$id,$value,$time,$debug) = @_;
 3420:     my $remembered_id=$name.':'.$id;
 3421:     $id=&make_key($name,$id);
 3422:     my $setvalue=$value;
 3423:     if (!defined($setvalue)) {
 3424: 	$setvalue='__undef__';
 3425:     }
 3426:     if (!defined($time) ) {
 3427: 	$time=600;
 3428:     }
 3429:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
 3430:     my $result = $memcache->set($id,$setvalue,$time);
 3431:     if (! $result) {
 3432: 	&logthis("caching of id -> $id  failed");
 3433: 	$memcache->disconnect_all();
 3434:     }
 3435:     # need to make a copy of $value
 3436:     &make_room($remembered_id,$value,$debug);
 3437:     return $value;
 3438: }
 3439: 
 3440: sub make_room {
 3441:     my ($remembered_id,$value,$debug)=@_;
 3442: 
 3443:     $remembered{$remembered_id}= (ref($value)) ? &Storable::dclone($value)
 3444:                                     : $value;
 3445:     if ($to_remember<0) { return; }
 3446:     $accessed{$remembered_id}=[&gettimeofday()];
 3447:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
 3448:     my $to_kick;
 3449:     my $max_time=0;
 3450:     foreach my $other (keys(%accessed)) {
 3451: 	if (&tv_interval($accessed{$other}) > $max_time) {
 3452: 	    $to_kick=$other;
 3453: 	    $max_time=&tv_interval($accessed{$other});
 3454: 	}
 3455:     }
 3456:     delete($remembered{$to_kick});
 3457:     delete($accessed{$to_kick});
 3458:     $kicks++;
 3459:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
 3460:     return;
 3461: }
 3462: 
 3463: sub purge_remembered {
 3464:     #&logthis("Tossing ".scalar(keys(%remembered)));
 3465:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
 3466:     undef(%remembered);
 3467:     undef(%accessed);
 3468: }
 3469: # ------------------------------------- Read an entry from a user's environment
 3470: 
 3471: sub userenvironment {
 3472:     my ($udom,$unam,@what)=@_;
 3473:     my $items;
 3474:     foreach my $item (@what) {
 3475:         $items.=&escape($item).'&';
 3476:     }
 3477:     $items=~s/\&$//;
 3478:     my %returnhash=();
 3479:     my $uhome = &homeserver($unam,$udom);
 3480:     unless ($uhome eq 'no_host') {
 3481:         my @answer=split(/\&/, 
 3482:             &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
 3483:         if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
 3484:             return %returnhash;
 3485:         }
 3486:         my $i;
 3487:         for ($i=0;$i<=$#what;$i++) {
 3488: 	    $returnhash{$what[$i]}=&unescape($answer[$i]);
 3489:         }
 3490:     }
 3491:     return %returnhash;
 3492: }
 3493: 
 3494: # ---------------------------------------------------------- Get a studentphoto
 3495: sub studentphoto {
 3496:     my ($udom,$unam,$ext) = @_;
 3497:     my $home=&homeserver($unam,$udom);
 3498:     if (defined($env{'request.course.id'})) {
 3499:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
 3500:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
 3501:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
 3502:             } else {
 3503:                 my ($result,$perm_reqd)=
 3504: 		    &auto_photo_permission($unam,$udom);
 3505:                 if ($result eq 'ok') {
 3506:                     if (!($perm_reqd eq 'yes')) {
 3507:                         return(&retrievestudentphoto($udom,$unam,$ext));
 3508:                     }
 3509:                 }
 3510:             }
 3511:         }
 3512:     } else {
 3513:         my ($result,$perm_reqd) = 
 3514: 	    &auto_photo_permission($unam,$udom);
 3515:         if ($result eq 'ok') {
 3516:             if (!($perm_reqd eq 'yes')) {
 3517:                 return(&retrievestudentphoto($udom,$unam,$ext));
 3518:             }
 3519:         }
 3520:     }
 3521:     return '/adm/lonKaputt/lonlogo_broken.gif';
 3522: }
 3523: 
 3524: sub retrievestudentphoto {
 3525:     my ($udom,$unam,$ext,$type) = @_;
 3526:     my $home=&homeserver($unam,$udom);
 3527:     my $ret=&reply("studentphoto:$udom:$unam:$ext:$type",$home);
 3528:     if ($ret eq 'ok') {
 3529:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
 3530:         if ($type eq 'thumbnail') {
 3531:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
 3532:         }
 3533:         my $tokenurl=&tokenwrapper($url);
 3534:         return $tokenurl;
 3535:     } else {
 3536:         if ($type eq 'thumbnail') {
 3537:             return '/adm/lonKaputt/genericstudent_tn.gif';
 3538:         } else { 
 3539:             return '/adm/lonKaputt/lonlogo_broken.gif';
 3540:         }
 3541:     }
 3542: }
 3543: 
 3544: # -------------------------------------------------------------------- New chat
 3545: 
 3546: sub chatsend {
 3547:     my ($newentry,$anon,$group)=@_;
 3548:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
 3549:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 3550:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
 3551:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
 3552: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
 3553: 		   &escape($newentry)).':'.$group,$chome);
 3554: }
 3555: 
 3556: # ------------------------------------------ Find current version of a resource
 3557: 
 3558: sub getversion {
 3559:     my $fname=&clutter(shift);
 3560:     unless ($fname=~m{^(/adm/wrapper|)/res/}) { return -1; }
 3561:     return &currentversion(&filelocation('',$fname));
 3562: }
 3563: 
 3564: sub currentversion {
 3565:     my $fname=shift;
 3566:     my $author=$fname;
 3567:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 3568:     my ($udom,$uname)=split(/\//,$author);
 3569:     my $home=&homeserver($uname,$udom);
 3570:     if ($home eq 'no_host') { 
 3571:         return -1; 
 3572:     }
 3573:     my $answer=&reply("currentversion:$fname",$home);
 3574:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
 3575: 	return -1;
 3576:     }
 3577:     return $answer;
 3578: }
 3579: 
 3580: #
 3581: # Return special version number of resource if set by override, empty otherwise
 3582: #
 3583: sub usedversion {
 3584:     my $fname=shift;
 3585:     unless ($fname) { $fname=$env{'request.uri'}; }
 3586:     my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
 3587:     if ($urlversion) { return $urlversion; }
 3588:     return '';
 3589: }
 3590: 
 3591: # ----------------------------- Subscribe to a resource, return URL if possible
 3592: 
 3593: sub subscribe {
 3594:     my $fname=shift;
 3595:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
 3596:     $fname=~s/[\n\r]//g;
 3597:     my $author=$fname;
 3598:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 3599:     my ($udom,$uname)=split(/\//,$author);
 3600:     my $home=homeserver($uname,$udom);
 3601:     if ($home eq 'no_host') {
 3602:         return 'not_found';
 3603:     }
 3604:     my $answer=reply("sub:$fname",$home);
 3605:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
 3606: 	$answer.=' by '.$home;
 3607:     }
 3608:     return $answer;
 3609: }
 3610:     
 3611: # -------------------------------------------------------------- Replicate file
 3612: 
 3613: sub repcopy {
 3614:     my $filename=shift;
 3615:     $filename=~s/\/+/\//g;
 3616:     my $londocroot = $perlvar{'lonDocRoot'};
 3617:     if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
 3618:     if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
 3619:     if ($filename=~m{^\Q$londocroot/userfiles/\E} or
 3620: 	$filename=~m{^/*(uploaded|editupload)/}) {
 3621: 	return &repcopy_userfile($filename);
 3622:     }
 3623:     $filename=~s/[\n\r]//g;
 3624:     my $transname="$filename.in.transfer";
 3625: # FIXME: this should flock
 3626:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
 3627:     my $remoteurl=subscribe($filename);
 3628:     if ($remoteurl =~ /^con_lost by/) {
 3629: 	   &logthis("Subscribe returned $remoteurl: $filename");
 3630:            return 'unavailable';
 3631:     } elsif ($remoteurl eq 'not_found') {
 3632: 	   #&logthis("Subscribe returned not_found: $filename");
 3633: 	   return 'not_found';
 3634:     } elsif ($remoteurl =~ /^rejected by/) {
 3635: 	   &logthis("Subscribe returned $remoteurl: $filename");
 3636:            return 'forbidden';
 3637:     } elsif ($remoteurl eq 'directory') {
 3638:            return 'ok';
 3639:     } else {
 3640:         my $author=$filename;
 3641:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 3642:         my ($udom,$uname)=split(/\//,$author);
 3643:         my $home=homeserver($uname,$udom);
 3644:         unless ($home eq $perlvar{'lonHostID'}) {
 3645:            my @parts=split(/\//,$filename);
 3646:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
 3647:            if ($path ne "$londocroot/res") {
 3648:                &logthis("Malconfiguration for replication: $filename");
 3649: 	       return 'bad_request';
 3650:            }
 3651:            my $count;
 3652:            for ($count=5;$count<$#parts;$count++) {
 3653:                $path.="/$parts[$count]";
 3654:                if ((-e $path)!=1) {
 3655: 		   mkdir($path,0777);
 3656:                }
 3657:            }
 3658:            my $request=new HTTP::Request('GET',"$remoteurl");
 3659:            my $response;
 3660:            if ($remoteurl =~ m{/raw/}) {
 3661:                $response=&LONCAPA::LWPReq::makerequest($home,$request,$transname,\%perlvar,'',0,1);
 3662:            } else {
 3663:                $response=&LONCAPA::LWPReq::makerequest($home,$request,$transname,\%perlvar,'',1);
 3664:            }
 3665:            if ($response->is_error()) {
 3666: 	       unlink($transname);
 3667:                my $message=$response->status_line;
 3668:                &logthis("<font color=\"blue\">WARNING:"
 3669:                        ." LWP get: $message: $filename</font>");
 3670:                return 'unavailable';
 3671:            } else {
 3672: 	       if ($remoteurl!~/\.meta$/) {
 3673:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
 3674:                   my $mresponse;
 3675:                   if ($remoteurl =~ m{/raw/}) {
 3676:                       $mresponse = &LONCAPA::LWPReq::makerequest($home,$mrequest,$filename.'.meta',\%perlvar,'',0,1);
 3677:                   } else {
 3678:                       $mresponse = &LONCAPA::LWPReq::makerequest($home,$mrequest,$filename.'.meta',\%perlvar,'',1);
 3679:                   }
 3680:                   if ($mresponse->is_error()) {
 3681: 		      unlink($filename.'.meta');
 3682:                       &logthis(
 3683:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
 3684:                   }
 3685: 	       }
 3686:                rename($transname,$filename);
 3687:                return 'ok';
 3688:            }
 3689:        }
 3690:     }
 3691: }
 3692: 
 3693: # ------------------------------------------------- Unsubscribe from a resource
 3694: 
 3695: sub unsubscribe {
 3696:     my ($fname) = @_;
 3697:     my $answer;
 3698:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return $answer; }
 3699:     $fname=~s/[\n\r]//g;
 3700:     my $author=$fname;
 3701:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 3702:     my ($udom,$uname)=split(/\//,$author);
 3703:     my $home=homeserver($uname,$udom);
 3704:     if ($home eq 'no_host') {
 3705:         $answer = 'no_host';
 3706:     } elsif (grep { $_ eq $home } &current_machine_ids()) {
 3707:         $answer = 'home';
 3708:     } else {
 3709:         my $defdom = $perlvar{'lonDefDomain'};
 3710:         if (&will_trust('content',$defdom,$udom)) {
 3711:             $answer = reply("unsub:$fname",$home);
 3712:         } else {
 3713:             $answer = 'untrusted';
 3714:         }
 3715:     }
 3716:     return $answer;
 3717: }
 3718: 
 3719: # ------------------------------------------------ Get server side include body
 3720: sub ssi_body {
 3721:     my ($filelink,%form)=@_;
 3722:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
 3723:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
 3724:     }
 3725:     my $output='';
 3726:     my $response;
 3727:     if ($filelink=~/^https?\:/) {
 3728:        ($output,$response)=&externalssi($filelink);
 3729:     } else {
 3730:        $filelink .= $filelink=~/\?/ ? '&' : '?';
 3731:        $filelink .= 'inhibitmenu=yes';
 3732:        ($output,$response)=&ssi($filelink,%form);
 3733:     }
 3734:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
 3735:     $output=~s/^.*?\<body[^\>]*\>//si;
 3736:     $output=~s/\<\/body\s*\>.*?$//si;
 3737:     if (wantarray) {
 3738:         return ($output, $response);
 3739:     } else {
 3740:         return $output;
 3741:     }
 3742: }
 3743: 
 3744: # --------------------------------------------------------- Server Side Include
 3745: 
 3746: sub absolute_url {
 3747:     my ($host_name,$unalias,$keep_proto) = @_;
 3748:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
 3749:     if ($host_name eq '') {
 3750: 	$host_name = $ENV{'SERVER_NAME'};
 3751:     }
 3752:     if ($unalias) {
 3753:         my $alias = &get_proxy_alias();
 3754:         if ($alias eq $host_name) {
 3755:             my $lonhost = $perlvar{'lonHostID'};
 3756:             my $hostname = &hostname($lonhost);
 3757:             my $lcproto; 
 3758:             if (($keep_proto) || ($hostname eq '')) {
 3759:                 $lcproto = $protocol;
 3760:             } else {
 3761:                 $lcproto = $protocol{$lonhost};
 3762:                 $lcproto = 'http' if ($lcproto ne 'https');
 3763:                 $lcproto .= '://';
 3764:             }
 3765:             unless ($hostname eq '') {
 3766:                 return $lcproto.$hostname;
 3767:             }
 3768:         }
 3769:     }
 3770:     return $protocol.$host_name;
 3771: }
 3772: 
 3773: #
 3774: #   Server side include.
 3775: # Parameters:
 3776: #  fn     Possibly encrypted resource name/id.
 3777: #  form   Hash that describes how the rendering should be done
 3778: #         and other things.
 3779: # Returns:
 3780: #   Scalar context: The content of the response.
 3781: #   Array context:  2 element list of the content and the full response object.
 3782: #     
 3783: sub ssi {
 3784: 
 3785:     my ($fn,%form)=@_;
 3786:     my ($host,$request,$response);
 3787:     $host = &absolute_url('',1);
 3788: 
 3789:     $form{'no_update_last_known'}=1;
 3790:     &Apache::lonenc::check_encrypt(\$fn);
 3791:     if (%form) {
 3792:       $request=new HTTP::Request('POST',$host.$fn);
 3793:       $request->content(join('&',map { 
 3794:             my $name = escape($_);
 3795:             "$name=" . ( ref($form{$_}) eq 'ARRAY' 
 3796:             ? join("&$name=", map {escape($_) } @{$form{$_}}) 
 3797:             : &escape($form{$_}) );    
 3798:         } keys(%form)));
 3799:     } else {
 3800:       $request=new HTTP::Request('GET',$host.$fn);
 3801:     }
 3802: 
 3803:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
 3804:     my $lonhost = $perlvar{'lonHostID'};
 3805:     my $islocal;
 3806:     if (($env{'request.course.id'}) &&
 3807:         ($form{'grade_courseid'} eq $env{'request.course.id'}) &&
 3808:         ($form{'grade_username'} ne '') && ($form{'grade_domain'} ne '') &&
 3809:         ($form{'grade_symb'} ne '') &&
 3810:         (&allowed('mgr',$env{'request.course.id'}.
 3811:                         ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:'')))) {
 3812:         $islocal = 1;
 3813:     }
 3814:     $response= &LONCAPA::LWPReq::makerequest($lonhost,$request,'',\%perlvar,
 3815:                                              '','','',$islocal);
 3816: 
 3817:     if (wantarray) {
 3818: 	return ($response->content, $response);
 3819:     } else {
 3820: 	return $response->content;
 3821:     }
 3822: }
 3823: 
 3824: sub externalssi {
 3825:     my ($url)=@_;
 3826:     my $request=new HTTP::Request('GET',$url);
 3827:     my $response = &LONCAPA::LWPReq::makerequest('',$request,'',\%perlvar);
 3828:     if (wantarray) {
 3829:         return ($response->content, $response);
 3830:     } else {
 3831:         return $response->content;
 3832:     }
 3833: }
 3834: 
 3835: 
 3836: # If the local copy of a replicated resource is outdated, trigger a  
 3837: # connection from the homeserver to flush the delayed queue. If no update 
 3838: # happens, remove local copies of outdated resource (and corresponding
 3839: # metadata file).
 3840: 
 3841: sub remove_stale_resfile {
 3842:     my ($url) = @_;
 3843:     my $removed;
 3844:     if ($url=~m{^/res/($match_domain)/($match_username)/}) {
 3845:         my $audom = $1;
 3846:         my $auname = $2;
 3847:         unless (($url =~ /\.\d+\.\w+$/) || ($url =~ m{^/res/lib/templates/})) {
 3848:             my $homeserver = &homeserver($auname,$audom);
 3849:             unless (($homeserver eq 'no_host') ||
 3850:                     (grep { $_ eq $homeserver } &current_machine_ids())) {
 3851:                 my $fname = &filelocation('',$url);
 3852:                 if (-e $fname) {
 3853:                     my $hostname = &hostname($homeserver);
 3854:                     if ($hostname) {
 3855:                         my $protocol = $protocol{$homeserver};
 3856:                         $protocol = 'http' if ($protocol ne 'https');
 3857:                         my $uri = &declutter($url);
 3858:                         my $request=new HTTP::Request('HEAD',$protocol.'://'.$hostname.'/raw/'.$uri);
 3859:                         my $response = &LONCAPA::LWPReq::makerequest($homeserver,$request,'',\%perlvar,5,0,1);
 3860:                         if ($response->is_success()) {
 3861:                             my $remmodtime = &HTTP::Date::str2time( $response->header('Last-modified') );
 3862:                             my $locmodtime = (stat($fname))[9];
 3863:                             if ($locmodtime < $remmodtime) {
 3864:                                 my $stale;
 3865:                                 my $answer = &reply('pong',$homeserver);
 3866:                                 if ($answer eq $homeserver.':'.$perlvar{'lonHostID'}) {
 3867:                                     sleep(0.2);
 3868:                                     $locmodtime = (stat($fname))[9];
 3869:                                     if ($locmodtime < $remmodtime) {
 3870:                                         my $posstransfer = $fname.'.in.transfer';
 3871:                                         if ((-e $posstransfer) && ($remmodtime < (stat($posstransfer))[9])) {
 3872:                                             $removed = 1;
 3873:                                         } else {
 3874:                                             $stale = 1;
 3875:                                         }
 3876:                                     } else {
 3877:                                         $removed = 1;
 3878:                                     }
 3879:                                 } else {
 3880:                                     $stale = 1;
 3881:                                 }
 3882:                                 if ($stale) {
 3883:                                     if (unlink($fname)) {
 3884:                                         if ($uri!~/\.meta$/) {
 3885:                                             if (-e $fname.'.meta') {
 3886:                                                 unlink($fname.'.meta');
 3887:                                             }
 3888:                                         }
 3889:                                         my $unsubresult = &unsubscribe($fname);
 3890:                                         unless ($unsubresult eq 'ok') {
 3891:                                             &logthis("no unsub of $fname from $homeserver, reason: $unsubresult");
 3892:                                         }
 3893:                                         $removed = 1;
 3894:                                     }
 3895:                                 }
 3896:                             }
 3897:                         }
 3898:                     }
 3899:                 }
 3900:             }
 3901:         }
 3902:     }
 3903:     return $removed;
 3904: }
 3905: 
 3906: # -------------------------------- Allow a /uploaded/ URI to be vouched for
 3907: 
 3908: sub allowuploaded {
 3909:     my ($srcurl,$url)=@_;
 3910:     $url=&clutter(&declutter($url));
 3911:     my $dir=$url;
 3912:     $dir=~s/\/[^\/]+$//;
 3913:     my %httpref=();
 3914:     my $httpurl=&hreflocation('',$url);
 3915:     $httpref{'httpref.'.$httpurl}=$srcurl;
 3916:     &Apache::lonnet::appenv(\%httpref);
 3917: }
 3918: 
 3919: #
 3920: # Determine if the current user should be able to edit a particular resource,
 3921: # when viewing in course context.
 3922: # (a) When viewing resource used to determine if "Edit" item is included in 
 3923: #     Functions.
 3924: # (b) When displaying folder contents in course editor, used to determine if
 3925: #     "Edit" link will be displayed alongside resource.
 3926: #
 3927: #  input: six args -- filename (decluttered), course number, course domain,
 3928: #                   url, symb (if registered) and group (if this is a group
 3929: #                   item -- e.g., bulletin board, group page etc.).
 3930: #  output: array of five scalars -- 
 3931: #          $cfile -- url for file editing if editable on current server
 3932: #          $home -- homeserver of resource (i.e., for author if published,
 3933: #                                           or course if uploaded.).
 3934: #          $switchserver --  1 if server switch will be needed.
 3935: #          $forceedit -- 1 if icon/link should be to go to edit mode 
 3936: #          $forceview -- 1 if icon/link should be to go to view mode
 3937: #
 3938: 
 3939: sub can_edit_resource {
 3940:     my ($file,$cnum,$cdom,$resurl,$symb,$group) = @_;
 3941:     my ($cfile,$home,$switchserver,$forceedit,$forceview,$uploaded,$incourse);
 3942: #
 3943: # For aboutme pages user can only edit his/her own.
 3944: #
 3945:     if ($resurl =~ m{^/?adm/($match_domain)/($match_username)/aboutme$}) {
 3946:         my ($sdom,$sname) = ($1,$2);
 3947:         if (($sdom eq $env{'user.domain'}) && ($sname eq $env{'user.name'})) {
 3948:             $home = $env{'user.home'};
 3949:             $cfile = $resurl;
 3950:             if ($env{'form.forceedit'}) {
 3951:                 $forceview = 1;
 3952:             } else {
 3953:                 $forceedit = 1;
 3954:             }
 3955:             return ($cfile,$home,$switchserver,$forceedit,$forceview);
 3956:         } else {
 3957:             return;
 3958:         }
 3959:     }
 3960: 
 3961: #
 3962: # For /adm/viewcoauthors can only edit if author or co-author who is manager.
 3963: #
 3964: 
 3965:     if (($resurl eq '/adm/viewcoauthors') && ($cnum ne '') && ($cdom ne '')) {
 3966:         if (((&allowed('cca',"$cdom/$cnum")) ||
 3967:              (&allowed('caa',"$cdom/$cnum"))) ||
 3968:              ((&allowed('vca',"$cdom/$cnum") ||
 3969:                &allowed('vaa',"$cdom/$cnum")) &&
 3970:               ($env{"environment.internal.manager./$cdom/$cnum"}))) {
 3971:             $home = $env{'user.home'};
 3972:             $cfile = $resurl;
 3973:             if ($env{'form.forceedit'}) {
 3974:                 $forceview = 1;
 3975:             } else {
 3976:                 $forceedit = 1;
 3977:             }
 3978:             return ($cfile,$home,$switchserver,$forceedit,$forceview);
 3979:         } else {
 3980:             return;
 3981:         }
 3982:     }
 3983: 
 3984:     if ($env{'request.course.id'}) {
 3985:         my $crsedit = &allowed('mdc',$env{'request.course.id'});
 3986:         if ($group ne '') {
 3987: # if this is a group homepage or group bulletin board, check group privs
 3988:             my $allowed = 0;
 3989:             if ($resurl =~ m{^/?adm/$cdom/$cnum/$group/smppg$}) {
 3990:                 if ((&allowed('mdg',$env{'request.course.id'}.
 3991:                               ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
 3992:                         (&allowed('mgh',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
 3993:                     $allowed = 1;
 3994:                 }
 3995:             } elsif ($resurl =~ m{^/?adm/$cdom/$cnum/\d+/bulletinboard$}) {
 3996:                 if ((&allowed('mdg',$env{'request.course.id'}.($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
 3997:                         (&allowed('cgb',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
 3998:                     $allowed = 1;
 3999:                 }
 4000:             }
 4001:             if ($allowed) {
 4002:                 $home=&homeserver($cnum,$cdom);
 4003:                 if ($env{'form.forceedit'}) {
 4004:                     $forceview = 1;
 4005:                 } else {
 4006:                     $forceedit = 1;
 4007:                 }
 4008:                 $cfile = $resurl;
 4009:             } else {
 4010:                 return;
 4011:             }
 4012:         } else {
 4013:             if ($resurl =~ m{^/?adm/viewclasslist$}) {
 4014:                 unless (&allowed('opa',$env{'request.course.id'})) {
 4015:                     return;
 4016:                 }
 4017:             } elsif (!$crsedit) {
 4018:                 if ($env{'request.role'} =~ m{^st\./$cdom/$cnum}) {
 4019: #
 4020: # No edit allowed where CC has switched to student role.
 4021: #
 4022:                     return;
 4023:                 } elsif (($resurl !~ m{^/res/$match_domain/$match_username/}) ||
 4024:                          ($resurl =~ m{^/res/lib/templates/})) {
 4025:                     return;
 4026:                 }
 4027:             }
 4028:         }
 4029:     }
 4030: 
 4031:     if ($file ne '') {
 4032:         if (($cnum =~ /$match_courseid/) && ($cdom =~ /$match_domain/)) {
 4033:             if (&is_course_upload($file,$cnum,$cdom)) {
 4034:                 $uploaded = 1;
 4035:                 $incourse = 1;
 4036:                 if ($file =~/\.(htm|html|css|js|txt)$/) {
 4037:                     $cfile = &hreflocation('',$file);
 4038:                     if ($env{'form.forceedit'}) {
 4039:                         $forceview = 1;
 4040:                     } else {
 4041:                         $forceedit = 1;
 4042:                     }
 4043:                 }
 4044:             } elsif ($resurl =~ m{^/public/$cdom/$cnum/syllabus}) {
 4045:                 $incourse = 1;
 4046:                 if ($env{'form.forceedit'}) {
 4047:                     $forceview = 1;
 4048:                 } else {
 4049:                     $forceedit = 1;
 4050:                 }
 4051:                 $cfile = $resurl;
 4052:             } elsif (($resurl ne '') && (&is_on_map($resurl))) {
 4053:                 if ($resurl =~ m{^/adm/$match_domain/$match_username/\d+/smppg|bulletinboard$}) {
 4054:                     $incourse = 1;
 4055:                     if ($env{'form.forceedit'}) {
 4056:                         $forceview = 1;
 4057:                     } else {
 4058:                         $forceedit = 1;
 4059:                     }
 4060:                     $cfile = $resurl;
 4061:                 } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem') {
 4062:                     $incourse = 1;
 4063:                     $cfile = $resurl.'/smpedit';
 4064:                 } elsif ($resurl =~ m{^/adm/wrapper/ext/}) {
 4065:                     $incourse = 1;
 4066:                     if ($env{'form.forceedit'}) {
 4067:                         $forceview = 1;
 4068:                     } else {
 4069:                         $forceedit = 1;
 4070:                     }
 4071:                     $cfile = $resurl;
 4072:                 } elsif (($resurl =~ m{^/ext/}) && ($symb ne '')) {
 4073:                     my ($map,$id,$res) = &decode_symb($symb);
 4074:                     if ($map =~ /\.page$/) {
 4075:                         $incourse = 1;
 4076:                         if ($env{'form.forceedit'}) {
 4077:                             $forceview = 1;
 4078:                             $cfile = $map;
 4079:                         } else {
 4080:                             $forceedit = 1;
 4081:                             $cfile =  '/adm/wrapper'.$resurl;
 4082:                         }
 4083:                     }
 4084:                 } elsif ($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/ext\.tool$}) {
 4085:                     $incourse = 1;
 4086:                     if ($env{'form.forceedit'}) {
 4087:                         $forceview = 1;
 4088:                     } else {
 4089:                         $forceedit = 1;
 4090:                     }
 4091:                     $cfile = $resurl;
 4092:                 } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
 4093:                     $incourse = 1;
 4094:                     if ($env{'form.forceedit'}) {
 4095:                         $forceview = 1;
 4096:                     } else {
 4097:                         $forceedit = 1;
 4098:                     }
 4099:                     $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
 4100:                 }
 4101:             } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem/smpedit') {
 4102:                 my $template = '/res/lib/templates/simpleproblem.problem';
 4103:                 if (&is_on_map($template)) { 
 4104:                     $incourse = 1;
 4105:                     $forceview = 1;
 4106:                     $cfile = $template;
 4107:                 }
 4108:             } elsif (($resurl =~ m{^/adm/wrapper/ext/}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
 4109:                 $incourse = 1;
 4110:                 if ($env{'form.forceedit'}) {
 4111:                     $forceview = 1;
 4112:                 } else {
 4113:                     $forceedit = 1;
 4114:                 }
 4115:                 $cfile = $resurl;
 4116:             } elsif (($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/ext\.tool$}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
 4117:                 $incourse = 1;
 4118:                 if ($env{'form.forceedit'}) {
 4119:                     $forceview = 1;
 4120:                 } else {
 4121:                     $forceedit = 1;
 4122:                 }
 4123:                 $cfile = $resurl;
 4124:             } elsif (($resurl eq '/adm/extresedit') && ($symb || $env{'form.folderpath'})) {
 4125:                 $incourse = 1;
 4126:                 $forceview = 1;
 4127:                 if ($symb) {
 4128:                     my ($map,$id,$res)=&decode_symb($symb);
 4129:                     $env{'request.symb'} = $symb;
 4130:                     $cfile = &clutter($res);
 4131:                 } else {
 4132:                     $cfile = $env{'form.suppurl'};
 4133:                     my $escfile = &unescape($cfile);
 4134:                     if ($escfile =~ m{^/adm/$cdom/$cnum/\d+/ext\.tool$}) {
 4135:                         $cfile = '/adm/wrapper'.$escfile;
 4136:                     } else {
 4137:                         $escfile =~ s{^http://}{};
 4138:                         $cfile = &escape("/adm/wrapper/ext/$escfile");
 4139:                     }
 4140:                 }
 4141:             } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
 4142:                 if ($env{'form.forceedit'}) {
 4143:                     $forceview = 1;
 4144:                 } else {
 4145:                     $forceedit = 1;
 4146:                 }
 4147:                 $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
 4148:             }
 4149:         }
 4150:         if ($uploaded || $incourse) {
 4151:             $home=&homeserver($cnum,$cdom);
 4152:         } elsif ($file !~ m{/$}) {
 4153:             $file=~s{^(priv/$match_domain/$match_username)}{/$1};
 4154:             $file=~s{^($match_domain/$match_username)}{/priv/$1};
 4155:             # Check that the user has permission to edit this resource
 4156:             my $setpriv = 1;
 4157:             my ($cfuname,$cfudom)=&constructaccess($file,$setpriv);
 4158:             if (defined($cfudom)) {
 4159:                 $home=&homeserver($cfuname,$cfudom);
 4160:                 $cfile=$file;
 4161:             }
 4162:         }
 4163:         if (($cfile ne '') && (!$incourse || $uploaded) && 
 4164:             (($home ne '') && ($home ne 'no_host'))) {
 4165:             my @ids=&current_machine_ids();
 4166:             unless (grep(/^\Q$home\E$/,@ids)) {
 4167:                 $switchserver=1;
 4168:             }
 4169:         }
 4170:     }
 4171:     return ($cfile,$home,$switchserver,$forceedit,$forceview);
 4172: }
 4173: 
 4174: sub is_course_upload {
 4175:     my ($file,$cnum,$cdom) = @_;
 4176:     my $uploadpath = &LONCAPA::propath($cdom,$cnum);
 4177:     $uploadpath =~ s{^\/}{};
 4178:     if (($file =~ m{^\Q$uploadpath\E/userfiles/(docs|supplemental)/}) ||
 4179:         ($file =~ m{^userfiles/\Q$cdom\E/\Q$cnum\E/(docs|supplemental)/})) {
 4180:         return 1;
 4181:     }
 4182:     return;
 4183: }
 4184: 
 4185: sub in_course {
 4186:     my ($udom,$uname,$cdom,$cnum,$type,$hideprivileged) = @_;
 4187:     if ($hideprivileged) {
 4188:         my $skipuser;
 4189:         my %coursehash = &coursedescription($cdom.'_'.$cnum);
 4190:         my @possdoms = ($cdom);  
 4191:         if ($coursehash{'checkforpriv'}) { 
 4192:             push(@possdoms,split(/,/,$coursehash{'checkforpriv'})); 
 4193:         }
 4194:         if (&privileged($uname,$udom,\@possdoms)) {
 4195:             $skipuser = 1;
 4196:             if ($coursehash{'nothideprivileged'}) {
 4197:                 foreach my $item (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 4198:                     my $user;
 4199:                     if ($item =~ /:/) {
 4200:                         $user = $item;
 4201:                     } else {
 4202:                         $user = join(':',split(/[\@]/,$item));
 4203:                     }
 4204:                     if ($user eq $uname.':'.$udom) {
 4205:                         undef($skipuser);
 4206:                         last;
 4207:                     }
 4208:                 }
 4209:             }
 4210:             if ($skipuser) {
 4211:                 return 0;
 4212:             }
 4213:         }
 4214:     }
 4215:     $type ||= 'any';
 4216:     if (!defined($cdom) || !defined($cnum)) {
 4217:         my $cid  = $env{'request.course.id'};
 4218:         $cdom = $env{'course.'.$cid.'.domain'};
 4219:         $cnum = $env{'course.'.$cid.'.num'};
 4220:     }
 4221:     my $typesref;
 4222:     if (($type eq 'any') || ($type eq 'all')) {
 4223:         $typesref = ['active','previous','future'];
 4224:     } elsif ($type eq 'previous' || $type eq 'future') {
 4225:         $typesref = [$type];
 4226:     }
 4227:     my %roles = &get_my_roles($uname,$udom,'userroles',
 4228:                               $typesref,undef,[$cdom]);
 4229:     my ($tmp) = keys(%roles);
 4230:     return 0 if ($tmp =~ /^(con_lost|error|no_such_host)/i);
 4231:     my @course_roles = grep(/^\Q$cnum\E:\Q$cdom\E:/, keys(%roles));
 4232:     if (@course_roles > 0) {
 4233:         return 1;
 4234:     }
 4235:     return 0;
 4236: }
 4237: 
 4238: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
 4239: # input: action, courseID, current domain, intended
 4240: #        path to file, source of file, instruction to parse file for objects,
 4241: #        ref to hash for embedded objects,
 4242: #        ref to hash for codebase of java objects.
 4243: #        reference to scalar to accommodate mime type determined
 4244: #          from File::MMagic if $parser = parse.
 4245: #
 4246: # output: url to file (if action was uploaddoc), 
 4247: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
 4248: #
 4249: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
 4250: # course.
 4251: #
 4252: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 4253: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
 4254: #          course's home server.
 4255: #
 4256: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
 4257: #          be copied from $source (current location) to 
 4258: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 4259: #         and will then be copied to
 4260: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
 4261: #         course's home server.
 4262: #
 4263: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 4264: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
 4265: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 4266: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
 4267: #         in course's home server.
 4268: #
 4269: 
 4270: sub process_coursefile {
 4271:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
 4272:         $mimetype)=@_;
 4273:     my $fetchresult;
 4274:     my $home=&homeserver($docuname,$docudom);
 4275:     if ($action eq 'propagate') {
 4276:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 4277: 			     $home);
 4278:     } else {
 4279:         my $fpath = '';
 4280:         my $fname = $file;
 4281:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 4282:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 4283:         my $filepath = &build_filepath($fpath);
 4284:         if ($action eq 'copy') {
 4285:             if ($source eq '') {
 4286:                 $fetchresult = 'no source file';
 4287:                 return $fetchresult;
 4288:             } else {
 4289:                 my $destination = $filepath.'/'.$fname;
 4290:                 rename($source,$destination);
 4291:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 4292:                                  $home);
 4293:             }
 4294:         } elsif ($action eq 'uploaddoc') {
 4295:             open(my $fh,'>',$filepath.'/'.$fname);
 4296:             print $fh $env{'form.'.$source};
 4297:             close($fh);
 4298:             if ($parser eq 'parse') {
 4299:                 my $mm = new File::MMagic;
 4300:                 my $type = $mm->checktype_filename($filepath.'/'.$fname);
 4301:                 if ($type eq 'text/html') {
 4302:                     my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
 4303:                     unless ($parse_result eq 'ok') {
 4304:                         &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
 4305:                     }
 4306:                 }
 4307:                 if (ref($mimetype)) {
 4308:                     $$mimetype = $type;
 4309:                 } 
 4310:             }
 4311:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 4312:                                  $home);
 4313:             if ($fetchresult eq 'ok') {
 4314:                 return '/uploaded/'.$fpath.'/'.$fname;
 4315:             } else {
 4316:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 4317:                         ' to host '.$home.': '.$fetchresult);
 4318:                 return '/adm/notfound.html';
 4319:             }
 4320:         }
 4321:     }
 4322:     unless ( $fetchresult eq 'ok') {
 4323:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 4324:              ' to host '.$home.': '.$fetchresult);
 4325:     }
 4326:     return $fetchresult;
 4327: }
 4328: 
 4329: sub build_filepath {
 4330:     my ($fpath) = @_;
 4331:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
 4332:     unless ($fpath eq '') {
 4333:         my @parts=split('/',$fpath);
 4334:         foreach my $part (@parts) {
 4335:             $filepath.= '/'.$part;
 4336:             if ((-e $filepath)!=1) {
 4337:                 mkdir($filepath,0777);
 4338:             }
 4339:         }
 4340:     }
 4341:     return $filepath;
 4342: }
 4343: 
 4344: sub store_edited_file {
 4345:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
 4346:     my $file = $primary_url;
 4347:     $file =~ s#^/uploaded/$docudom/$docuname/##;
 4348:     my $fpath = '';
 4349:     my $fname = $file;
 4350:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 4351:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 4352:     my $filepath = &build_filepath($fpath);
 4353:     open(my $fh,'>',$filepath.'/'.$fname);
 4354:     print $fh $content;
 4355:     close($fh);
 4356:     my $home=&homeserver($docuname,$docudom);
 4357:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 4358: 			  $home);
 4359:     if ($$fetchresult eq 'ok') {
 4360:         return '/uploaded/'.$fpath.'/'.$fname;
 4361:     } else {
 4362:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 4363: 		 ' to host '.$home.': '.$$fetchresult);
 4364:         return '/adm/notfound.html';
 4365:     }
 4366: }
 4367: 
 4368: sub clean_filename {
 4369:     my ($fname,$args)=@_;
 4370: # Replace Windows backslashes by forward slashes
 4371:     $fname=~s/\\/\//g;
 4372:     if (!$args->{'keep_path'}) {
 4373:         # Get rid of everything but the actual filename
 4374: 	$fname=~s/^.*\/([^\/]+)$/$1/;
 4375:     }
 4376: # Replace spaces by underscores
 4377:     $fname=~s/\s+/\_/g;
 4378: # Transliterate non-ascii text to ascii
 4379:     my $lang = &Apache::lonlocal::current_language();
 4380:     $fname = &LONCAPA::transliterate::fname_to_ascii($fname,$lang);
 4381: # Replace all other weird characters by nothing
 4382:     $fname=~s{[^/\w\.\-]}{}g;
 4383: # Replace all .\d. sequences with _\d. so they no longer look like version
 4384: # numbers
 4385:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
 4386: # Replace three or more adjacent underscores with one for consistency 
 4387: # with loncfile::filename_check() so complete url can be extracted by
 4388: # lonnet::decode_symb()
 4389:     $fname=~s/_{3,}/_/g;
 4390:     return $fname;
 4391: }
 4392: 
 4393: # This Function checks if an Image's dimensions exceed either $resizewidth (width) 
 4394: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an 
 4395: # image with the same aspect ratio as the original, but with dimensions which do 
 4396: # not exceed $resizewidth and $resizeheight.
 4397:  
 4398: sub resizeImage {
 4399:     my ($img_path,$resizewidth,$resizeheight) = @_;
 4400:     my $ima = Image::Magick->new;
 4401:     my $resized;
 4402:     if (-e $img_path) {
 4403:         $ima->Read($img_path);
 4404:         if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
 4405:             my $width = $ima->Get('width');
 4406:             my $height = $ima->Get('height');
 4407:             if ($width > $resizewidth) {
 4408: 	        my $factor = $width/$resizewidth;
 4409:                 my $newheight = $height/$factor;
 4410:                 $ima->Scale(width=>$resizewidth,height=>$newheight);
 4411:                 $resized = 1;
 4412:             }
 4413:         }
 4414:         if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
 4415:             my $width = $ima->Get('width');
 4416:             my $height = $ima->Get('height');
 4417:             if ($height > $resizeheight) {
 4418:                 my $factor = $height/$resizeheight;
 4419:                 my $newwidth = $width/$factor;
 4420:                 $ima->Scale(width=>$newwidth,height=>$resizeheight);
 4421:                 $resized = 1;
 4422:             }
 4423:         }
 4424:         if ($resized) {
 4425:             $ima->Write($img_path);
 4426:         }
 4427:     }
 4428:     return;
 4429: }
 4430: 
 4431: # --------------- Take an uploaded file and put it into the userfiles directory
 4432: # input: $formname - the contents of the file are in $env{"form.$formname"}
 4433: #                    the desired filename is in $env{"form.$formname.filename"}
 4434: #        $context - possible values: coursedoc, existingfile, overwrite, 
 4435: #                                    canceloverwrite, scantron, toollogo  or ''.
 4436: #                   if 'coursedoc': upload to the current course
 4437: #                   if 'existingfile': write file to tmp/overwrites directory 
 4438: #                   if 'canceloverwrite': delete file written to tmp/overwrites directory
 4439: #                   $context is passed as argument to &finishuserfileupload
 4440: #        $subdir - directory in userfile to store the file into
 4441: #        $parser - instruction to parse file for objects ($parser = parse) or
 4442: #                  if context is 'scantron', $parser is hashref of csv column mapping
 4443: #                  (e.g.,{ PaperID => 0, LastName => 1, FirstName => 2, ID => 3, 
 4444: #                          Section => 4, CODE => 5, FirstQuestion => 9 }).
 4445: #        $allfiles - reference to hash for embedded objects
 4446: #        $codebase - reference to hash for codebase of java objects
 4447: #        $destuname - username for permanent storage of uploaded file
 4448: #        $destudom - domain for permanaent storage of uploaded file
 4449: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
 4450: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
 4451: #        $resizewidth - width (pixels) to which to resize uploaded image
 4452: #        $resizeheight - height (pixels) to which to resize uploaded image
 4453: #        $mimetype - reference to scalar to accommodate mime type determined
 4454: #                    from File::MMagic.
 4455: # 
 4456: # output: url of file in userspace, or error: <message> 
 4457: #             or /adm/notfound.html if failure to upload occurse
 4458: 
 4459: sub userfileupload {
 4460:     my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
 4461:         $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
 4462:     if (!defined($subdir)) { $subdir='unknown'; }
 4463:     my $fname=$env{'form.'.$formname.'.filename'};
 4464:     $fname=&clean_filename($fname);
 4465:     # See if there is anything left
 4466:     unless ($fname) { return 'error: no uploaded file'; }
 4467:     # If filename now begins with a . prepend unix timestamp _ milliseconds
 4468:     if ($fname =~ /^\./) {
 4469:         my ($s,$usec) = &gettimeofday();
 4470:         while (length($usec) < 6) {
 4471:             $usec = '0'.$usec;
 4472:         }
 4473:         $fname = $s.'_'.substr($usec,0,3).$fname;
 4474:     }
 4475:     # Files uploaded to help request form, or uploaded to "create course" page are handled differently
 4476:     if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
 4477:         (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
 4478:          ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
 4479:         my $now = time;
 4480:         my $filepath;
 4481:         if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
 4482:              $filepath = 'tmp/helprequests/'.$now;
 4483:         } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
 4484:              $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
 4485:                          '_'.$env{'user.domain'}.'/pending';
 4486:         } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
 4487:             my ($docuname,$docudom);
 4488:             if ($destudom =~ /^$match_domain$/) {
 4489:                 $docudom = $destudom;
 4490:             } else {
 4491:                 $docudom = $env{'user.domain'};
 4492:             }
 4493:             if ($destuname =~ /^$match_username$/) {
 4494:                 $docuname = $destuname;
 4495:             } else {
 4496:                 $docuname = $env{'user.name'};
 4497:             }
 4498:             if (exists($env{'form.group'})) {
 4499:                 $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 4500:                 $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 4501:             }
 4502:             $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
 4503:             if ($context eq 'canceloverwrite') {
 4504:                 my $tempfile =  $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
 4505:                 if (-e  $tempfile) {
 4506:                     my @info = stat($tempfile);
 4507:                     if ($info[9] eq $env{'form.timestamp'}) {
 4508:                         unlink($tempfile);
 4509:                     }
 4510:                 }
 4511:                 return;
 4512:             }
 4513:         }
 4514:         # Create the directory if not present
 4515:         my @parts=split(/\//,$filepath);
 4516:         my $fullpath = $perlvar{'lonDaemons'};
 4517:         for (my $i=0;$i<@parts;$i++) {
 4518:             $fullpath .= '/'.$parts[$i];
 4519:             if ((-e $fullpath)!=1) {
 4520:                 mkdir($fullpath,0777);
 4521:             }
 4522:         }
 4523:         open(my $fh,'>',$fullpath.'/'.$fname);
 4524:         print $fh $env{'form.'.$formname};
 4525:         close($fh);
 4526:         if ($context eq 'existingfile') {
 4527:             my @info = stat($fullpath.'/'.$fname);
 4528:             return ($fullpath.'/'.$fname,$info[9]);
 4529:         } else {
 4530:             return $fullpath.'/'.$fname;
 4531:         }
 4532:     }
 4533:     if ($subdir eq 'scantron') {
 4534:         $fname = 'scantron_orig_'.$fname;
 4535:     } else {
 4536:         $fname="$subdir/$fname";
 4537:     }
 4538:     if ($context eq 'coursedoc') {
 4539: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 4540: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 4541:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
 4542:             return &finishuserfileupload($docuname,$docudom,
 4543: 					 $formname,$fname,$parser,$allfiles,
 4544: 					 $codebase,$thumbwidth,$thumbheight,
 4545:                                          $resizewidth,$resizeheight,$context,$mimetype);
 4546:         } else {
 4547:             if ($env{'form.folder'}) {
 4548:                 $fname=$env{'form.folder'}.'/'.$fname;
 4549:             }
 4550:             return &process_coursefile('uploaddoc',$docuname,$docudom,
 4551: 				       $fname,$formname,$parser,
 4552: 				       $allfiles,$codebase,$mimetype);
 4553:         }
 4554:     } elsif (defined($destuname)) {
 4555:         my $docuname=$destuname;
 4556:         my $docudom=$destudom;
 4557: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
 4558: 				     $parser,$allfiles,$codebase,
 4559:                                      $thumbwidth,$thumbheight,
 4560:                                      $resizewidth,$resizeheight,$context,$mimetype);
 4561:     } else {
 4562:         my $docuname=$env{'user.name'};
 4563:         my $docudom=$env{'user.domain'};
 4564:         if ((exists($env{'form.group'})) || ($context eq 'syllabus')) {
 4565:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 4566:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 4567:         }
 4568: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
 4569: 				     $parser,$allfiles,$codebase,
 4570:                                      $thumbwidth,$thumbheight,
 4571:                                      $resizewidth,$resizeheight,$context,$mimetype);
 4572:     }
 4573: }
 4574: 
 4575: sub finishuserfileupload {
 4576:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
 4577:         $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
 4578:     my $path=$docudom.'/'.$docuname.'/';
 4579:     my $filepath=$perlvar{'lonDocRoot'};
 4580:   
 4581:     my ($fnamepath,$file,$fetchthumb);
 4582:     $file=$fname;
 4583:     if ($fname=~m|/|) {
 4584:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
 4585: 	$path.=$fnamepath.'/';
 4586:     }
 4587:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
 4588:     my $count;
 4589:     for ($count=4;$count<=$#parts;$count++) {
 4590:         $filepath.="/$parts[$count]";
 4591:         if ((-e $filepath)!=1) {
 4592: 	    mkdir($filepath,0777);
 4593:         }
 4594:     }
 4595: 
 4596: # Save the file
 4597:     {
 4598: 	if (!open(FH,'>',$filepath.'/'.$file)) {
 4599: 	    &logthis('Failed to create '.$filepath.'/'.$file);
 4600: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
 4601: 	    return '/adm/notfound.html';
 4602: 	}
 4603:         if ($context eq 'overwrite') {
 4604:             my $source =  LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
 4605:             my $target = $filepath.'/'.$file;
 4606:             if (-e $source) {
 4607:                 my @info = stat($source);
 4608:                 if ($info[9] eq $env{'form.timestamp'}) {   
 4609:                     unless (&File::Copy::move($source,$target)) {
 4610:                         &logthis('Failed to overwrite '.$filepath.'/'.$file);
 4611:                         return "Moving from $source failed";
 4612:                     }
 4613:                 } else {
 4614:                     return "Temporary file: $source had unexpected date/time for last modification";
 4615:                 }
 4616:             } else {
 4617:                 return "Temporary file: $source missing";
 4618:             }
 4619:         } elsif (!print FH ($env{'form.'.$formname})) {
 4620: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
 4621: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
 4622: 	    return '/adm/notfound.html';
 4623: 	}
 4624: 	close(FH);
 4625:         if ($resizewidth && $resizeheight) {
 4626:             my $mm = new File::MMagic;
 4627:             my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
 4628:             if ($mime_type =~ m{^image/}) {
 4629: 	        &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
 4630:             }  
 4631: 	}
 4632:     }
 4633:     if (($context eq 'coursedoc') || ($parser eq 'parse')) {
 4634:         if (ref($mimetype)) {
 4635:             if ($$mimetype eq '') {
 4636:                 my $mm = new File::MMagic;
 4637:                 my $type = $mm->checktype_filename($filepath.'/'.$file);
 4638:                 $$mimetype = $type;
 4639:             }
 4640:         }
 4641:     }
 4642:     if (($context ne 'scantron') && ($parser eq 'parse')) {
 4643:         if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
 4644:             my $parse_result = &extract_embedded_items($filepath.'/'.$file,
 4645:                                                        $allfiles,$codebase);
 4646:             unless ($parse_result eq 'ok') {
 4647:                 &logthis('Failed to parse '.$filepath.$file.
 4648: 	   	         ' for embedded media: '.$parse_result); 
 4649:             }
 4650:         }
 4651:     } elsif (($context eq 'scantron') && (ref($parser) eq 'HASH')) {
 4652:         my $format = $env{'form.scantron_format'};
 4653:         &bubblesheet_converter($docudom,$filepath.'/'.$file,$parser,$format);
 4654:     }
 4655:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
 4656:         my $input = $filepath.'/'.$file;
 4657:         my $output = $filepath.'/'.'tn-'.$file;
 4658:         my $makethumb; 
 4659:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
 4660:         if ($context eq 'toollogo') {
 4661:             my ($fullwidth,$fullheight) = &check_dimensions($input);
 4662:             if ($fullwidth ne '' && $fullheight ne '') {
 4663:                 if ($fullwidth > $thumbwidth && $fullheight > $thumbheight) {
 4664:                     $makethumb = 1;
 4665:                 }
 4666:             }
 4667:         } else {
 4668:             $makethumb = 1;
 4669:         }
 4670:         if ($makethumb) {
 4671:             my @args = ('convert','-sample',$thumbsize,$input,$output);
 4672:             system({$args[0]} @args);
 4673:             if (-e $filepath.'/'.'tn-'.$file) {
 4674:                 $fetchthumb  = 1; 
 4675:             }
 4676:         }
 4677:     }
 4678:  
 4679: # Notify homeserver to grep it
 4680: #
 4681:     my $docuhome=&homeserver($docuname,$docudom);	
 4682:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
 4683:     if ($fetchresult eq 'ok') {
 4684:         if ($fetchthumb) {
 4685:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
 4686:             if ($thumbresult ne 'ok') {
 4687:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
 4688:                          $docuhome.': '.$thumbresult);
 4689:             }
 4690:         }
 4691: #
 4692: # Return the URL to it
 4693:         return '/uploaded/'.$path.$file;
 4694:     } else {
 4695:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
 4696: 		 ': '.$fetchresult);
 4697:         return '/adm/notfound.html';
 4698:     }
 4699: }
 4700: 
 4701: sub extract_embedded_items {
 4702:     my ($fullpath,$allfiles,$codebase,$content) = @_;
 4703:     my @state = ();
 4704:     my (%lastids,%related,%shockwave,%flashvars);
 4705:     my %javafiles = (
 4706:                       codebase => '',
 4707:                       code => '',
 4708:                       archive => ''
 4709:                     );
 4710:     my %mediafiles = (
 4711:                       src => '',
 4712:                       movie => '',
 4713:                      );
 4714:     my $p;
 4715:     if ($content) {
 4716:         $p = HTML::LCParser->new($content);
 4717:     } else {
 4718:         $p = HTML::LCParser->new($fullpath);
 4719:     }
 4720:     while (my $t=$p->get_token()) {
 4721: 	if ($t->[0] eq 'S') {
 4722: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
 4723: 	    push(@state, $tagname);
 4724:             if (lc($tagname) eq 'allow') {
 4725:                 &add_filetype($allfiles,$attr->{'src'},'src');
 4726:             }
 4727: 	    if (lc($tagname) eq 'img') {
 4728: 		&add_filetype($allfiles,$attr->{'src'},'src');
 4729: 	    }
 4730: 	    if (lc($tagname) eq 'a') {
 4731:                 unless (($attr->{'href'} =~ /^#/) || ($attr->{'href'} eq '')) {
 4732:                     &add_filetype($allfiles,$attr->{'href'},'href');
 4733:                 }
 4734: 	    }
 4735:             if (lc($tagname) eq 'script') {
 4736:                 my $src;
 4737:                 if ($attr->{'archive'} =~ /\.jar$/i) {
 4738:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
 4739:                 } else {
 4740:                     if ($attr->{'src'} ne '') {
 4741:                         $src = $attr->{'src'};
 4742:                         &add_filetype($allfiles,$src,'src');
 4743:                     }
 4744:                 }
 4745:                 my $text = $p->get_trimmed_text();
 4746:                 if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
 4747:                     my @swfargs = split(/,/,$1);
 4748:                     foreach my $item (@swfargs) {
 4749:                         $item =~ s/["']//g;
 4750:                         $item =~ s/^\s+//;
 4751:                         $item =~ s/\s+$//;
 4752:                     }
 4753:                     if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
 4754:                         if (ref($related{$swfargs[0]}) eq 'ARRAY') {
 4755:                             push(@{$related{$swfargs[0]}},$swfargs[2]);
 4756:                         } else {
 4757:                             $related{$swfargs[0]} = [$swfargs[2]];
 4758:                         }
 4759:                     }
 4760:                 }
 4761:             }
 4762:             if (lc($tagname) eq 'link') {
 4763:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
 4764:                     &add_filetype($allfiles,$attr->{'href'},'href');
 4765:                 }
 4766:             }
 4767: 	    if (lc($tagname) eq 'object' ||
 4768: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
 4769: 		foreach my $item (keys(%javafiles)) {
 4770: 		    $javafiles{$item} = '';
 4771: 		}
 4772:                 if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
 4773:                     $lastids{lc($tagname)} = $attr->{'id'};
 4774:                 }
 4775: 	    }
 4776: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
 4777: 		my $name = lc($attr->{'name'});
 4778: 		foreach my $item (keys(%javafiles)) {
 4779: 		    if ($name eq $item) {
 4780: 			$javafiles{$item} = $attr->{'value'};
 4781: 			last;
 4782: 		    }
 4783: 		}
 4784:                 my $pathfrom;
 4785: 		foreach my $item (keys(%mediafiles)) {
 4786: 		    if ($name eq $item) {
 4787:                         $pathfrom = $attr->{'value'};
 4788:                         $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
 4789: 			&add_filetype($allfiles,$pathfrom,$name);
 4790: 			last;
 4791: 		    }
 4792: 		}
 4793:                 if ($name eq 'flashvars') {
 4794:                     $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
 4795:                 }
 4796:                 if ($pathfrom ne '') {
 4797:                     &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
 4798:                                          $pathfrom);
 4799:                 }
 4800: 	    }
 4801: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
 4802: 		foreach my $item (keys(%javafiles)) {
 4803: 		    if ($attr->{$item}) {
 4804: 			$javafiles{$item} = $attr->{$item};
 4805: 			last;
 4806: 		    }
 4807: 		}
 4808: 		foreach my $item (keys(%mediafiles)) {
 4809: 		    if ($attr->{$item}) {
 4810: 			&add_filetype($allfiles,$attr->{$item},$item);
 4811: 			last;
 4812: 		    }
 4813: 		}
 4814:                 if (lc($tagname) eq 'embed') {
 4815:                     if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
 4816:                         &embedded_dependency($allfiles,\%related,$attr->{'name'},
 4817:                                              $attr->{'src'});
 4818:                     }
 4819:                 }
 4820: 	    }
 4821:             if (lc($tagname) eq 'iframe') {
 4822:                 my $src = $attr->{'src'} ;
 4823:                 if (($src ne '') && ($src !~ m{^(/|https?://)})) {
 4824:                     &add_filetype($allfiles,$src,'src');
 4825:                 } elsif ($src =~ m{^/}) {
 4826:                     if ($env{'request.course.id'}) {
 4827:                         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 4828:                         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 4829:                         my $url = &hreflocation('',$fullpath);
 4830:                         if ($url =~ m{^/uploaded/$cdom/$cnum/docs/(\w+/\d+)/}) {
 4831:                             my $relpath = $1;
 4832:                             if ($src =~ m{^/uploaded/$cdom/$cnum/docs/\Q$relpath\E/(.+)$}) {
 4833:                                 &add_filetype($allfiles,$1,'src');
 4834:                             }
 4835:                         }
 4836:                     }
 4837:                 }
 4838:             }
 4839:             if ($t->[4] =~ m{/>$}) {
 4840:                 pop(@state);
 4841:             }
 4842: 	} elsif ($t->[0] eq 'E') {
 4843: 	    my ($tagname) = ($t->[1]);
 4844: 	    if ($javafiles{'codebase'} ne '') {
 4845: 		$javafiles{'codebase'} .= '/';
 4846: 	    }  
 4847: 	    if (lc($tagname) eq 'applet' ||
 4848: 		lc($tagname) eq 'object' ||
 4849: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
 4850: 		) {
 4851: 		foreach my $item (keys(%javafiles)) {
 4852: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
 4853: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
 4854: 			&add_filetype($allfiles,$file,$item);
 4855: 		    }
 4856: 		}
 4857: 	    } 
 4858: 	    pop @state;
 4859: 	}
 4860:     }
 4861:     foreach my $id (sort(keys(%flashvars))) {
 4862:         if ($shockwave{$id} ne '') {
 4863:             my @pairs = split(/\&/,$flashvars{$id});
 4864:             foreach my $pair (@pairs) {
 4865:                 my ($key,$value) = split(/\=/,$pair);
 4866:                 if ($key eq 'thumb') {
 4867:                     &add_filetype($allfiles,$value,$key);
 4868:                 } elsif ($key eq 'content') {
 4869:                     my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
 4870:                     my ($ext) = ($value =~ /\.([^.]+)$/);
 4871:                     if ($ext ne '') {
 4872:                         &add_filetype($allfiles,$path.$value,$ext);
 4873:                     }
 4874:                 }
 4875:             }
 4876:         }
 4877:     }
 4878:     return 'ok';
 4879: }
 4880: 
 4881: sub add_filetype {
 4882:     my ($allfiles,$file,$type)=@_;
 4883:     if (exists($allfiles->{$file})) {
 4884: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
 4885: 	    push(@{$allfiles->{$file}}, &escape($type));
 4886: 	}
 4887:     } else {
 4888: 	@{$allfiles->{$file}} = (&escape($type));
 4889:     }
 4890: }
 4891: 
 4892: sub embedded_dependency {
 4893:     my ($allfiles,$related,$identifier,$pathfrom) = @_;
 4894:     if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
 4895:         if (($identifier ne '') &&
 4896:             (ref($related->{$identifier}) eq 'ARRAY') &&
 4897:             ($pathfrom ne '')) {
 4898:             my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
 4899:             foreach my $dep (@{$related->{$identifier}}) {
 4900:                 &add_filetype($allfiles,$path.$dep,'object');
 4901:             }
 4902:         }
 4903:     }
 4904:     return;
 4905: }
 4906: 
 4907: sub check_dimensions {
 4908:     my ($inputfile) = @_;
 4909:     my ($fullwidth,$fullheight);
 4910:     if (($inputfile =~ m|^[/\w.\-]+$|) && (-e $inputfile)) {
 4911:         my $mm = new File::MMagic;
 4912:         my $mime_type = $mm->checktype_filename($inputfile);
 4913:         if ($mime_type =~ m{^image/}) {
 4914:             if (open(PIPE,"identify $inputfile 2>&1 |")) {
 4915:                 my $imageinfo = <PIPE>;
 4916:                 if (!close(PIPE)) {
 4917:                     &Apache::lonnet::logthis("Failed to close PIPE opened to retrieve image information for $inputfile");
 4918:                 }
 4919:                 chomp($imageinfo);
 4920:                 my ($fullsize) =
 4921:                     ($imageinfo =~ /^\Q$inputfile\E\s+\w+\s+(\d+x\d+)/);
 4922:                 if ($fullsize) {
 4923:                     ($fullwidth,$fullheight) = split(/x/,$fullsize);
 4924:                 }
 4925:             }
 4926:         }
 4927:     }
 4928:     return ($fullwidth,$fullheight);
 4929: }
 4930: 
 4931: sub bubblesheet_converter {
 4932:     my ($cdom,$fullpath,$config,$format) = @_;
 4933:     if ((&domain($cdom) ne '') &&
 4934:         ($fullpath =~ m{^\Q$perlvar{'lonDocRoot'}/userfiles/$cdom/\E$match_courseid/scantron_orig}) &&
 4935:         (-e $fullpath) && (ref($config) eq 'HASH') && ($format ne '')) {
 4936:         my (%csvcols,%csvoptions);
 4937:         if (ref($config->{'fields'}) eq 'HASH') {  
 4938:             %csvcols = %{$config->{'fields'}};
 4939:         }
 4940:         if (ref($config->{'options'}) eq 'HASH') {
 4941:             %csvoptions = %{$config->{'options'}};
 4942:         }
 4943:         my %csvbynum = reverse(%csvcols);
 4944:         my %scantronconf = &get_scantron_config($format,$cdom);
 4945:         if (keys(%scantronconf)) {
 4946:             my %bynum = (
 4947:                           $scantronconf{CODEstart} => 'CODEstart',
 4948:                           $scantronconf{IDstart}   => 'IDstart',
 4949:                           $scantronconf{PaperID}   => 'PaperID',
 4950:                           $scantronconf{FirstName} => 'FirstName',
 4951:                           $scantronconf{LastName}  => 'LastName',
 4952:                           $scantronconf{Qstart}    => 'Qstart',
 4953:                         );
 4954:             my @ordered;
 4955:             foreach my $item (sort { $a <=> $b } keys(%bynum)) {
 4956:                 push(@ordered,$bynum{$item});
 4957:             }
 4958:             my %mapstart = (
 4959:                               CODEstart => 'CODE',
 4960:                               IDstart   => 'ID',
 4961:                               PaperID   => 'PaperID',
 4962:                               FirstName => 'FirstName',
 4963:                               LastName  => 'LastName',
 4964:                               Qstart    => 'FirstQuestion',
 4965:                            );
 4966:             my %maplength = (
 4967:                               CODEstart => 'CODElength',
 4968:                               IDstart   => 'IDlength',
 4969:                               PaperID   => 'PaperIDlength',
 4970:                               FirstName => 'FirstNamelength',
 4971:                               LastName  => 'LastNamelength',
 4972:             );
 4973:             if (open(my $fh,'<',$fullpath)) {
 4974:                 my $output;
 4975:                 my %lettdig = &letter_to_digits();
 4976:                 my %diglett = reverse(%lettdig);
 4977:                 my $numletts = scalar(keys(%lettdig));
 4978:                 my $num = 0;
 4979:                 while (my $line=<$fh>) {
 4980:                     $num ++;
 4981:                     next if (($num == 1) && ($csvoptions{'hdr'} == 1));
 4982:                     $line =~ s{[\r\n]+$}{};
 4983:                     my %found;
 4984:                     my @values = split(/,/,$line,-1);
 4985:                     my ($qstart,$record);
 4986:                     for (my $i=0; $i<@values; $i++) {
 4987:                         if ((($qstart ne '') && ($i > $qstart)) ||
 4988:                             ($csvbynum{$i} eq 'FirstQuestion')) {
 4989:                             if ($values[$i] eq '') {
 4990:                                 $values[$i] = $scantronconf{'Qoff'};
 4991:                             } elsif ($scantronconf{'Qon'} eq 'number') {
 4992:                                 if ($values[$i] =~ /^[A-Ja-j]$/) {
 4993:                                     $values[$i] = $lettdig{uc($values[$i])};
 4994:                                 }
 4995:                             } elsif ($scantronconf{'Qon'} eq 'letter') {
 4996:                                 if ($values[$i] =~ /^[0-9]$/) {
 4997:                                     $values[$i] = $diglett{$values[$i]};
 4998:                                 }
 4999:                             } else {
 5000:                                 if ($values[$i] =~ /^[0-9A-Ja-j]$/) {
 5001:                                     my $digit;
 5002:                                     if ($values[$i] =~ /^[A-Ja-j]$/) {
 5003:                                         $digit = $lettdig{uc($values[$i])}-1;
 5004:                                         if ($values[$i] eq 'J') {
 5005:                                             $digit += $numletts;
 5006:                                         }
 5007:                                     } elsif ($values[$i] =~ /^[0-9]$/) {
 5008:                                         $digit = $values[$i]-1;
 5009:                                         if ($values[$i] eq '0') {
 5010:                                             $digit += $numletts;
 5011:                                         }
 5012:                                     }
 5013:                                     my $qval='';
 5014:                                     for (my $j=0; $j<$scantronconf{'Qlength'}; $j++) {
 5015:                                         if ($j == $digit) {
 5016:                                             $qval .= $scantronconf{'Qon'};
 5017:                                         } else {
 5018:                                             $qval .= $scantronconf{'Qoff'};
 5019:                                         }
 5020:                                     }
 5021:                                     $values[$i] = $qval;
 5022:                                 }
 5023:                             }
 5024:                             if (length($values[$i]) > $scantronconf{'Qlength'}) {
 5025:                                 $values[$i] = substr($values[$i],0,$scantronconf{'Qlength'});
 5026:                             }
 5027:                             my $numblank = $scantronconf{'Qlength'} - length($values[$i]);
 5028:                             if ($numblank > 0) {
 5029:                                  $values[$i] .= ($scantronconf{'Qoff'} x $numblank);
 5030:                             }
 5031:                             if ($csvbynum{$i} eq 'FirstQuestion') {
 5032:                                 $qstart = $i;
 5033:                                 $found{$csvbynum{$i}} = $values[$i];
 5034:                             } else {
 5035:                                 $found{'FirstQuestion'} .= $values[$i];
 5036:                             }
 5037:                         } elsif (exists($csvbynum{$i})) {
 5038:                             if ($csvoptions{'rem'}) {
 5039:                                 $values[$i] =~ s/^\s+//;
 5040:                             }
 5041:                             if (($csvbynum{$i} eq 'PaperID') && ($csvoptions{'pad'})) {
 5042:                                 while (length($values[$i]) < $scantronconf{$maplength{$csvbynum{$i}}}) {
 5043:                                     $values[$i] = '0'.$values[$i];
 5044:                                 }
 5045:                             }
 5046:                             $found{$csvbynum{$i}} = $values[$i];
 5047:                         }
 5048:                     }
 5049:                     foreach my $item (@ordered) {
 5050:                         my $currlength = 1+length($record);
 5051:                         my $numspaces = $scantronconf{$item} - $currlength;
 5052:                         if ($numspaces > 0) {
 5053:                             $record .= (' ' x $numspaces);
 5054:                         }
 5055:                         if (($mapstart{$item} ne '') && (exists($found{$mapstart{$item}}))) {
 5056:                             unless ($item eq 'Qstart') {
 5057:                                 if (length($found{$mapstart{$item}}) > $scantronconf{$maplength{$item}}) {
 5058:                                     $found{$mapstart{$item}} = substr($found{$mapstart{$item}},0,$scantronconf{$maplength{$item}});
 5059:                                 }
 5060:                             }
 5061:                             $record .= $found{$mapstart{$item}};
 5062:                         }
 5063:                     }
 5064:                     $output .= "$record\n";
 5065:                 }
 5066:                 close($fh);
 5067:                 if ($output) {
 5068:                     if (open(my $fh,'>',$fullpath)) {
 5069:                         print $fh $output;
 5070:                         close($fh);
 5071:                     }
 5072:                 }
 5073:             }
 5074:         }
 5075:         return;
 5076:     }
 5077: }
 5078: 
 5079: sub letter_to_digits {
 5080:     my %lettdig = (
 5081:                     A => 1,
 5082:                     B => 2,
 5083:                     C => 3,
 5084:                     D => 4,
 5085:                     E => 5,
 5086:                     F => 6,
 5087:                     G => 7,
 5088:                     H => 8,
 5089:                     I => 9,
 5090:                     J => 0,
 5091:                   );
 5092:     return %lettdig;
 5093: }
 5094: 
 5095: sub get_scantron_config {
 5096:     my ($which,$cdom) = @_;
 5097:     my @lines = &get_scantronformat_file($cdom);
 5098:     my %config;
 5099:     #FIXME probably should move to XML it has already gotten a bit much now
 5100:     foreach my $line (@lines) {
 5101:         my ($name,$descrip)=split(/:/,$line);
 5102:         if ($name ne $which ) { next; }
 5103:         chomp($line);
 5104:         my @config=split(/:/,$line);
 5105:         $config{'name'}=$config[0];
 5106:         $config{'description'}=$config[1];
 5107:         $config{'CODElocation'}=$config[2];
 5108:         $config{'CODEstart'}=$config[3];
 5109:         $config{'CODElength'}=$config[4];
 5110:         $config{'IDstart'}=$config[5];
 5111:         $config{'IDlength'}=$config[6];
 5112:         $config{'Qstart'}=$config[7];
 5113:         $config{'Qlength'}=$config[8];
 5114:         $config{'Qoff'}=$config[9];
 5115:         $config{'Qon'}=$config[10];
 5116:         $config{'PaperID'}=$config[11];
 5117:         $config{'PaperIDlength'}=$config[12];
 5118:         $config{'FirstName'}=$config[13];
 5119:         $config{'FirstNamelength'}=$config[14];
 5120:         $config{'LastName'}=$config[15];
 5121:         $config{'LastNamelength'}=$config[16];
 5122:         $config{'BubblesPerRow'}=$config[17];
 5123:         last;
 5124:     }
 5125:     return %config;
 5126: }
 5127: 
 5128: sub get_scantronformat_file {
 5129:     my ($cdom) = @_;
 5130:     if ($cdom eq '') {
 5131:         $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
 5132:     }
 5133:     my %domconfig = &get_dom('configuration',['scantron'],$cdom);
 5134:     my $gottab = 0;
 5135:     my @lines;
 5136:     if (ref($domconfig{'scantron'}) eq 'HASH') {
 5137:         if ($domconfig{'scantron'}{'scantronformat'} ne '') {
 5138:             my $formatfile = &getfile($perlvar{'lonDocRoot'}.$domconfig{'scantron'}{'scantronformat'});
 5139:             if ($formatfile ne '-1') {
 5140:                 @lines = split("\n",$formatfile,-1);
 5141:                 $gottab = 1;
 5142:             }
 5143:         }
 5144:     }
 5145:     if (!$gottab) {
 5146:         my $confname = $cdom.'-domainconfig';
 5147:         my $default = $perlvar{'lonDocRoot'}.'/res/'.$cdom.'/'.$confname.'/default.tab';
 5148:         my $formatfile = &getfile($default);
 5149:         if ($formatfile ne '-1') {
 5150:             @lines = split("\n",$formatfile,-1);
 5151:             $gottab = 1;
 5152:         }
 5153:     }
 5154:     if (!$gottab) {
 5155:         my @domains = &current_machine_domains();
 5156:         if (grep(/^\Q$cdom\E$/,@domains)) {
 5157:             if (open(my $fh,'<',$perlvar{'lonTabDir'}.'/scantronformat.tab')) {
 5158:                 @lines = <$fh>;
 5159:                 close($fh);
 5160:             }
 5161:         } else {
 5162:             if (open(my $fh,'<',$perlvar{'lonTabDir'}.'/default_scantronformat.tab')) {
 5163:                 @lines = <$fh>;
 5164:                 close($fh);
 5165:             }
 5166:         }
 5167:         chomp(@lines);
 5168:     }
 5169:     return @lines;
 5170: }
 5171: 
 5172: sub removeuploadedurl {
 5173:     my ($url)=@_;	
 5174:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);    
 5175:     return &removeuserfile($uname,$udom,$fname);
 5176: }
 5177: 
 5178: sub removeuserfile {
 5179:     my ($docuname,$docudom,$fname)=@_;
 5180:     my $home=&homeserver($docuname,$docudom);    
 5181:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
 5182:     if ($result eq 'ok') {	
 5183:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
 5184:             my $metafile = $fname.'.meta';
 5185:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
 5186: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
 5187:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];	   
 5188:             my $sqlresult = 
 5189:                 &update_portfolio_table($docuname,$docudom,$file,
 5190:                                         'portfolio_metadata',$group,
 5191:                                         'delete');
 5192:         }
 5193:     }
 5194:     return $result;
 5195: }
 5196: 
 5197: sub mkdiruserfile {
 5198:     my ($docuname,$docudom,$dir)=@_;
 5199:     my $home=&homeserver($docuname,$docudom);
 5200:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
 5201: }
 5202: 
 5203: sub renameuserfile {
 5204:     my ($docuname,$docudom,$old,$new)=@_;
 5205:     my $home=&homeserver($docuname,$docudom);
 5206:     my $result = &reply("renameuserfile:$docudom:$docuname:".
 5207:                         &escape("$old").':'.&escape("$new"),$home);
 5208:     if ($result eq 'ok') {
 5209:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
 5210:             my $oldmeta = $old.'.meta';
 5211:             my $newmeta = $new.'.meta';
 5212:             my $metaresult = 
 5213:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
 5214: 	    my $url = "/uploaded/$docudom/$docuname/$old";
 5215:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
 5216:             my $sqlresult = 
 5217:                 &update_portfolio_table($docuname,$docudom,$file,
 5218:                                         'portfolio_metadata',$group,
 5219:                                         'delete');
 5220:         }
 5221:     }
 5222:     return $result;
 5223: }
 5224: 
 5225: # ------------------------------------------------------------------------- Log
 5226: 
 5227: sub log {
 5228:     my ($dom,$nam,$hom,$what)=@_;
 5229:     return critical("log:$dom:$nam:$what",$hom);
 5230: }
 5231: 
 5232: # ------------------------------------------------------------------ Course Log
 5233: #
 5234: # This routine flushes several buffers of non-mission-critical nature
 5235: #
 5236: 
 5237: sub flushcourselogs {
 5238:     &logthis('Flushing log buffers');
 5239: #
 5240: # course logs
 5241: # This is a log of all transactions in a course, which can be used
 5242: # for data mining purposes
 5243: #
 5244: # It also collects the courseid database, which lists last transaction
 5245: # times and course titles for all courseids
 5246: #
 5247:     my %courseidbuffer=();
 5248:     foreach my $crsid (keys(%courselogs)) {
 5249:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
 5250: 		          &escape($courselogs{$crsid}),
 5251: 		          $coursehombuf{$crsid}) eq 'ok') {
 5252: 	    delete $courselogs{$crsid};
 5253:         } else {
 5254:             &logthis('Failed to flush log buffer for '.$crsid);
 5255:             if (length($courselogs{$crsid})>40000) {
 5256:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
 5257:                         " exceeded maximum size, deleting.</font>");
 5258:                delete $courselogs{$crsid};
 5259:             }
 5260:         }
 5261:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
 5262:             'description' => $coursedescrbuf{$crsid},
 5263:             'inst_code'    => $courseinstcodebuf{$crsid},
 5264:             'type'        => $coursetypebuf{$crsid},
 5265:             'owner'       => $courseownerbuf{$crsid},
 5266:         };
 5267:     }
 5268: #
 5269: # Write course id database (reverse lookup) to homeserver of courses 
 5270: # Is used in pickcourse
 5271: #
 5272:     foreach my $crs_home (keys(%courseidbuffer)) {
 5273:         my $response = &courseidput(&host_domain($crs_home),
 5274:                                     $courseidbuffer{$crs_home},
 5275:                                     $crs_home,'timeonly');
 5276:     }
 5277: #
 5278: # File accesses
 5279: # Writes to the dynamic metadata of resources to get hit counts, etc.
 5280: #
 5281:     foreach my $entry (keys(%accesshash)) {
 5282:         if ($entry =~ /___count$/) {
 5283:             my ($dom,$name);
 5284:             ($dom,$name,undef)=
 5285: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
 5286:             if (! defined($dom) || $dom eq '' || 
 5287:                 ! defined($name) || $name eq '') {
 5288:                 my $cid = $env{'request.course.id'};
 5289: #
 5290: # FIXME 11/29/2021
 5291: # Typo in rev. 1.458 (2003/12/09)??
 5292: # These should likely by $env{'course.'.$cid.'.domain'} and $env{'course.'.$cid.'.num'}
 5293: #
 5294: # While these remain as $env{'request.'.$cid.'.domain'} and $env{'request.'.$cid.'.num'}
 5295: # $dom and $name will always be null, so the &inc() call will default to storing this data
 5296: # in a nohist_accesscount.db file for the user rather than the course.
 5297: #
 5298: # That said there is a lot of noise in the data being stored.
 5299: # So counts for prtspool/  and adm/ etc. are recorded.
 5300: #
 5301: # A review of which items ending '___count' are written to %accesshash should likely be 
 5302: # made before deciding whether to set these to 'course.' instead of 'request.'
 5303: #
 5304: # Under the current scheme each user receives a nohist_accesscount.db file listing 
 5305: # accesses for things which are not published resources, regardless of course, and
 5306: # there is not a nohist_accesscount.db file in a course, which might log accesses from
 5307: # anyone in the course for things which are not published resources.
 5308: #
 5309: # For an author, nohist_accesscount.db ends up having records for other items
 5310: # mixed up with the legitimate access counts for the author's published resources.
 5311: #
 5312:                 $dom  = $env{'request.'.$cid.'.domain'};
 5313:                 $name = $env{'request.'.$cid.'.num'};
 5314:             }
 5315:             my $value = $accesshash{$entry};
 5316:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
 5317:             my %temphash=($url => $value);
 5318:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
 5319:             if ($result eq 'ok') {
 5320:                 delete $accesshash{$entry};
 5321:             }
 5322:         } else {
 5323:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
 5324:             if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
 5325:             my %temphash=($entry => $accesshash{$entry});
 5326:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
 5327:                 delete $accesshash{$entry};
 5328:             }
 5329:         }
 5330:     }
 5331: #
 5332: # Roles
 5333: # Reverse lookup of user roles for course faculty/staff and co-authorship
 5334: #
 5335:     foreach my $entry (keys(%userrolehash)) {
 5336:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
 5337: 	    split(/\:/,$entry);
 5338:         if (&put('nohist_userroles',
 5339:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
 5340:                 $rudom,$runame) eq 'ok') {
 5341: 	    delete $userrolehash{$entry};
 5342:         }
 5343:     }
 5344: #
 5345: # Reverse lookup of domain roles (dc, ad, li, sc, dh, da, au)
 5346: #
 5347:     my %domrolebuffer = ();
 5348:     foreach my $entry (keys(%domainrolehash)) {
 5349:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
 5350:         if ($domrolebuffer{$rudom}) {
 5351:             $domrolebuffer{$rudom}.='&'.&escape($entry).
 5352:                       '='.&escape($domainrolehash{$entry});
 5353:         } else {
 5354:             $domrolebuffer{$rudom}.=&escape($entry).
 5355:                       '='.&escape($domainrolehash{$entry});
 5356:         }
 5357:         delete $domainrolehash{$entry};
 5358:     }
 5359:     foreach my $dom (keys(%domrolebuffer)) {
 5360: 	my %servers;
 5361: 	if (defined(&domain($dom,'primary'))) {
 5362: 	    my $primary=&domain($dom,'primary');
 5363: 	    my $hostname=&hostname($primary);
 5364: 	    $servers{$primary} = $hostname;
 5365: 	} else { 
 5366: 	    %servers = &get_servers($dom,'library');
 5367: 	}
 5368: 	foreach my $tryserver (keys(%servers)) {
 5369: 	    if (&reply('domroleput:'.$dom.':'.
 5370: 		       $domrolebuffer{$dom},$tryserver) eq 'ok') {
 5371: 		last;
 5372: 	    } else {  
 5373: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
 5374: 	    }
 5375:         }
 5376:     }
 5377:     $dumpcount++;
 5378: }
 5379: 
 5380: sub courselog {
 5381:     my $what=shift;
 5382:     $what=time.':'.$what;
 5383:     unless ($env{'request.course.id'}) { return ''; }
 5384:     $coursedombuf{$env{'request.course.id'}}=
 5385:        $env{'course.'.$env{'request.course.id'}.'.domain'};
 5386:     $coursenumbuf{$env{'request.course.id'}}=
 5387:        $env{'course.'.$env{'request.course.id'}.'.num'};
 5388:     $coursehombuf{$env{'request.course.id'}}=
 5389:        $env{'course.'.$env{'request.course.id'}.'.home'};
 5390:     $coursedescrbuf{$env{'request.course.id'}}=
 5391:        $env{'course.'.$env{'request.course.id'}.'.description'};
 5392:     $courseinstcodebuf{$env{'request.course.id'}}=
 5393:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
 5394:     $courseownerbuf{$env{'request.course.id'}}=
 5395:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
 5396:     $coursetypebuf{$env{'request.course.id'}}=
 5397:        $env{'course.'.$env{'request.course.id'}.'.type'};
 5398:     if (defined $courselogs{$env{'request.course.id'}}) {
 5399: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
 5400:     } else {
 5401: 	$courselogs{$env{'request.course.id'}}.=$what;
 5402:     }
 5403:     if (length($courselogs{$env{'request.course.id'}})>4048) {
 5404: 	&flushcourselogs();
 5405:     }
 5406: }
 5407: 
 5408: sub courseacclog {
 5409:     my $fnsymb=shift;
 5410:     unless ($env{'request.course.id'}) { return ''; }
 5411:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
 5412:     if ($fnsymb=~/$LONCAPA::assess_re/) {
 5413:         $what.=':POST';
 5414:         # FIXME: Probably ought to escape things....
 5415: 	foreach my $key (keys(%env)) {
 5416:             if ($key=~/^form\.(.*)/) {
 5417:                 my $formitem = $1;
 5418:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
 5419:                     $what.=':'.$formitem.'='.$env{$key};
 5420:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
 5421:                     if ($formitem eq 'proctorpassword') {
 5422:                         $what.=':'.$formitem.'=' . '*' x length($env{$key});
 5423:                     } else {
 5424:                         $what.=':'.$formitem.'='.$env{$key};
 5425:                     }
 5426:                 }
 5427:             }
 5428:         }
 5429:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
 5430:         # FIXME: We should not be depending on a form parameter that someone
 5431:         # editing lonsearchcat.pm might change in the future.
 5432:         if ($env{'form.phase'} eq 'course_search') {
 5433:             $what.= ':POST';
 5434:             # FIXME: Probably ought to escape things....
 5435:             foreach my $element ('courseexp','crsfulltext','crsrelated',
 5436:                                  'crsdiscuss') {
 5437:                 $what.=':'.$element.'='.$env{'form.'.$element};
 5438:             }
 5439:         }
 5440:     }
 5441:     &courselog($what);
 5442: }
 5443: 
 5444: sub countacc {
 5445:     my $url=&declutter(shift);
 5446:     return if (! defined($url) || $url eq '');
 5447:     unless ($env{'request.course.id'}) { return ''; }
 5448: #
 5449: # Mark that this url was used in this course
 5450: #
 5451:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
 5452: #
 5453: # Increase the access count for this resource in this child process
 5454: #
 5455:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
 5456:     $accesshash{$key}++;
 5457: }
 5458: 
 5459: sub linklog {
 5460:     my ($from,$to)=@_;
 5461:     $from=&declutter($from);
 5462:     $to=&declutter($to);
 5463:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
 5464:     $accesshash{$to.'___'.$from.'___goto'}=1;
 5465: }
 5466: 
 5467: sub statslog {
 5468:     my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
 5469:     if ($users<2) { return; }
 5470:     my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
 5471:             'course'       => $env{'request.course.id'},
 5472:             'sections'     => '"all"',
 5473:             'num_students' => $users,
 5474:             'part'         => $part,
 5475:             'symb'         => $symb,
 5476:             'mean_tries'   => $av_attempts,
 5477:             'deg_of_diff'  => $degdiff});
 5478:     foreach my $key (keys(%dynstore)) {
 5479:         $accesshash{$key}=$dynstore{$key};
 5480:     }
 5481: }
 5482:   
 5483: sub userrolelog {
 5484:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
 5485:     if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
 5486:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 5487:        $userrolehash
 5488:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 5489:                     =$tend.':'.$tstart;
 5490:     }
 5491:     if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
 5492:        $userrolehash
 5493:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
 5494:                     =$tend.':'.$tstart;
 5495:     }
 5496:     if ($trole =~ /^(dc|ad|li|au|dg|sc|dh|da)/ ) {
 5497:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 5498:        $domainrolehash
 5499:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 5500:                     = $tend.':'.$tstart;
 5501:     }
 5502: }
 5503: 
 5504: sub courserolelog {
 5505:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,
 5506:         $context,$othdomby,$requester)=@_;
 5507:     if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
 5508:         my $cdom = $1;
 5509:         my $cnum = $2;
 5510:         my $sec = $3;
 5511:         my $namespace = 'rolelog';
 5512:         my %storehash = (
 5513:                            role    => $trole,
 5514:                            start   => $tstart,
 5515:                            end     => $tend,
 5516:                            selfenroll => $selfenroll,
 5517:                            context    => $context,
 5518:                         );
 5519:         if ($othdomby) {
 5520:             if ($othdomby eq 'othdombydc') {
 5521:                 $storehash{'approval'} = 'domain';
 5522:             } elsif ($othdomby eq 'othdombyuser') {
 5523:                 $storehash{'approval'} = 'user'; 
 5524:             }
 5525:             if ($requester ne '') {
 5526:                 $storehash{'requester'} = $requester;
 5527:             }
 5528:         }
 5529:         if ($trole eq 'gr') {
 5530:             $namespace = 'groupslog';
 5531:             $storehash{'group'} = $sec;
 5532:         } else {
 5533:             $storehash{'section'} = $sec;
 5534:             my ($curruserdomstr,$newuserdomstr);
 5535:             if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.userdomains'})) {
 5536:                 $curruserdomstr = $env{'course.'.$env{'request.course.id'}.'.internal.userdomains'};
 5537:             } else {
 5538:                 my %courseinfo = &coursedescription($cdom.'/'.$cnum);
 5539:                 $curruserdomstr = $courseinfo{'internal.userdomains'};
 5540:             }
 5541:             if ($curruserdomstr ne '') {
 5542:                 my @udoms = split(/,/,$curruserdomstr);
 5543:                 unless (grep(/^\Q$domain\E/,@udoms)) {
 5544:                     push(@udoms,$domain);
 5545:                     $newuserdomstr = join(',',sort(@udoms));
 5546:                 }
 5547:             } else {
 5548:                 $newuserdomstr = $domain;
 5549:             }
 5550:             if ($newuserdomstr ne '') {
 5551:                 my $putresult = &put('environment',{ 'internal.userdomains' => $newuserdomstr },
 5552:                                      $cdom,$cnum);
 5553:                 if ($putresult eq 'ok') {
 5554:                     unless (($selfenroll) || ($context eq 'selfenroll')) { 
 5555:                         if (($context eq 'createcourse') || ($context eq 'requestcourses') ||
 5556:                             ($context eq 'automated') || ($context eq 'domain')) {
 5557:                             $env{'course.'.$cdom.'_'.$cnum.'.internal.userdomains'} = $newuserdomstr;
 5558:                         } elsif ($env{'request.course.id'} eq $cdom.'_'.$cnum) {
 5559:                             &appenv({'course.'.$cdom.'_'.$cnum.'.internal.userdomains' => $newuserdomstr});
 5560:                         }
 5561:                     }
 5562:                 }
 5563:             }
 5564:         }
 5565:         &write_log('course',$namespace,\%storehash,$delflag,$username,
 5566:                    $domain,$cnum,$cdom);
 5567:         if (($trole ne 'st') || ($sec ne '')) {
 5568:             &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
 5569:         }
 5570:     }
 5571:     return;
 5572: }
 5573: 
 5574: sub domainrolelog {
 5575:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,
 5576:         $context,$othdomby,$requester)=@_;
 5577:     if ($area =~ m{^/($match_domain)/$}) {
 5578:         my $cdom = $1;
 5579:         my $domconfiguser = &get_domainconfiguser($cdom);
 5580:         my $namespace = 'rolelog';
 5581:         my %storehash = (
 5582:                            role    => $trole,
 5583:                            start   => $tstart,
 5584:                            end     => $tend,
 5585:                            context => $context,
 5586:                         );
 5587:         if ($othdomby) {
 5588:             if ($othdomby eq 'othdombydc') {
 5589:                 $storehash{'approval'} = 'domain';
 5590:             } elsif ($othdomby eq 'othdombyuser') {
 5591:                 $storehash{'approval'} = 'user';
 5592:             }
 5593:             if ($requester ne '') {
 5594:                 $storehash{'requester'} = $requester;
 5595:             }
 5596:         }
 5597:         &write_log('domain',$namespace,\%storehash,$delflag,$username,
 5598:                    $domain,$domconfiguser,$cdom);
 5599:     }
 5600:     return;
 5601: 
 5602: }
 5603: 
 5604: sub coauthorrolelog {
 5605:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,
 5606:         $context,$othdomby,$requester)=@_;
 5607:     if ($area =~ m{^/($match_domain)/($match_username)$}) {
 5608:         my $audom = $1;
 5609:         my $auname = $2;
 5610:         my $namespace = 'rolelog';
 5611:         my %storehash = (
 5612:                            role    => $trole,
 5613:                            start   => $tstart,
 5614:                            end     => $tend,
 5615:                            context => $context,
 5616:                         );
 5617:         if ($othdomby) {
 5618:             if ($othdomby eq 'othdombydc') {
 5619:                 $storehash{'approval'} = 'domain';
 5620:             } elsif ($othdomby eq 'othdombyuser') {
 5621:                 $storehash{'approval'} = 'user';
 5622:             }
 5623:             if ($requester ne '') {
 5624:                 $storehash{'requester'} = $requester;
 5625:             }
 5626:         }
 5627:         &write_log('author',$namespace,\%storehash,$delflag,$username,
 5628:                    $domain,$auname,$audom);
 5629:     }
 5630:     return;
 5631: }
 5632: 
 5633: sub authorarchivelog {
 5634:     my ($hashref,$size,$filesdest,$action) = @_;
 5635:     my $lonprtdir = $Apache::lonnet::perlvar{'lonPrtDir'};
 5636:     my $londocroot = $Apache::lonnet::perlvar{'lonDocRoot'};
 5637:     $filesdest =~ s{^\Q$lonprtdir/\E}{};
 5638:     if ($filesdest =~ m{^($match_username)_($match_domain)_archive_(\d+_\d+_\d+(|[.\w]+))$}) {
 5639:         my ($auname,$audom,$id) = ($1,$2,$3);
 5640:         if (ref($hashref) eq 'HASH') {
 5641:             my $namespace = 'archivelog';
 5642:             my $dir;
 5643:             if ($hashref->{dir} =~ m{^\Q$londocroot/priv/$audom/$auname\E(.*)$}) {
 5644:                 $dir = $1;
 5645:             }
 5646:             my $delflag = 0;
 5647:             my %storehash = (
 5648:                               id      => $id,
 5649:                               dir     => $dir,
 5650:                               files   => $hashref->{numfiles},
 5651:                               subdirs => $hashref->{numdirs},
 5652:                               bytes   => $hashref->{bytes},
 5653:                               size    => $size,
 5654:                               action  => $action,
 5655:                             );
 5656:             if ($action eq 'delete') {
 5657:                 $delflag = 1;
 5658:             }
 5659:             &write_log('author',$namespace,\%storehash,$delflag,$auname,
 5660:                        $audom,$auname,$audom);
 5661:         }
 5662:     }
 5663:     return;
 5664: }
 5665: 
 5666: sub get_course_adv_roles {
 5667:     my ($cid,$codes) = @_;
 5668:     $cid=$env{'request.course.id'} unless (defined($cid));
 5669:     my %coursehash=&coursedescription($cid);
 5670:     my $crstype = &Apache::loncommon::course_type($cid);
 5671:     my %nothide=();
 5672:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 5673:         if ($user !~ /:/) {
 5674: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
 5675:         } else {
 5676:             $nothide{$user}=1;
 5677:         }
 5678:     }
 5679:     my @possdoms = ($coursehash{'domain'});
 5680:     if ($coursehash{'checkforpriv'}) {
 5681:         push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
 5682:     }
 5683:     my %returnhash=();
 5684:     my %dumphash=
 5685:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
 5686:     my $now=time;
 5687:     my %privileged;
 5688:     foreach my $entry (keys(%dumphash)) {
 5689: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
 5690:         if (($tstart) && ($tstart<0)) { next; }
 5691:         if (($tend) && ($tend<$now)) { next; }
 5692:         if (($tstart) && ($now<$tstart)) { next; }
 5693:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
 5694: 	if ($username eq '' || $domain eq '') { next; }
 5695:         if ((&privileged($username,$domain,\@possdoms)) &&
 5696:             (!$nothide{$username.':'.$domain})) { next; }
 5697: 	if ($role eq 'cr') { next; }
 5698:         if ($codes) {
 5699:             if ($section) { $role .= ':'.$section; }
 5700:             if ($returnhash{$role}) {
 5701:                 $returnhash{$role}.=','.$username.':'.$domain;
 5702:             } else {
 5703:                 $returnhash{$role}=$username.':'.$domain;
 5704:             }
 5705:         } else {
 5706:             my $key=&plaintext($role,$crstype);
 5707:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
 5708:             if ($returnhash{$key}) {
 5709: 	        $returnhash{$key}.=','.$username.':'.$domain;
 5710:             } else {
 5711:                 $returnhash{$key}=$username.':'.$domain;
 5712:             }
 5713:         }
 5714:     }
 5715:     return %returnhash;
 5716: }
 5717: 
 5718: sub get_my_roles {
 5719:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
 5720:     unless (defined($uname)) { $uname=$env{'user.name'}; }
 5721:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
 5722:     my (%dumphash,%nothide);
 5723:     if ($context eq 'userroles') {
 5724:         %dumphash = &dump('roles',$udom,$uname);
 5725:     } else {
 5726:         %dumphash = &dump('nohist_userroles',$udom,$uname);
 5727:         if ($hidepriv) {
 5728:             my %coursehash=&coursedescription($udom.'_'.$uname);
 5729:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 5730:                 if ($user !~ /:/) {
 5731:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
 5732:                 } else {
 5733:                     $nothide{$user} = 1;
 5734:                 }
 5735:             }
 5736:         }
 5737:     }
 5738:     my %returnhash=();
 5739:     my $now=time;
 5740:     my %privileged;
 5741:     foreach my $entry (keys(%dumphash)) {
 5742:         my ($role,$tend,$tstart);
 5743:         if ($context eq 'userroles') {
 5744:             next if ($entry =~ /^rolesdef/);
 5745: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
 5746:         } else {
 5747:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
 5748:         }
 5749:         if (($tstart) && ($tstart<0)) { next; }
 5750:         my $status = 'active';
 5751:         if (($tend) && ($tend<=$now)) {
 5752:             $status = 'previous';
 5753:         } 
 5754:         if (($tstart) && ($now<$tstart)) {
 5755:             $status = 'future';
 5756:         }
 5757:         if (ref($types) eq 'ARRAY') {
 5758:             if (!grep(/^\Q$status\E$/,@{$types})) {
 5759:                 next;
 5760:             } 
 5761:         } else {
 5762:             if ($status ne 'active') {
 5763:                 next;
 5764:             }
 5765:         }
 5766:         my ($rolecode,$username,$domain,$section,$area);
 5767:         if ($context eq 'userroles') {
 5768:             ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
 5769:             (undef,$domain,$username,$section) = split(/\//,$area);
 5770:         } else {
 5771:             ($role,$username,$domain,$section) = split(/\:/,$entry);
 5772:         }
 5773:         if (ref($roledoms) eq 'ARRAY') {
 5774:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
 5775:                 next;
 5776:             }
 5777:         }
 5778:         if (ref($roles) eq 'ARRAY') {
 5779:             if (!grep(/^\Q$role\E$/,@{$roles})) {
 5780:                 if ($role =~ /^cr\//) {
 5781:                     if (!grep(/^cr$/,@{$roles})) {
 5782:                         next;
 5783:                     }
 5784:                 } elsif ($role =~ /^gr\//) {
 5785:                     if (!grep(/^gr$/,@{$roles})) {
 5786:                         next;
 5787:                     }
 5788:                 } else {
 5789:                     next;
 5790:                 }
 5791:             }
 5792:         }
 5793:         if ($hidepriv) {
 5794:             my @privroles = ('dc','su');
 5795:             if ($context eq 'userroles') {
 5796:                 next if (grep(/^\Q$role\E$/,@privroles));
 5797:             } else {
 5798:                 my $possdoms = [$domain];
 5799:                 if (ref($roledoms) eq 'ARRAY') {
 5800:                    push(@{$possdoms},@{$roledoms}); 
 5801:                 }
 5802:                 if (&privileged($username,$domain,$possdoms,\@privroles)) {
 5803:                     if (!$nothide{$username.':'.$domain}) {
 5804:                         next;
 5805:                     }
 5806:                 }
 5807:             }
 5808:         }
 5809:         if ($withsec) {
 5810:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
 5811:                 $tstart.':'.$tend;
 5812:         } else {
 5813:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
 5814:         }
 5815:     }
 5816:     return %returnhash;
 5817: }
 5818: 
 5819: sub get_all_adhocroles {
 5820:     my ($dom) = @_;
 5821:     my @roles_by_num = ();
 5822:     my %domdefaults = &get_domain_defaults($dom);
 5823:     my (%description,%access_in_dom,%access_info);
 5824:     if (ref($domdefaults{'adhocroles'}) eq 'HASH') {
 5825:         my $count = 0;
 5826:         my %domcurrent = %{$domdefaults{'adhocroles'}};
 5827:         my %ordered;
 5828:         foreach my $role (sort(keys(%domcurrent))) {
 5829:             my ($order,$desc,$access_in_dom);
 5830:             if (ref($domcurrent{$role}) eq 'HASH') {
 5831:                 $order = $domcurrent{$role}{'order'};
 5832:                 $desc = $domcurrent{$role}{'desc'};
 5833:                 $access_in_dom{$role} = $domcurrent{$role}{'access'};
 5834:                 $access_info{$role} = $domcurrent{$role}{$access_in_dom{$role}};
 5835:             }
 5836:             if ($order eq '') {
 5837:                 $order = $count;
 5838:             }
 5839:             $ordered{$order} = $role;
 5840:             if ($desc ne '') {
 5841:                 $description{$role} = $desc;
 5842:             } else {
 5843:                 $description{$role}= $role;
 5844:             }
 5845:             $count++;
 5846:         }
 5847:         foreach my $item (sort {$a <=> $b } (keys(%ordered))) {
 5848:             push(@roles_by_num,$ordered{$item});
 5849:         }
 5850:     }
 5851:     return (\@roles_by_num,\%description,\%access_in_dom,\%access_info);
 5852: }
 5853: 
 5854: sub get_my_adhocroles {
 5855:     my ($cid,$checkreg) = @_;
 5856:     my ($cdom,$cnum,%info,@possroles,$description,$roles_by_num);
 5857:     if ($env{'request.course.id'} eq $cid) {
 5858:         $cdom = $env{'course.'.$cid.'.domain'};
 5859:         $cnum = $env{'course.'.$cid.'.num'};
 5860:         $info{'internal.coursecode'} = $env{'course.'.$cid.'.internal.coursecode'};
 5861:     } elsif ($cid =~ /^($match_domain)_($match_courseid)$/) {
 5862:         $cdom = $1;
 5863:         $cnum = $2;
 5864:         %info = &get('environment',['internal.coursecode'],
 5865:                      $cdom,$cnum);
 5866:     }
 5867:     if (($info{'internal.coursecode'} ne '') && ($checkreg)) {
 5868:         my $user = $env{'user.name'}.':'.$env{'user.domain'};
 5869:         my %rosterhash = &get('classlist',[$user],$cdom,$cnum);
 5870:         if ($rosterhash{$user} ne '') {
 5871:             my $type = (split(/:/,$rosterhash{$user}))[5];
 5872:             return ([],{}) if ($type eq 'auto');
 5873:         }
 5874:     }
 5875:     if (($cdom ne '') && ($cnum ne ''))  {
 5876:         if (($env{"user.role.dh./$cdom/"}) || ($env{"user.role.da./$cdom/"})) {
 5877:             my $then=$env{'user.login.time'};
 5878:             my $update=$env{'user.update.time'};
 5879:             if (!$update) {
 5880:                 $update = $then;
 5881:             }
 5882:             my @liveroles;
 5883:             foreach my $role ('dh','da') {
 5884:                 if ($env{"user.role.$role./$cdom/"}) {
 5885:                     my ($tstart,$tend)=split(/\./,$env{"user.role.$role./$cdom/"});
 5886:                     my $limit = $update;
 5887:                     if ($env{'request.role'} eq "$role./$cdom/") {
 5888:                         $limit = $then;
 5889:                     }
 5890:                     my $activerole = 1;
 5891:                     if ($tstart && $tstart>$limit) { $activerole = 0; }
 5892:                     if ($tend   && $tend  <$limit) { $activerole = 0; }
 5893:                     if ($activerole) {
 5894:                         push(@liveroles,$role);
 5895:                     }
 5896:                 }
 5897:             }
 5898:             if (@liveroles) {
 5899:                 if (&homeserver($cnum,$cdom) ne 'no_host') {
 5900:                     my ($accessref,$accessinfo,%access_in_dom);
 5901:                     ($roles_by_num,$description,$accessref,$accessinfo) = &get_all_adhocroles($cdom);
 5902:                     if (ref($roles_by_num) eq 'ARRAY') {
 5903:                         if (@{$roles_by_num}) {
 5904:                             my %settings;
 5905:                             if ($env{'request.course.id'} eq $cid) {
 5906:                                 foreach my $envkey (keys(%env)) {
 5907:                                     if ($envkey =~ /^\Qcourse.$cid.\E(internal\.adhoc.+)$/) {
 5908:                                         $settings{$1} = $env{$envkey};
 5909:                                     }
 5910:                                 }
 5911:                             } else {
 5912:                                 %settings = &dump('environment',$cdom,$cnum,'internal\.adhoc');
 5913:                             }
 5914:                             my %setincrs;
 5915:                             if ($settings{'internal.adhocaccess'}) {
 5916:                                 map { $setincrs{$_} = 1; } split(/,/,$settings{'internal.adhocaccess'});
 5917:                             }
 5918:                             my @statuses;
 5919:                             if ($env{'environment.inststatus'}) {
 5920:                                 @statuses = split(/,/,$env{'environment.inststatus'});
 5921:                             }
 5922:                             my $user = $env{'user.name'}.':'.$env{'user.domain'};
 5923:                             if (ref($accessref) eq 'HASH') {
 5924:                                 %access_in_dom = %{$accessref};
 5925:                             }
 5926:                             foreach my $role (@{$roles_by_num}) {
 5927:                                 my ($curraccess,@okstatus,@personnel);
 5928:                                 if ($setincrs{$role}) {
 5929:                                     ($curraccess,my $rest) = split(/=/,$settings{'internal.adhoc.'.$role});
 5930:                                     if ($curraccess eq 'status') {
 5931:                                         @okstatus = split(/\&/,$rest);
 5932:                                     } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
 5933:                                         @personnel = split(/\&/,$rest);
 5934:                                     }
 5935:                                 } else {
 5936:                                     $curraccess = $access_in_dom{$role};
 5937:                                     if (ref($accessinfo) eq 'HASH') {
 5938:                                         if ($curraccess eq 'status') {
 5939:                                             if (ref($accessinfo->{$role}) eq 'ARRAY') {
 5940:                                                 @okstatus = @{$accessinfo->{$role}};
 5941:                                             }
 5942:                                         } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
 5943:                                             if (ref($accessinfo->{$role}) eq 'ARRAY') {
 5944:                                                 @personnel = @{$accessinfo->{$role}};
 5945:                                             }
 5946:                                         }
 5947:                                     }
 5948:                                 }
 5949:                                 if ($curraccess eq 'none') {
 5950:                                     next;
 5951:                                 } elsif ($curraccess eq 'all') {
 5952:                                     push(@possroles,$role);
 5953:                                 } elsif ($curraccess eq 'dh') {
 5954:                                     if (grep(/^dh$/,@liveroles)) {
 5955:                                         push(@possroles,$role);
 5956:                                     } else {
 5957:                                         next;
 5958:                                     }
 5959:                                 } elsif ($curraccess eq 'da') {
 5960:                                     if (grep(/^da$/,@liveroles)) {
 5961:                                         push(@possroles,$role);
 5962:                                     } else {
 5963:                                         next;
 5964:                                     }
 5965:                                 } elsif ($curraccess eq 'status') {
 5966:                                     if (@okstatus) {
 5967:                                         if (!@statuses) {
 5968:                                             if (grep(/^default$/,@okstatus)) {
 5969:                                                 push(@possroles,$role);
 5970:                                             }
 5971:                                         } else {
 5972:                                             foreach my $status (@okstatus) {
 5973:                                                 if (grep(/^\Q$status\E$/,@statuses)) {
 5974:                                                     push(@possroles,$role);
 5975:                                                     last;
 5976:                                                 }
 5977:                                             }
 5978:                                         }
 5979:                                     }
 5980:                                 } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
 5981:                                     if (grep(/^\Q$user\E$/,@personnel)) {
 5982:                                         if ($curraccess eq 'exc') {
 5983:                                             push(@possroles,$role);
 5984:                                         }
 5985:                                     } elsif ($curraccess eq 'inc') {
 5986:                                         push(@possroles,$role);
 5987:                                     }
 5988:                                 }
 5989:                             }
 5990:                         }
 5991:                     }
 5992:                 }
 5993:             }
 5994:         }
 5995:     }
 5996:     unless (ref($description) eq 'HASH') {
 5997:         if (ref($roles_by_num) eq 'ARRAY') {
 5998:             my %desc;
 5999:             map { $desc{$_} = $_; } (@{$roles_by_num});
 6000:             $description = \%desc;
 6001:         } else {
 6002:             $description = {};
 6003:         }
 6004:     }
 6005:     return (\@possroles,$description);
 6006: }
 6007: 
 6008: # ----------------------------------------------------- Frontpage Announcements
 6009: #
 6010: #
 6011: 
 6012: sub postannounce {
 6013:     my ($server,$text)=@_;
 6014:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
 6015:     unless ($text=~/\w/) { $text=''; }
 6016:     return &reply('setannounce:'.&escape($text),$server);
 6017: }
 6018: 
 6019: sub getannounce {
 6020: 
 6021:     if (open(my $fh,"<",$perlvar{'lonDocRoot'}.'/announcement.txt')) {
 6022: 	my $announcement='';
 6023: 	while (my $line = <$fh>) { $announcement .= $line; }
 6024: 	close($fh);
 6025: 	if ($announcement=~/\w/) { 
 6026: 	    return 
 6027:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
 6028:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
 6029: 	} else {
 6030: 	    return '';
 6031: 	}
 6032:     } else {
 6033: 	return '';
 6034:     }
 6035: }
 6036: 
 6037: # ---------------------------------------------------------- Course ID routines
 6038: # Deal with domain's nohist_courseid.db files
 6039: #
 6040: 
 6041: sub courseidput {
 6042:     my ($domain,$storehash,$coursehome,$caller) = @_;
 6043:     return unless (ref($storehash) eq 'HASH');
 6044:     my $outcome;
 6045:     if ($caller eq 'timeonly') {
 6046:         my $cids = '';
 6047:         foreach my $item (keys(%$storehash)) {
 6048:             $cids.=&escape($item).'&';
 6049:         }
 6050:         $cids=~s/\&$//;
 6051:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
 6052:                           $coursehome);       
 6053:     } else {
 6054:         my $items = '';
 6055:         foreach my $item (keys(%$storehash)) {
 6056:             $items.= &escape($item).'='.
 6057:                      &freeze_escape($$storehash{$item}).'&';
 6058:         }
 6059:         $items=~s/\&$//;
 6060:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
 6061:                           $coursehome);
 6062:     }
 6063:     if ($outcome eq 'unknown_cmd') {
 6064:         my $what;
 6065:         foreach my $cid (keys(%$storehash)) {
 6066:             $what .= &escape($cid).'=';
 6067:             foreach my $item ('description','inst_code','owner','type') {
 6068:                 $what .= &escape($storehash->{$cid}{$item}).':';
 6069:             }
 6070:             $what =~ s/\:$/&/;
 6071:         }
 6072:         $what =~ s/\&$//;  
 6073:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
 6074:     } else {
 6075:         return $outcome;
 6076:     }
 6077: }
 6078: 
 6079: sub courseiddump {
 6080:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
 6081:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
 6082:         $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
 6083:         $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner,
 6084:         $hasuniquecode,$reqcrsdom,$reqinstcode)=@_;
 6085:     my $as_hash = 1;
 6086:     my %returnhash;
 6087:     if (!$domfilter) { $domfilter=''; }
 6088:     my %libserv = &all_library();
 6089:     foreach my $tryserver (keys(%libserv)) {
 6090:         if ( (  $hostidflag == 1 
 6091: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
 6092: 	     || (!defined($hostidflag)) ) {
 6093: 
 6094: 	    if (($domfilter eq '') ||
 6095: 		(&host_domain($tryserver) eq $domfilter)) {
 6096:                 my $rep;
 6097:                 if (grep { $_ eq $tryserver } current_machine_ids()) {
 6098:                     $rep = LONCAPA::Lond::dump_course_id_handler(
 6099:                         join(":", (&host_domain($tryserver), $sincefilter, 
 6100:                                 &escape($descfilter), &escape($instcodefilter), 
 6101:                                 &escape($ownerfilter), &escape($coursefilter),
 6102:                                 &escape($typefilter), &escape($regexp_ok), 
 6103:                                 $as_hash, &escape($selfenrollonly), 
 6104:                                 &escape($catfilter), $showhidden, $caller, 
 6105:                                 &escape($cloner), &escape($cc_clone), $cloneonly, 
 6106:                                 &escape($createdbefore), &escape($createdafter), 
 6107:                                 &escape($creationcontext),$domcloner,$hasuniquecode,
 6108:                                 $reqcrsdom,&escape($reqinstcode))));
 6109:                 } else {
 6110:                     $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
 6111:                              $sincefilter.':'.&escape($descfilter).':'.
 6112:                              &escape($instcodefilter).':'.&escape($ownerfilter).
 6113:                              ':'.&escape($coursefilter).':'.&escape($typefilter).
 6114:                              ':'.&escape($regexp_ok).':'.$as_hash.':'.
 6115:                              &escape($selfenrollonly).':'.&escape($catfilter).':'.
 6116:                              $showhidden.':'.$caller.':'.&escape($cloner).':'.
 6117:                              &escape($cc_clone).':'.$cloneonly.':'.
 6118:                              &escape($createdbefore).':'.&escape($createdafter).':'.
 6119:                              &escape($creationcontext).':'.$domcloner.':'.$hasuniquecode.
 6120:                              ':'.$reqcrsdom.':'.&escape($reqinstcode),$tryserver);
 6121:                 }
 6122:                      
 6123:                 my @pairs=split(/\&/,$rep);
 6124:                 foreach my $item (@pairs) {
 6125:                     my ($key,$value)=split(/\=/,$item,2);
 6126:                     $key = &unescape($key);
 6127:                     next if ($key =~ /^error: 2 /);
 6128:                     my $result = &thaw_unescape($value);
 6129:                     if (ref($result) eq 'HASH') {
 6130:                         $returnhash{$key}=$result;
 6131:                     } else {
 6132:                         my @responses = split(/:/,$value);
 6133:                         my @items = ('description','inst_code','owner','type');
 6134:                         for (my $i=0; $i<@responses; $i++) {
 6135:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
 6136:                         }
 6137:                     }
 6138:                 }
 6139:             }
 6140:         }
 6141:     }
 6142:     return %returnhash;
 6143: }
 6144: 
 6145: sub courselastaccess {
 6146:     my ($cdom,$cnum,$hostidref) = @_;
 6147:     my %returnhash;
 6148:     if ($cdom && $cnum) {
 6149:         my $chome = &homeserver($cnum,$cdom);
 6150:         if ($chome ne 'no_host') {
 6151:             my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
 6152:             &extract_lastaccess(\%returnhash,$rep);
 6153:         }
 6154:     } else {
 6155:         if (!$cdom) { $cdom=''; }
 6156:         my %libserv = &all_library();
 6157:         foreach my $tryserver (keys(%libserv)) {
 6158:             if (ref($hostidref) eq 'ARRAY') {
 6159:                 next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
 6160:             } 
 6161:             if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
 6162:                 my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
 6163:                 &extract_lastaccess(\%returnhash,$rep);
 6164:             }
 6165:         }
 6166:     }
 6167:     return %returnhash;
 6168: }
 6169: 
 6170: sub extract_lastaccess {
 6171:     my ($returnhash,$rep) = @_;
 6172:     if (ref($returnhash) eq 'HASH') {
 6173:         unless ($rep eq 'unknown_cmd' || $rep eq 'no_such_host' || 
 6174:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
 6175:                  $rep eq '') {
 6176:             my @pairs=split(/\&/,$rep);
 6177:             foreach my $item (@pairs) {
 6178:                 my ($key,$value)=split(/\=/,$item,2);
 6179:                 $key = &unescape($key);
 6180:                 next if ($key =~ /^error: 2 /);
 6181:                 $returnhash->{$key} = &thaw_unescape($value);
 6182:             }
 6183:         }
 6184:     }
 6185:     return;
 6186: }
 6187: 
 6188: # ---------------------------------------------------------- DC e-mail
 6189: 
 6190: sub dcmailput {
 6191:     my ($domain,$msgid,$message,$server)=@_;
 6192:     my $status = &critical(
 6193:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
 6194:        &escape($message),$server);
 6195:     return $status;
 6196: }
 6197: 
 6198: sub dcmaildump {
 6199:     my ($dom,$startdate,$enddate,$senders) = @_;
 6200:     my %returnhash=();
 6201: 
 6202:     if (defined(&domain($dom,'primary'))) {
 6203:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
 6204:                                                          &escape($enddate).':';
 6205: 	my @esc_senders=map { &escape($_)} @$senders;
 6206: 	$cmd.=&escape(join('&',@esc_senders));
 6207: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
 6208:             my ($key,$value) = split(/\=/,$line,2);
 6209:             if (($key) && ($value)) {
 6210:                 $returnhash{&unescape($key)} = &unescape($value);
 6211:             }
 6212:         }
 6213:     }
 6214:     return %returnhash;
 6215: }
 6216: # ---------------------------------------------------------- Domain roles
 6217: 
 6218: sub get_domain_roles {
 6219:     my ($dom,$roles,$startdate,$enddate)=@_;
 6220:     if ((!defined($startdate)) || ($startdate eq '')) {
 6221:         $startdate = '.';
 6222:     }
 6223:     if ((!defined($enddate)) || ($enddate eq '')) {
 6224:         $enddate = '.';
 6225:     }
 6226:     my $rolelist;
 6227:     if (ref($roles) eq 'ARRAY') {
 6228:         $rolelist = join('&',@{$roles});
 6229:     }
 6230:     my %personnel = ();
 6231: 
 6232:     my %servers = &get_servers($dom,'library');
 6233:     foreach my $tryserver (keys(%servers)) {
 6234: 	%{$personnel{$tryserver}}=();
 6235: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
 6236: 					    &escape($startdate).':'.
 6237: 					    &escape($enddate).':'.
 6238: 					    &escape($rolelist), $tryserver))) {
 6239: 	    my ($key,$value) = split(/\=/,$line,2);
 6240: 	    if (($key) && ($value)) {
 6241: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
 6242: 	    }
 6243: 	}
 6244:     }
 6245:     return %personnel;
 6246: }
 6247: 
 6248: sub get_active_domroles {
 6249:     my ($dom,$roles) = @_;
 6250:     return () unless (ref($roles) eq 'ARRAY');
 6251:     my $now = time;
 6252:     my %dompersonnel = &get_domain_roles($dom,$roles,$now,$now);
 6253:     my %domroles;
 6254:     foreach my $server (keys(%dompersonnel)) {
 6255:         foreach my $user (sort(keys(%{$dompersonnel{$server}}))) {
 6256:             my ($trole,$uname,$udom,$runame,$rudom,$rsec) = split(/:/,$user);
 6257:             $domroles{$uname.':'.$udom} = $dompersonnel{$server}{$user};
 6258:         }
 6259:     }
 6260:     return %domroles;
 6261: }
 6262: 
 6263: # ----------------------------------------------------------- Interval timing 
 6264: 
 6265: {
 6266: # Caches needed for speedup of navmaps
 6267: # We don't want to cache this for very long at all (5 seconds at most)
 6268: # 
 6269: # The user for whom we cache
 6270: my $cachedkey='';
 6271: # The cached times for this user
 6272: my %cachedtimes=();
 6273: # When this was last done
 6274: my $cachedtime='';
 6275: 
 6276: sub load_all_first_access {
 6277:     my ($uname,$udom,$ignorecache)=@_;
 6278:     if (($cachedkey eq $uname.':'.$udom) &&
 6279:         (abs($cachedtime-time)<5) && (!$env{'form.markaccess'}) &&
 6280:         (!$ignorecache)) {
 6281:         return;
 6282:     }
 6283:     $cachedtime=time;
 6284:     $cachedkey=$uname.':'.$udom;
 6285:     %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
 6286: }
 6287: 
 6288: sub get_first_access {
 6289:     my ($type,$argsymb,$argmap,$ignorecache)=@_;
 6290:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 6291:     if ($argsymb) { $symb=$argsymb; }
 6292:     my ($map,$id,$res)=&decode_symb($symb);
 6293:     if ($argmap) { $map = $argmap; }
 6294:     if ($type eq 'course') {
 6295: 	$res='course';
 6296:     } elsif ($type eq 'map') {
 6297: 	$res=&symbread($map);
 6298:     } else {
 6299: 	$res=$symb;
 6300:     }
 6301:     &load_all_first_access($uname,$udom,$ignorecache);
 6302:     return $cachedtimes{"$courseid\0$res"};
 6303: }
 6304: 
 6305: sub set_first_access {
 6306:     my ($type,$interval)=@_;
 6307:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 6308:     my ($map,$id,$res)=&decode_symb($symb);
 6309:     if ($type eq 'course') {
 6310: 	$res='course';
 6311:     } elsif ($type eq 'map') {
 6312: 	$res=&symbread($map);
 6313:     } else {
 6314: 	$res=$symb;
 6315:     }
 6316:     $cachedkey='';
 6317:     my $firstaccess=&get_first_access($type,$symb,$map);
 6318:     if ($firstaccess) {
 6319:         &logthis("First access time already set ($firstaccess) when attempting ".
 6320:                  "to set new value (type: $type, extent: $res) for $uname:$udom ".
 6321:                  "in $courseid");
 6322:         return 'already_set';
 6323:     } else {
 6324:         my $start = time;
 6325: 	my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
 6326:                           $udom,$uname);
 6327:         if ($putres eq 'ok') {
 6328:             &put('timerinterval',{"$courseid\0$res"=>$interval},
 6329:                  $udom,$uname); 
 6330:             &appenv(
 6331:                      {
 6332:                         'course.'.$courseid.'.firstaccess.'.$res   => $start,
 6333:                         'course.'.$courseid.'.timerinterval.'.$res => $interval,
 6334:                      }
 6335:                   );
 6336:             if (($cachedtime) && (abs($start-$cachedtime) < 5)) {
 6337:                 $cachedtimes{"$courseid\0$res"} = $start;
 6338:             }
 6339:         } elsif ($putres ne 'refused') {
 6340:             &logthis("Result: $putres when attempting to set first access time ".
 6341:                      "(type: $type, extent: $res) for $uname:$udom in $courseid");
 6342:         }
 6343:         return $putres;
 6344:     }
 6345:     return 'already_set';
 6346: }
 6347: }
 6348: 
 6349: # --------------------------------------------- Set Expire Date for Spreadsheet
 6350: 
 6351: sub expirespread {
 6352:     my ($uname,$udom,$stype,$usymb)=@_;
 6353:     my $cid=$env{'request.course.id'}; 
 6354:     if ($cid) {
 6355:        my $now=time;
 6356:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
 6357:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
 6358:                             $env{'course.'.$cid.'.num'}.
 6359: 	        	    ':nohist_expirationdates:'.
 6360:                             &escape($key).'='.$now,
 6361:                             $env{'course.'.$cid.'.home'})
 6362:     }
 6363:     return 'ok';
 6364: }
 6365: 
 6366: # ----------------------------------------------------- Devalidate Spreadsheets
 6367: 
 6368: sub devalidate {
 6369:     my ($symb,$uname,$udom)=@_;
 6370:     my $cid=$env{'request.course.id'}; 
 6371:     if ($cid) {
 6372:         # delete the stored spreadsheets for
 6373:         # - the student level sheet of this user in course's homespace
 6374:         # - the assessment level sheet for this resource 
 6375:         #   for this user in user's homespace
 6376: 	# - current conditional state info
 6377: 	my $key=$uname.':'.$udom.':';
 6378:         my $status=
 6379: 	    &del('nohist_calculatedsheets',
 6380: 		 [$key.'studentcalc:'],
 6381: 		 $env{'course.'.$cid.'.domain'},
 6382: 		 $env{'course.'.$cid.'.num'})
 6383: 		.' '.
 6384: 	    &del('nohist_calculatedsheets_'.$cid,
 6385: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
 6386:         unless ($status eq 'ok ok') {
 6387:            &logthis('Could not devalidate spreadsheet '.
 6388:                     $uname.' at '.$udom.' for '.
 6389: 		    $symb.': '.$status);
 6390:         }
 6391: 	&delenv('user.state.'.$cid);
 6392:     }
 6393: }
 6394: 
 6395: sub get_scalar {
 6396:     my ($string,$end) = @_;
 6397:     my $value;
 6398:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
 6399: 	$value = $1;
 6400:     } elsif ($$string =~ s/^([^&]*?)&//) {
 6401: 	$value = $1;
 6402:     }
 6403:     return &unescape($value);
 6404: }
 6405: 
 6406: sub array2str {
 6407:   my (@array) = @_;
 6408:   my $result=&arrayref2str(\@array);
 6409:   $result=~s/^__ARRAY_REF__//;
 6410:   $result=~s/__END_ARRAY_REF__$//;
 6411:   return $result;
 6412: }
 6413: 
 6414: sub arrayref2str {
 6415:   my ($arrayref) = @_;
 6416:   my $result='__ARRAY_REF__';
 6417:   foreach my $elem (@$arrayref) {
 6418:     if(ref($elem) eq 'ARRAY') {
 6419:       $result.=&arrayref2str($elem).'&';
 6420:     } elsif(ref($elem) eq 'HASH') {
 6421:       $result.=&hashref2str($elem).'&';
 6422:     } elsif(ref($elem)) {
 6423:       #print("Got a ref of ".(ref($elem))." skipping.");
 6424:     } else {
 6425:       $result.=&escape($elem).'&';
 6426:     }
 6427:   }
 6428:   $result=~s/\&$//;
 6429:   $result .= '__END_ARRAY_REF__';
 6430:   return $result;
 6431: }
 6432: 
 6433: sub hash2str {
 6434:   my (%hash) = @_;
 6435:   my $result=&hashref2str(\%hash);
 6436:   $result=~s/^__HASH_REF__//;
 6437:   $result=~s/__END_HASH_REF__$//;
 6438:   return $result;
 6439: }
 6440: 
 6441: sub hashref2str {
 6442:   my ($hashref)=@_;
 6443:   my $result='__HASH_REF__';
 6444:   foreach my $key (sort(keys(%$hashref))) {
 6445:     if (ref($key) eq 'ARRAY') {
 6446:       $result.=&arrayref2str($key).'=';
 6447:     } elsif (ref($key) eq 'HASH') {
 6448:       $result.=&hashref2str($key).'=';
 6449:     } elsif (ref($key)) {
 6450:       $result.='=';
 6451:       #print("Got a ref of ".(ref($key))." skipping.");
 6452:     } else {
 6453: 	if (defined($key)) {$result.=&escape($key).'=';} else { last; }
 6454:     }
 6455: 
 6456:     if(ref($hashref->{$key}) eq 'ARRAY') {
 6457:       $result.=&arrayref2str($hashref->{$key}).'&';
 6458:     } elsif(ref($hashref->{$key}) eq 'HASH') {
 6459:       $result.=&hashref2str($hashref->{$key}).'&';
 6460:     } elsif(ref($hashref->{$key})) {
 6461:        $result.='&';
 6462:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
 6463:     } else {
 6464:       $result.=&escape($hashref->{$key}).'&';
 6465:     }
 6466:   }
 6467:   $result=~s/\&$//;
 6468:   $result .= '__END_HASH_REF__';
 6469:   return $result;
 6470: }
 6471: 
 6472: sub str2hash {
 6473:     my ($string)=@_;
 6474:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
 6475:     return %$hash;
 6476: }
 6477: 
 6478: sub str2hashref {
 6479:   my ($string) = @_;
 6480: 
 6481:   my %hash;
 6482: 
 6483:   if($string !~ /^__HASH_REF__/) {
 6484:       if (! ($string eq '' || !defined($string))) {
 6485: 	  $hash{'error'}='Not hash reference';
 6486:       }
 6487:       return (\%hash, $string);
 6488:   }
 6489: 
 6490:   $string =~ s/^__HASH_REF__//;
 6491: 
 6492:   while($string !~ /^__END_HASH_REF__/) {
 6493:       #key
 6494:       my $key='';
 6495:       if($string =~ /^__HASH_REF__/) {
 6496:           ($key, $string)=&str2hashref($string);
 6497:           if(defined($key->{'error'})) {
 6498:               $hash{'error'}='Bad data';
 6499:               return (\%hash, $string);
 6500:           }
 6501:       } elsif($string =~ /^__ARRAY_REF__/) {
 6502:           ($key, $string)=&str2arrayref($string);
 6503:           if($key->[0] eq 'Array reference error') {
 6504:               $hash{'error'}='Bad data';
 6505:               return (\%hash, $string);
 6506:           }
 6507:       } else {
 6508:           $string =~ s/^(.*?)=//;
 6509: 	  $key=&unescape($1);
 6510:       }
 6511:       $string =~ s/^=//;
 6512: 
 6513:       #value
 6514:       my $value='';
 6515:       if($string =~ /^__HASH_REF__/) {
 6516:           ($value, $string)=&str2hashref($string);
 6517:           if(defined($value->{'error'})) {
 6518:               $hash{'error'}='Bad data';
 6519:               return (\%hash, $string);
 6520:           }
 6521:       } elsif($string =~ /^__ARRAY_REF__/) {
 6522:           ($value, $string)=&str2arrayref($string);
 6523:           if($value->[0] eq 'Array reference error') {
 6524:               $hash{'error'}='Bad data';
 6525:               return (\%hash, $string);
 6526:           }
 6527:       } else {
 6528: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
 6529:       }
 6530:       $string =~ s/^&//;
 6531: 
 6532:       $hash{$key}=$value;
 6533:   }
 6534: 
 6535:   $string =~ s/^__END_HASH_REF__//;
 6536: 
 6537:   return (\%hash, $string);
 6538: }
 6539: 
 6540: sub str2array {
 6541:     my ($string)=@_;
 6542:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
 6543:     return @$array;
 6544: }
 6545: 
 6546: sub str2arrayref {
 6547:   my ($string) = @_;
 6548:   my @array;
 6549: 
 6550:   if($string !~ /^__ARRAY_REF__/) {
 6551:       if (! ($string eq '' || !defined($string))) {
 6552: 	  $array[0]='Array reference error';
 6553:       }
 6554:       return (\@array, $string);
 6555:   }
 6556: 
 6557:   $string =~ s/^__ARRAY_REF__//;
 6558: 
 6559:   while($string !~ /^__END_ARRAY_REF__/) {
 6560:       my $value='';
 6561:       if($string =~ /^__HASH_REF__/) {
 6562:           ($value, $string)=&str2hashref($string);
 6563:           if(defined($value->{'error'})) {
 6564:               $array[0] ='Array reference error';
 6565:               return (\@array, $string);
 6566:           }
 6567:       } elsif($string =~ /^__ARRAY_REF__/) {
 6568:           ($value, $string)=&str2arrayref($string);
 6569:           if($value->[0] eq 'Array reference error') {
 6570:               $array[0] ='Array reference error';
 6571:               return (\@array, $string);
 6572:           }
 6573:       } else {
 6574: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
 6575:       }
 6576:       $string =~ s/^&//;
 6577: 
 6578:       push(@array, $value);
 6579:   }
 6580: 
 6581:   $string =~ s/^__END_ARRAY_REF__//;
 6582: 
 6583:   return (\@array, $string);
 6584: }
 6585: 
 6586: # -------------------------------------------------------------------Temp Store
 6587: 
 6588: sub tmpreset {
 6589:   my ($symb,$namespace,$domain,$stuname) = @_;
 6590:   if (!$symb) {
 6591:     $symb=&symbread();
 6592:     if (!$symb) { $symb= $env{'request.url'}; }
 6593:   }
 6594:   $symb=escape($symb);
 6595: 
 6596:   if (!$namespace) { $namespace=$env{'request.state'}; }
 6597:   $namespace=~s/\//\_/g;
 6598:   $namespace=~s/\W//g;
 6599: 
 6600:   if (!$domain) { $domain=$env{'user.domain'}; }
 6601:   if (!$stuname) { $stuname=$env{'user.name'}; }
 6602:   if ($domain eq 'public' && $stuname eq 'public') {
 6603:       $stuname=&get_requestor_ip();
 6604:   }
 6605:   my $path=LONCAPA::tempdir();
 6606:   my %hash;
 6607:   if (tie(%hash,'GDBM_File',
 6608: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 6609: 	  &GDBM_WRCREAT(),0640)) {
 6610:     foreach my $key (keys(%hash)) {
 6611:       if ($key=~ /:$symb/) {
 6612: 	delete($hash{$key});
 6613:       }
 6614:     }
 6615:   }
 6616: }
 6617: 
 6618: sub tmpstore {
 6619:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 6620: 
 6621:   if (!$symb) {
 6622:     $symb=&symbread();
 6623:     if (!$symb) { $symb= $env{'request.url'}; }
 6624:   }
 6625:   $symb=escape($symb);
 6626: 
 6627:   if (!$namespace) {
 6628:     # I don't think we would ever want to store this for a course.
 6629:     # it seems this will only be used if we don't have a course.
 6630:     #$namespace=$env{'request.course.id'};
 6631:     #if (!$namespace) {
 6632:       $namespace=$env{'request.state'};
 6633:     #}
 6634:   }
 6635:   $namespace=~s/\//\_/g;
 6636:   $namespace=~s/\W//g;
 6637:   if (!$domain) { $domain=$env{'user.domain'}; }
 6638:   if (!$stuname) { $stuname=$env{'user.name'}; }
 6639:   if ($domain eq 'public' && $stuname eq 'public') {
 6640:       $stuname=&get_requestor_ip();
 6641:   }
 6642:   my $now=time;
 6643:   my %hash;
 6644:   my $path=LONCAPA::tempdir();
 6645:   if (tie(%hash,'GDBM_File',
 6646: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 6647: 	  &GDBM_WRCREAT(),0640)) {
 6648:     $hash{"version:$symb"}++;
 6649:     my $version=$hash{"version:$symb"};
 6650:     my $allkeys=''; 
 6651:     foreach my $key (keys(%$storehash)) {
 6652:       $allkeys.=$key.':';
 6653:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
 6654:     }
 6655:     $hash{"$version:$symb:timestamp"}=$now;
 6656:     $allkeys.='timestamp';
 6657:     $hash{"$version:keys:$symb"}=$allkeys;
 6658:     if (untie(%hash)) {
 6659:       return 'ok';
 6660:     } else {
 6661:       return "error:$!";
 6662:     }
 6663:   } else {
 6664:     return "error:$!";
 6665:   }
 6666: }
 6667: 
 6668: # -----------------------------------------------------------------Temp Restore
 6669: 
 6670: sub tmprestore {
 6671:   my ($symb,$namespace,$domain,$stuname) = @_;
 6672: 
 6673:   if (!$symb) {
 6674:     $symb=&symbread();
 6675:     if (!$symb) { $symb= $env{'request.url'}; }
 6676:   }
 6677:   $symb=escape($symb);
 6678: 
 6679:   if (!$namespace) { $namespace=$env{'request.state'}; }
 6680: 
 6681:   if (!$domain) { $domain=$env{'user.domain'}; }
 6682:   if (!$stuname) { $stuname=$env{'user.name'}; }
 6683:   if ($domain eq 'public' && $stuname eq 'public') {
 6684:       $stuname=&get_requestor_ip();
 6685:   }
 6686:   my %returnhash;
 6687:   $namespace=~s/\//\_/g;
 6688:   $namespace=~s/\W//g;
 6689:   my %hash;
 6690:   my $path=LONCAPA::tempdir();
 6691:   if (tie(%hash,'GDBM_File',
 6692: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 6693: 	  &GDBM_READER(),0640)) {
 6694:     my $version=$hash{"version:$symb"};
 6695:     $returnhash{'version'}=$version;
 6696:     my $scope;
 6697:     for ($scope=1;$scope<=$version;$scope++) {
 6698:       my $vkeys=$hash{"$scope:keys:$symb"};
 6699:       my @keys=split(/:/,$vkeys);
 6700:       my $key;
 6701:       $returnhash{"$scope:keys"}=$vkeys;
 6702:       foreach $key (@keys) {
 6703: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 6704: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 6705:       }
 6706:     }
 6707:     if (!(untie(%hash))) {
 6708:       return "error:$!";
 6709:     }
 6710:   } else {
 6711:     return "error:$!";
 6712:   }
 6713:   return %returnhash;
 6714: }
 6715: 
 6716: # ----------------------------------------------------------------------- Store
 6717: 
 6718: sub store {
 6719:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
 6720:     my $home='';
 6721: 
 6722:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 6723: 
 6724:     $symb=&symbclean($symb);
 6725:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 6726: 
 6727:     if (!$domain) { $domain=$env{'user.domain'}; }
 6728:     if (!$stuname) { $stuname=$env{'user.name'}; }
 6729: 
 6730:     &devalidate($symb,$stuname,$domain);
 6731: 
 6732:     $symb=escape($symb);
 6733:     if (!$namespace) { 
 6734:        unless ($namespace=$env{'request.course.id'}) { 
 6735:           return ''; 
 6736:        } 
 6737:     }
 6738:     if (!$home) { $home=$env{'user.home'}; }
 6739: 
 6740:     $$storehash{'ip'}=&get_requestor_ip();
 6741:     $$storehash{'host'}=$perlvar{'lonHostID'};
 6742: 
 6743:     my $namevalue='';
 6744:     foreach my $key (keys(%$storehash)) {
 6745:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 6746:     }
 6747:     $namevalue=~s/\&$//;
 6748:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
 6749:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
 6750: }
 6751: 
 6752: # -------------------------------------------------------------- Critical Store
 6753: 
 6754: sub cstore {
 6755:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
 6756:     my $home='';
 6757: 
 6758:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 6759: 
 6760:     unless (($symb eq '_feedback') || ($symb eq '_discussion')) {
 6761:         $symb=&symbclean($symb);
 6762:     }
 6763:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 6764: 
 6765:     if (!$domain) { $domain=$env{'user.domain'}; }
 6766:     if (!$stuname) { $stuname=$env{'user.name'}; }
 6767: 
 6768:     unless (($symb eq '_feedback') || ($symb eq '_discussion')) {
 6769:         &devalidate($symb,$stuname,$domain);
 6770:     }
 6771: 
 6772:     $symb=escape($symb);
 6773:     if (!$namespace) { 
 6774:        unless ($namespace=$env{'request.course.id'}) { 
 6775:           return ''; 
 6776:        } 
 6777:     }
 6778:     if (!$home) { $home=$env{'user.home'}; }
 6779: 
 6780:     $$storehash{'ip'} = &get_requestor_ip();
 6781:     $$storehash{'host'}=$perlvar{'lonHostID'};
 6782: 
 6783:     my $namevalue='';
 6784:     foreach my $key (keys(%$storehash)) {
 6785:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 6786:     }
 6787:     $namevalue=~s/\&$//;
 6788:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
 6789:     return critical
 6790:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
 6791: }
 6792: 
 6793: # --------------------------------------------------------------------- Restore
 6794: 
 6795: sub restore {
 6796:     my ($symb,$namespace,$domain,$stuname) = @_;
 6797:     my $home='';
 6798: 
 6799:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 6800: 
 6801:     if (!$symb) {
 6802:         return if ($namespace eq 'courserequests');
 6803:         unless ($symb=escape(&symbread())) { return ''; }
 6804:     } else {
 6805:         unless ($namespace eq 'courserequests') {
 6806:             $symb=&escape(&symbclean($symb));
 6807:         }
 6808:     }
 6809:     if (!$namespace) { 
 6810:        unless ($namespace=$env{'request.course.id'}) { 
 6811:           return ''; 
 6812:        } 
 6813:     }
 6814:     if (!$domain) { $domain=$env{'user.domain'}; }
 6815:     if (!$stuname) { $stuname=$env{'user.name'}; }
 6816:     if (!$home) { $home=$env{'user.home'}; }
 6817:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
 6818: 
 6819:     my %returnhash=();
 6820:     foreach my $line (split(/\&/,$answer)) {
 6821: 	my ($name,$value)=split(/\=/,$line);
 6822:         $returnhash{&unescape($name)}=&thaw_unescape($value);
 6823:     }
 6824:     my $version;
 6825:     for ($version=1;$version<=$returnhash{'version'};$version++) {
 6826:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
 6827:           $returnhash{$item}=$returnhash{$version.':'.$item};
 6828:        }
 6829:     }
 6830:     return %returnhash;
 6831: }
 6832: 
 6833: # ---------------------------------------------------------- Course Description
 6834: #
 6835: #  
 6836: 
 6837: sub coursedescription {
 6838:     my ($courseid,$args)=@_;
 6839:     $courseid=~s/^\///;
 6840:     $courseid=~s/\_/\//g;
 6841:     my ($cdomain,$cnum)=split(/\//,$courseid);
 6842:     my $chome=&homeserver($cnum,$cdomain);
 6843:     my $normalid=$cdomain.'_'.$cnum;
 6844:     # need to always cache even if we get errors otherwise we keep 
 6845:     # trying and trying and trying to get the course description.
 6846:     my %envhash=();
 6847:     my %returnhash=();
 6848:     
 6849:     my $expiretime=600;
 6850:     if ($env{'request.course.id'} eq $normalid) {
 6851: 	$expiretime=120;
 6852:     }
 6853: 
 6854:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
 6855:     if (!$args->{'freshen_cache'}
 6856: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
 6857: 	foreach my $key (keys(%env)) {
 6858: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
 6859: 	    my ($setting) = $1;
 6860: 	    $returnhash{$setting} = $env{$key};
 6861: 	}
 6862: 	return %returnhash;
 6863:     }
 6864: 
 6865:     # get the data again
 6866: 
 6867:     if (!$args->{'one_time'}) {
 6868: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
 6869:     }
 6870: 
 6871:     if ($chome ne 'no_host') {
 6872:        %returnhash=&dump('environment',$cdomain,$cnum);
 6873:        if (!exists($returnhash{'con_lost'})) {
 6874: 	   my $username = $env{'user.name'}; # Defult username
 6875: 	   if(defined $args->{'user'}) {
 6876: 	       $username = $args->{'user'};
 6877: 	   }
 6878:            $returnhash{'home'}= $chome;
 6879: 	   $returnhash{'domain'} = $cdomain;
 6880: 	   $returnhash{'num'} = $cnum;
 6881:            if (!defined($returnhash{'type'})) {
 6882:                $returnhash{'type'} = 'Course';
 6883:            }
 6884:            while (my ($name,$value) = each %returnhash) {
 6885:                $envhash{'course.'.$normalid.'.'.$name}=$value;
 6886:            }
 6887:            $returnhash{'url'}=&clutter($returnhash{'url'});
 6888:            $returnhash{'fn'}=LONCAPA::tempdir() .
 6889: 	       $username.'_'.$cdomain.'_'.$cnum;
 6890:            $envhash{'course.'.$normalid.'.home'}=$chome;
 6891:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
 6892:            $envhash{'course.'.$normalid.'.num'}=$cnum;
 6893:        }
 6894:     }
 6895:     if (!$args->{'one_time'}) {
 6896: 	&appenv(\%envhash);
 6897:     }
 6898:     return %returnhash;
 6899: }
 6900: 
 6901: sub update_released_required {
 6902:     my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
 6903:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
 6904:         $cid = $env{'request.course.id'};
 6905:         $cdom = $env{'course.'.$cid.'.domain'};
 6906:         $cnum = $env{'course.'.$cid.'.num'};
 6907:         $chome = $env{'course.'.$cid.'.home'};
 6908:     }
 6909:     if ($needsrelease) {
 6910:         my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
 6911:         my $needsupdate;
 6912:         if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
 6913:             $needsupdate = 1;
 6914:         } else {
 6915:             my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
 6916:             my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
 6917:             if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
 6918:                 $needsupdate = 1;
 6919:             }
 6920:         }
 6921:         if ($needsupdate) {
 6922:             my %needshash = (
 6923:                              'internal.releaserequired' => $needsrelease,
 6924:                             );
 6925:             my $putresult = &put('environment',\%needshash,$cdom,$cnum);
 6926:             if ($putresult eq 'ok') {
 6927:                 &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
 6928:                 my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
 6929:                 if (ref($crsinfo{$cid}) eq 'HASH') {
 6930:                     $crsinfo{$cid}{'releaserequired'} = $needsrelease;
 6931:                     &courseidput($cdom,\%crsinfo,$chome,'notime');
 6932:                 }
 6933:             }
 6934:         }
 6935:     }
 6936:     return;
 6937: }
 6938: 
 6939: # -------------------------------------------------See if a user is privileged
 6940: 
 6941: sub privileged {
 6942:     my ($username,$domain,$possdomains,$possroles)=@_;
 6943:     my $now = time;
 6944:     my $roles;
 6945:     if (ref($possroles) eq 'ARRAY') {
 6946:         $roles = $possroles; 
 6947:     } else {
 6948:         $roles = ['dc','su'];
 6949:     }
 6950:     if (ref($possdomains) eq 'ARRAY') {
 6951:         my %privileged = &privileged_by_domain($possdomains,$roles);
 6952:         foreach my $dom (@{$possdomains}) {
 6953:             if (($username =~ /^$match_username$/) && ($domain =~ /^$match_domain$/) &&
 6954:                 (ref($privileged{$dom}) eq 'HASH')) {
 6955:                 foreach my $role (@{$roles}) {
 6956:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
 6957:                         if (exists($privileged{$dom}{$role}{$username.':'.$domain})) {
 6958:                             my ($end,$start) = split(/:/,$privileged{$dom}{$role}{$username.':'.$domain});
 6959:                             return 1 unless (($end && $end < $now) ||
 6960:                                              ($start && $start > $now));
 6961:                         }
 6962:                     }
 6963:                 }
 6964:             }
 6965:         }
 6966:     } else {
 6967:         my %rolesdump = &dump("roles", $domain, $username) or return 0;
 6968:         my $now = time;
 6969: 
 6970:         for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys(%rolesdump)}) {
 6971:             my ($trole, $tend, $tstart) = split(/_/, $role);
 6972:             if (grep(/^\Q$trole\E$/,@{$roles})) {
 6973:                 return 1 unless ($tend && $tend < $now) 
 6974:                         or ($tstart && $tstart > $now);
 6975:             }
 6976:         }
 6977:     }
 6978:     return 0;
 6979: }
 6980: 
 6981: sub privileged_by_domain {
 6982:     my ($domains,$roles) = @_;
 6983:     my %privileged = ();
 6984:     my $cachetime = 60*60*24;
 6985:     my $now = time;
 6986:     unless ((ref($domains) eq 'ARRAY') && (ref($roles) eq 'ARRAY')) {
 6987:         return %privileged;
 6988:     }
 6989:     foreach my $dom (@{$domains}) {
 6990:         next if (ref($privileged{$dom}) eq 'HASH');
 6991:         my $needroles;
 6992:         foreach my $role (@{$roles}) {
 6993:             my ($result,$cached)=&is_cached_new('priv_'.$role,$dom);
 6994:             if (defined($cached)) {
 6995:                 if (ref($result) eq 'HASH') {
 6996:                     $privileged{$dom}{$role} = $result;
 6997:                 }
 6998:             } else {
 6999:                 $needroles = 1;
 7000:             }
 7001:         }
 7002:         if ($needroles) {
 7003:             my %dompersonnel = &get_domain_roles($dom,$roles);
 7004:             $privileged{$dom} = {};
 7005:             foreach my $server (keys(%dompersonnel)) {
 7006:                 if (ref($dompersonnel{$server}) eq 'HASH') {
 7007:                     foreach my $item (keys(%{$dompersonnel{$server}})) {
 7008:                         my ($trole,$uname,$udom,$rest) = split(/:/,$item,4);
 7009:                         my ($end,$start) = split(/:/,$dompersonnel{$server}{$item});
 7010:                         next if ($end && $end < $now);
 7011:                         $privileged{$dom}{$trole}{$uname.':'.$udom} = 
 7012:                             $dompersonnel{$server}{$item};
 7013:                     }
 7014:                 }
 7015:             }
 7016:             if (ref($privileged{$dom}) eq 'HASH') {
 7017:                 foreach my $role (@{$roles}) {
 7018:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
 7019:                         &do_cache_new('priv_'.$role,$dom,$privileged{$dom}{$role},$cachetime);
 7020:                     } else {
 7021:                         my %hash = ();
 7022:                         &do_cache_new('priv_'.$role,$dom,\%hash,$cachetime);
 7023:                     }
 7024:                 }
 7025:             }
 7026:         }
 7027:     }
 7028:     return %privileged;
 7029: }
 7030: 
 7031: # -------------------------------------------------------- Get user privileges
 7032: 
 7033: sub rolesinit {
 7034:     my ($domain, $username) = @_;
 7035:     my %userroles = ('user.login.time' => time);
 7036:     my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
 7037: 
 7038:     # firstaccess and timerinterval are related to timed maps/resources. 
 7039:     # also, blocking can be triggered by an activating timer
 7040:     # it's saved in the user's %env.
 7041:     my %firstaccess = &dump('firstaccesstimes', $domain, $username);
 7042:     my %timerinterval = &dump('timerinterval', $domain, $username);
 7043:     my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
 7044:         %timerintchk, %timerintenv, %coauthorenv);
 7045: 
 7046:     foreach my $key (keys(%firstaccess)) {
 7047:         my ($cid, $rest) = split(/\0/, $key);
 7048:         $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
 7049:     }
 7050: 
 7051:     foreach my $key (keys(%timerinterval)) {
 7052:         my ($cid,$rest) = split(/\0/,$key);
 7053:         $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
 7054:     }
 7055: 
 7056:     my %allroles=();
 7057:     my %allgroups=();
 7058:     my %gotcoauconfig=();
 7059:     my %domdefaults=();
 7060: 
 7061:     for my $area (grep { ! /^rolesdef_/ } keys(%rolesdump)) {
 7062:         my $role = $rolesdump{$area};
 7063:         $area =~ s/\_\w\w$//;
 7064: 
 7065:         my ($trole, $tend, $tstart, $group_privs);
 7066: 
 7067:         if ($role =~ /^cr/) {
 7068:         # Custom role, defined by a user 
 7069:         # e.g., user.role.cr/msu/smith/mynewrole
 7070:             if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
 7071:                 $trole = $1;
 7072:                 ($tend, $tstart) = split('_', $2);
 7073:             } else {
 7074:                 $trole = $role;
 7075:             }
 7076:         } elsif ($role =~ m|^gr/|) {
 7077:         # Role of member in a group, defined within a course/community
 7078:         # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
 7079:             ($trole, $tend, $tstart) = split(/_/, $role);
 7080:             next if $tstart eq '-1';
 7081:             ($trole, $group_privs) = split(/\//, $trole);
 7082:             $group_privs = &unescape($group_privs);
 7083:         } else {
 7084:         # Just a normal role, defined in roles.tab
 7085:             ($trole, $tend, $tstart) = split(/_/,$role);
 7086:         }
 7087: 
 7088:         my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
 7089:                  $username);
 7090:         @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
 7091: 
 7092:         # role expired or not available yet?
 7093:         $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or 
 7094:             ($tstart != 0 && $tstart > $userroles{'user.login.time'});
 7095: 
 7096:         next if $area eq '' or $trole eq '';
 7097: 
 7098:         my $spec = "$trole.$area";
 7099:         my ($tdummy, $tdomain, $trest) = split(/\//, $area);
 7100: 
 7101:         if ($trole =~ /^cr\//) {
 7102:         # Custom role, defined by a user
 7103:             &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
 7104:         } elsif ($trole eq 'gr') {
 7105:         # Role of a member in a group, defined within a course/community
 7106:             &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
 7107:             next;
 7108:         } else {
 7109:         # Normal role, defined in roles.tab
 7110:             &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
 7111:             if (($trole eq 'ca') || ($trole eq 'aa')) {
 7112:                 (undef,my ($audom,$auname)) = split(/\//,$area);
 7113:                 unless ($gotcoauconfig{$area}) {
 7114:                     my @ca_settings = ('authoreditors','coauthorlist','coauthoroptin');
 7115:                     my %info = &userenvironment($audom,$auname,@ca_settings);
 7116:                     $gotcoauconfig{$area} = 1;
 7117:                     foreach my $item (@ca_settings) {
 7118:                         if (exists($info{$item})) {
 7119:                             my $name = $item;
 7120:                             if ($item eq 'authoreditors') {
 7121:                                 $name = 'editors';
 7122:                                 unless ($info{'authoreditors'}) {
 7123:                                     my %domdefs;
 7124:                                     if (ref($domdefaults{$audom}) eq 'HASH') {
 7125:                                         %domdefs = %{$domdefaults{$audom}};
 7126:                                     } else {
 7127:                                         %domdefs = &get_domain_defaults($audom);
 7128:                                         $domdefaults{$audom} = \%domdefs;
 7129:                                     }
 7130:                                     if ($domdefs{$name} ne '') {
 7131:                                         $info{'authoreditors'} = $domdefs{$name};
 7132:                                     } else {
 7133:                                         $info{'authoreditors'} = 'edit,xml';
 7134:                                     }
 7135:                                 }
 7136:                             }
 7137:                             $coauthorenv{"environment.internal.$name.$area"} = $info{$item};
 7138:                         }
 7139:                     }
 7140:                 }
 7141:             }
 7142:         }
 7143: 
 7144:         my $cid = $tdomain.'_'.$trest;
 7145:         unless ($firstaccchk{$cid}) {
 7146:             if (ref($coursetimerstarts{$cid}) eq 'HASH') {
 7147:                 foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
 7148:                     $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} = 
 7149:                         $coursetimerstarts{$cid}{$item}; 
 7150:                 }
 7151:             }
 7152:             $firstaccchk{$cid} = 1;
 7153:         }
 7154:         unless ($timerintchk{$cid}) {
 7155:             if (ref($coursetimerintervals{$cid}) eq 'HASH') {
 7156:                 foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
 7157:                     $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
 7158:                        $coursetimerintervals{$cid}{$item};
 7159:                 }
 7160:             }
 7161:             $timerintchk{$cid} = 1;
 7162:         }
 7163:     }
 7164: 
 7165:     @userroles{'user.author','user.adv','user.rar'} = &set_userprivs(\%userroles,
 7166:                                                           \%allroles, \%allgroups);
 7167:     $env{'user.adv'} = $userroles{'user.adv'};
 7168:     $env{'user.rar'} = $userroles{'user.rar'};
 7169: 
 7170:     return (\%userroles,\%firstaccenv,\%timerintenv,\%coauthorenv);
 7171: }
 7172: 
 7173: sub set_arearole {
 7174:     my ($trole,$area,$tstart,$tend,$domain,$username,$nolog) = @_;
 7175:     unless ($nolog) {
 7176: # log the associated role with the area
 7177:         &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
 7178:     }
 7179:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
 7180: }
 7181: 
 7182: sub custom_roleprivs {
 7183:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
 7184:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
 7185:     my $homsvr = &homeserver($rauthor,$rdomain);
 7186:     if (&hostname($homsvr) ne '') {
 7187:         my ($rdummy,$roledef)=
 7188:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
 7189:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
 7190:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
 7191:             if (defined($syspriv)) {
 7192:                 if ($trest =~ /^$match_community$/) {
 7193:                     $syspriv =~ s/bre\&S//; 
 7194:                 }
 7195:                 $$allroles{'cm./'}.=':'.$syspriv;
 7196:                 $$allroles{$spec.'./'}.=':'.$syspriv;
 7197:             }
 7198:             if ($tdomain ne '') {
 7199:                 if (defined($dompriv)) {
 7200:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
 7201:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
 7202:                 }
 7203:                 if (($trest ne '') && (defined($coursepriv))) {
 7204:                     if ($trole =~ m{^cr/$tdomain/$tdomain\Q-domainconfig\E/([^/]+)$}) {
 7205:                         my $rolename = $1;
 7206:                         $coursepriv = &course_adhocrole_privs($rolename,$tdomain,$trest,$coursepriv);
 7207:                     }
 7208:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
 7209:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
 7210:                 }
 7211:             }
 7212:         }
 7213:     }
 7214: }
 7215: 
 7216: sub course_adhocrole_privs {
 7217:     my ($rolename,$cdom,$cnum,$coursepriv) = @_;
 7218:     my %overrides = &get('environment',["internal.adhocpriv.$rolename"],$cdom,$cnum);
 7219:     if ($overrides{"internal.adhocpriv.$rolename"}) {
 7220:         my (%currprivs,%storeprivs);
 7221:         foreach my $item (split(/:/,$coursepriv)) {
 7222:             my ($priv,$restrict) = split(/\&/,$item);
 7223:             $currprivs{$priv} = $restrict;
 7224:         }
 7225:         my (%possadd,%possremove,%full);
 7226:         foreach my $item (split(/\:/,$Apache::lonnet::pr{'cr:c'})) {
 7227:             my ($priv,$restrict)=split(/\&/,$item);
 7228:             $full{$priv} = $restrict;
 7229:         }
 7230:         foreach my $item (split(/,/,$overrides{"internal.adhocpriv.$rolename"})) {
 7231:             next if ($item eq '');
 7232:             my ($rule,$rest) = split(/=/,$item);
 7233:             next unless (($rule eq 'off') || ($rule eq 'on'));
 7234:             foreach my $priv (split(/:/,$rest)) {
 7235:                 if ($priv ne '') {
 7236:                     if ($rule eq 'off') {
 7237:                         $possremove{$priv} = 1;
 7238:                     } else {
 7239:                         $possadd{$priv} = 1;
 7240:                     }
 7241:                 }
 7242:             }
 7243:         }
 7244:         foreach my $priv (sort(keys(%full))) {
 7245:             if (exists($currprivs{$priv})) {
 7246:                 unless (exists($possremove{$priv})) {
 7247:                     $storeprivs{$priv} = $currprivs{$priv};
 7248:                 }
 7249:             } elsif (exists($possadd{$priv})) {
 7250:                 $storeprivs{$priv} = $full{$priv};
 7251:             }
 7252:         }
 7253:         $coursepriv = ':'.join(':',map { $_.'&'.$storeprivs{$_}; } sort(keys(%storeprivs)));
 7254:     }
 7255:     return $coursepriv;
 7256: }
 7257: 
 7258: sub group_roleprivs {
 7259:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
 7260:     my $access = 1;
 7261:     my $now = time;
 7262:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
 7263:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
 7264:     if ($access) {
 7265:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
 7266:         $$allgroups{$course}{$group} .=':'.$group_privs;
 7267:     }
 7268: }
 7269: 
 7270: sub standard_roleprivs {
 7271:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
 7272:     if (defined($pr{$trole.':s'})) {
 7273:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
 7274:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
 7275:     }
 7276:     if ($tdomain ne '') {
 7277:         if (defined($pr{$trole.':d'})) {
 7278:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 7279:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 7280:         }
 7281:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
 7282:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
 7283:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
 7284:         }
 7285:     }
 7286: }
 7287: 
 7288: sub set_userprivs {
 7289:     my ($userroles,$allroles,$allgroups,$groups_roles) = @_; 
 7290:     my $author=0;
 7291:     my $adv=0;
 7292:     my $rar=0;
 7293:     my %grouproles = ();
 7294:     if (keys(%{$allgroups}) > 0) {
 7295:         my @groupkeys; 
 7296:         foreach my $role (keys(%{$allroles})) {
 7297:             push(@groupkeys,$role);
 7298:         }
 7299:         if (ref($groups_roles) eq 'HASH') {
 7300:             foreach my $key (keys(%{$groups_roles})) {
 7301:                 unless (grep(/^\Q$key\E$/,@groupkeys)) {
 7302:                     push(@groupkeys,$key);
 7303:                 }
 7304:             }
 7305:         }
 7306:         if (@groupkeys > 0) {
 7307:             foreach my $role (@groupkeys) {
 7308:                 my ($trole,$area,$sec,$extendedarea);
 7309:                 if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
 7310:                     $trole = $1;
 7311:                     $area = $2;
 7312:                     $sec = $3;
 7313:                     $extendedarea = $area.$sec;
 7314:                     if (exists($$allgroups{$area})) {
 7315:                         foreach my $group (keys(%{$$allgroups{$area}})) {
 7316:                             my $spec = $trole.'.'.$extendedarea;
 7317:                             $grouproles{$spec.'.'.$area.'/'.$group} = 
 7318:                                                 $$allgroups{$area}{$group};
 7319:                         }
 7320:                     }
 7321:                 }
 7322:             }
 7323:         }
 7324:     }
 7325:     foreach my $group (keys(%grouproles)) {
 7326:         $$allroles{$group} = $grouproles{$group};
 7327:     }
 7328:     foreach my $role (keys(%{$allroles})) {
 7329:         my %thesepriv;
 7330:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
 7331:         foreach my $item (split(/:/,$$allroles{$role})) {
 7332:             if ($item ne '') {
 7333:                 my ($privilege,$restrictions)=split(/&/,$item);
 7334:                 if ($restrictions eq '') {
 7335:                     $thesepriv{$privilege}='F';
 7336:                 } elsif ($thesepriv{$privilege} ne 'F') {
 7337:                     $thesepriv{$privilege}.=$restrictions;
 7338:                 }
 7339:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
 7340:                 if ($thesepriv{'rar'} eq 'F') { $rar=1; }
 7341:             }
 7342:         }
 7343:         my $thesestr='';
 7344:         foreach my $priv (sort(keys(%thesepriv))) {
 7345: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
 7346: 	}
 7347:         $userroles->{'user.priv.'.$role} = $thesestr;
 7348:     }
 7349:     return ($author,$adv,$rar);
 7350: }
 7351: 
 7352: sub role_status {
 7353:     my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
 7354:     if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
 7355:         my ($one,$two) = split(m{\./},$rolekey,2);
 7356:         (undef,undef,$$role) = split(/\./,$one,3);
 7357:         unless (!defined($$role) || $$role eq '') {
 7358:             $$where = '/'.$two;
 7359:             $$trolecode=$$role.'.'.$$where;
 7360:             ($$tstart,$$tend)=split(/\./,$env{$rolekey});
 7361:             $$tstatus='is';
 7362:             if ($$tstart && $$tstart>$update) {
 7363:                 $$tstatus='future';
 7364:                 if ($$tstart<$now) {
 7365:                     if ($$tstart && $$tstart>$refresh) {
 7366:                         if (($$where ne '') && ($$role ne '')) {
 7367:                             my (%allroles,%allgroups,$group_privs,
 7368:                                 %groups_roles,@rolecodes);
 7369:                             my %userroles = (
 7370:                                 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
 7371:                             );
 7372:                             @rolecodes = ('cm'); 
 7373:                             my $spec=$$role.'.'.$$where;
 7374:                             my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
 7375:                             if ($$role =~ /^cr\//) {
 7376:                                 &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
 7377:                                 push(@rolecodes,'cr');
 7378:                             } elsif ($$role eq 'gr') {
 7379:                                 push(@rolecodes,$$role);
 7380:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
 7381:                                                     $env{'user.name'});
 7382:                                 my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
 7383:                                 (undef,my $group_privs) = split(/\//,$trole);
 7384:                                 $group_privs = &unescape($group_privs);
 7385:                                 &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
 7386:                                 my %course_roles = &get_my_roles($env{'user.name'},$env{'user.domain'},'userroles',['active'],['cc','co','in','ta','ep','ad','st','cr'],[$tdomain],1);
 7387:                                 &get_groups_roles($tdomain,$trest,
 7388:                                                   \%course_roles,\@rolecodes,
 7389:                                                   \%groups_roles);
 7390:                             } else {
 7391:                                 push(@rolecodes,$$role);
 7392:                                 &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
 7393:                             }
 7394:                             my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%allroles,\%allgroups,
 7395:                                                                    \%groups_roles);
 7396:                             &appenv(\%userroles,\@rolecodes);
 7397:                             &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
 7398:                         }
 7399:                     }
 7400:                     $$tstatus = 'is';
 7401:                 }
 7402:             }
 7403:             if ($$tend) {
 7404:                 if ($$tend<$update) {
 7405:                     $$tstatus='expired';
 7406:                 } elsif ($$tend<$now) {
 7407:                     $$tstatus='will_not';
 7408:                 }
 7409:             }
 7410:         }
 7411:     }
 7412: }
 7413: 
 7414: sub get_groups_roles {
 7415:     my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
 7416:     return unless((ref($cdom_courseroles) eq 'HASH') && 
 7417:                   (ref($rolecodes) eq 'ARRAY') && 
 7418:                   (ref($groups_roles) eq 'HASH')); 
 7419:     if (keys(%{$cdom_courseroles}) > 0) {
 7420:         my ($cnum) = ($rest =~ /^($match_courseid)/);
 7421:         if ($cdom ne '' && $cnum ne '') {
 7422:             foreach my $key (keys(%{$cdom_courseroles})) {
 7423:                 if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
 7424:                     my $crsrole = $1;
 7425:                     my $crssec = $2;
 7426:                     if ($crsrole =~ /^cr/) {
 7427:                         unless (grep(/^cr$/,@{$rolecodes})) {
 7428:                             push(@{$rolecodes},'cr');
 7429:                         }
 7430:                     } else {
 7431:                         unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
 7432:                             push(@{$rolecodes},$crsrole);
 7433:                         }
 7434:                     }
 7435:                     my $rolekey = "$crsrole./$cdom/$cnum";
 7436:                     if ($crssec ne '') {
 7437:                         $rolekey .= "/$crssec";
 7438:                     }
 7439:                     $rolekey .= './';
 7440:                     $groups_roles->{$rolekey} = $rolecodes;
 7441:                 }
 7442:             }
 7443:         }
 7444:     }
 7445:     return;
 7446: }
 7447: 
 7448: sub delete_env_groupprivs {
 7449:     my ($where,$courseroles,$possroles) = @_;
 7450:     return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
 7451:     my ($dummy,$udom,$uname,$group) = split(/\//,$where);
 7452:     unless (ref($courseroles->{$udom}) eq 'HASH') {
 7453:         %{$courseroles->{$udom}} =
 7454:             &get_my_roles('','','userroles',['active'],
 7455:                           $possroles,[$udom],1);
 7456:     }
 7457:     if (ref($courseroles->{$udom}) eq 'HASH') {
 7458:         foreach my $item (keys(%{$courseroles->{$udom}})) {
 7459:             my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
 7460:             my $area = '/'.$cdom.'/'.$cnum;
 7461:             my $privkey = "user.priv.$crsrole.$area";
 7462:             if ($crssec ne '') {
 7463:                 $privkey .= '/'.$crssec;
 7464:             }
 7465:             $privkey .= ".$area/$group";
 7466:             &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
 7467:         }
 7468:     }
 7469:     return;
 7470: }
 7471: 
 7472: sub check_adhoc_privs {
 7473:     my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller,$sec) = @_;
 7474:     my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
 7475:     if ($sec) {
 7476:         $cckey .= '/'.$sec;
 7477:     } 
 7478:     my $setprivs;
 7479:     if ($env{$cckey}) {
 7480:         my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
 7481:         &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
 7482:         unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
 7483:             &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
 7484:             $setprivs = 1;
 7485:         }
 7486:     } else {
 7487:         &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
 7488:         $setprivs = 1;
 7489:     }
 7490:     return $setprivs;
 7491: }
 7492: 
 7493: sub set_adhoc_privileges {
 7494: # role can be cc, ca, or cr/<dom>/<dom>-domainconfig/role
 7495:     my ($dcdom,$pickedcourse,$role,$caller,$sec) = @_;
 7496:     my $area = '/'.$dcdom.'/'.$pickedcourse;
 7497:     if ($sec ne '') {
 7498:         $area .= '/'.$sec;
 7499:     }
 7500:     my $spec = $role.'.'.$area;
 7501:     my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
 7502:                                   $env{'user.name'},1);
 7503:     my %rolehash = ();
 7504:     if ($role =~ m{^\Qcr/$dcdom/$dcdom\E\-domainconfig/(\w+)$}) {
 7505:         my $rolename = $1;
 7506:         &custom_roleprivs(\%rolehash,$role,$dcdom,$pickedcourse,$spec,$area);
 7507:         my %domdef = &get_domain_defaults($dcdom);
 7508:         if (ref($domdef{'adhocroles'}) eq 'HASH') {
 7509:             if (ref($domdef{'adhocroles'}{$rolename}) eq 'HASH') {
 7510:                 &appenv({'request.role.desc' => $domdef{'adhocroles'}{$rolename}{'desc'},});
 7511:             }
 7512:         }
 7513:     } else {
 7514:         &standard_roleprivs(\%rolehash,$role,$dcdom,$spec,$pickedcourse,$area);
 7515:     }
 7516:     my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%rolehash);
 7517:     &appenv(\%userroles,[$role,'cm']);
 7518:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
 7519:     unless (($caller eq 'constructaccess' && $env{'request.course.id'}) ||
 7520:             ($caller eq 'tiny')) {
 7521:         &appenv( {'request.role'        => $spec,
 7522:                   'request.role.domain' => $dcdom,
 7523:                   'request.course.sec'  => $sec,
 7524:                  }
 7525:                );
 7526:         my $tadv=0;
 7527:         if (&allowed('adv') eq 'F') { $tadv=1; }
 7528:         &appenv({'request.role.adv'    => $tadv});
 7529:     }
 7530:     if ($role eq 'ca') {
 7531:         my @ca_settings = ('authoreditors','coauthorlist');
 7532:         my %info = &userenvironment($dcdom,$pickedcourse,@ca_settings);
 7533:         foreach my $item (@ca_settings) {
 7534:             if (exists($info{$item})) {
 7535:                 my $name = $item;
 7536:                 if ($item eq 'authoreditors') {
 7537:                     $name = 'editors';
 7538:                     unless ($info{'authoreditors'}) {
 7539:                         my %domdefs = &get_domain_defaults($dcdom);
 7540:                         if ($domdefs{$name} ne '') {
 7541:                             $info{'authoreditors'} = $domdefs{$name};
 7542:                         } else {
 7543:                             $info{'authoreditors'} = 'edit,xml';
 7544:                         }
 7545:                     }
 7546:                 }
 7547:                 &appenv({"environment.internal.$name./$dcdom/$pickedcourse" => $info{$item}});
 7548:             }
 7549:         }
 7550:     }
 7551: }
 7552: 
 7553: # --------------------------------------------------------------- get interface
 7554: 
 7555: sub get {
 7556:    my ($namespace,$storearr,$udomain,$uname)=@_;
 7557:    my $items='';
 7558:    foreach my $item (@$storearr) {
 7559:        $items.=&escape($item).'&';
 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: 
 7566:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
 7567:    my @pairs=split(/\&/,$rep);
 7568:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
 7569:      return @pairs;
 7570:    }
 7571:    my %returnhash=();
 7572:    my $i=0;
 7573:    foreach my $item (@$storearr) {
 7574:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 7575:       $i++;
 7576:    }
 7577:    return %returnhash;
 7578: }
 7579: 
 7580: # --------------------------------------------------------------- del interface
 7581: 
 7582: sub del {
 7583:    my ($namespace,$storearr,$udomain,$uname)=@_;
 7584:    my $items='';
 7585:    foreach my $item (@$storearr) {
 7586:        $items.=&escape($item).'&';
 7587:    }
 7588: 
 7589:    $items=~s/\&$//;
 7590:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 7591:    if (!$uname) { $uname=$env{'user.name'}; }
 7592:    my $uhome=&homeserver($uname,$udomain);
 7593:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
 7594: }
 7595: 
 7596: # -------------------------------------------------------------- dump interface
 7597: 
 7598: sub unserialize {
 7599:     my ($rep, $escapedkeys) = @_;
 7600: 
 7601:     return {} if $rep =~ /^error/;
 7602: 
 7603:     my %returnhash=();
 7604: 	foreach my $item (split(/\&/,$rep)) {
 7605: 	    my ($key, $value) = split(/=/, $item, 2);
 7606: 	    $key = unescape($key) unless $escapedkeys;
 7607: 	    next if $key =~ /^error: 2 /;
 7608: 	    $returnhash{$key} = &thaw_unescape($value);
 7609: 	}
 7610:     #return %returnhash;
 7611:     return \%returnhash;
 7612: }        
 7613: 
 7614: # see Lond::dump_with_regexp
 7615: # if $escapedkeys hash keys won't get unescaped.
 7616: sub dump {
 7617:     my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys,$encrypt)=@_;
 7618:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 7619:     if (!$uname) { $uname=$env{'user.name'}; }
 7620:     my $uhome=&homeserver($uname,$udomain);
 7621: 
 7622:     if ($regexp) {
 7623:         $regexp=&escape($regexp);
 7624:     } else {
 7625:         $regexp='.';
 7626:     }
 7627:     if (grep { $_ eq $uhome } current_machine_ids()) {
 7628:         # user is hosted on this machine
 7629:         my $reply = LONCAPA::Lond::dump_with_regexp(join(":", ($udomain,
 7630:                     $uname, $namespace, $regexp, $range)), $perlvar{'lonVersion'});
 7631:         return %{unserialize($reply, $escapedkeys)};
 7632:     }
 7633:     my $rep;
 7634:     if ($encrypt) {
 7635:         $rep=&reply("encrypt:edump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
 7636:     } else {
 7637:         $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
 7638:     }
 7639:     my @pairs=split(/\&/,$rep);
 7640:     my %returnhash=();
 7641:     if (!($rep =~ /^error/ )) {
 7642: 	foreach my $item (@pairs) {
 7643: 	    my ($key,$value)=split(/=/,$item,2);
 7644:         $key = unescape($key) unless $escapedkeys;
 7645:         #$key = &unescape($key);
 7646: 	    next if ($key =~ /^error: 2 /);
 7647: 	    $returnhash{$key}=&thaw_unescape($value);
 7648: 	}
 7649:     }
 7650:     return %returnhash;
 7651: }
 7652: 
 7653: 
 7654: # --------------------------------------------------------- dumpstore interface
 7655: 
 7656: sub dumpstore {
 7657:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
 7658:    # same as dump but keys must be escaped. They may contain colon separated
 7659:    # lists of values that may themself contain colons (e.g. symbs).
 7660:    return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
 7661: }
 7662: 
 7663: # -------------------------------------------------------------- keys interface
 7664: 
 7665: sub getkeys {
 7666:    my ($namespace,$udomain,$uname)=@_;
 7667:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 7668:    if (!$uname) { $uname=$env{'user.name'}; }
 7669:    my $uhome=&homeserver($uname,$udomain);
 7670:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
 7671:    my @keyarray=();
 7672:    foreach my $key (split(/\&/,$rep)) {
 7673:       next if ($key =~ /^error: 2 /);
 7674:       push(@keyarray,&unescape($key));
 7675:    }
 7676:    return @keyarray;
 7677: }
 7678: 
 7679: # --------------------------------------------------------------- currentdump
 7680: sub currentdump {
 7681:    my ($courseid,$sdom,$sname)=@_;
 7682:    $courseid = $env{'request.course.id'} if (! defined($courseid));
 7683:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
 7684:    $sname    = $env{'user.name'}         if (! defined($sname));
 7685:    my $uhome = &homeserver($sname,$sdom);
 7686:    my $rep;
 7687: 
 7688:    if (grep { $_ eq $uhome } current_machine_ids()) {
 7689:        $rep = LONCAPA::Lond::dump_profile_database(join(":", ($sdom, $sname, 
 7690:                    $courseid)));
 7691:    } else {
 7692:        $rep = reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
 7693:    }
 7694: 
 7695:    return if ($rep =~ /^(error:|no_such_host)/);
 7696:    #
 7697:    my %returnhash=();
 7698:    #
 7699:    if ($rep eq 'unknown_cmd') {
 7700:        # an old lond will not know currentdump
 7701:        # Do a dump and make it look like a currentdump
 7702:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
 7703:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
 7704:        my %hash = @tmp;
 7705:        @tmp=();
 7706:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
 7707:    } else {
 7708:        my @pairs=split(/\&/,$rep);
 7709:        foreach my $pair (@pairs) {
 7710:            my ($key,$value)=split(/=/,$pair,2);
 7711:            my ($symb,$param) = split(/:/,$key);
 7712:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
 7713:                                                         &thaw_unescape($value);
 7714:        }
 7715:    }
 7716:    return %returnhash;
 7717: }
 7718: 
 7719: sub convert_dump_to_currentdump{
 7720:     my %hash = %{shift()};
 7721:     my %returnhash;
 7722:     # Code ripped from lond, essentially.  The only difference
 7723:     # here is the unescaping done by lonnet::dump().  Conceivably
 7724:     # we might run in to problems with parameter names =~ /^v\./
 7725:     while (my ($key,$value) = each(%hash)) {
 7726:         my ($v,$symb,$param) = split(/:/,$key);
 7727: 	$symb  = &unescape($symb);
 7728: 	$param = &unescape($param);
 7729:         next if ($v eq 'version' || $symb eq 'keys');
 7730:         next if (exists($returnhash{$symb}) &&
 7731:                  exists($returnhash{$symb}->{$param}) &&
 7732:                  $returnhash{$symb}->{'v.'.$param} > $v);
 7733:         $returnhash{$symb}->{$param}=$value;
 7734:         $returnhash{$symb}->{'v.'.$param}=$v;
 7735:     }
 7736:     #
 7737:     # Remove all of the keys in the hashes which keep track of
 7738:     # the version of the parameter.
 7739:     while (my ($symb,$param_hash) = each(%returnhash)) {
 7740:         # use a foreach because we are going to delete from the hash.
 7741:         foreach my $key (keys(%$param_hash)) {
 7742:             delete($param_hash->{$key}) if ($key =~ /^v\./);
 7743:         }
 7744:     }
 7745:     return \%returnhash;
 7746: }
 7747: 
 7748: # ------------------------------------------------------ critical inc interface
 7749: 
 7750: sub cinc {
 7751:     return &inc(@_,'critical');
 7752: }
 7753: 
 7754: # --------------------------------------------------------------- inc interface
 7755: 
 7756: sub inc {
 7757:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
 7758:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 7759:     if (!$uname) { $uname=$env{'user.name'}; }
 7760:     my $uhome=&homeserver($uname,$udomain);
 7761:     my $items='';
 7762:     if (! ref($store)) {
 7763:         # got a single value, so use that instead
 7764:         $items = &escape($store).'=&';
 7765:     } elsif (ref($store) eq 'SCALAR') {
 7766:         $items = &escape($$store).'=&';        
 7767:     } elsif (ref($store) eq 'ARRAY') {
 7768:         $items = join('=&',map {&escape($_);} @{$store});
 7769:     } elsif (ref($store) eq 'HASH') {
 7770:         while (my($key,$value) = each(%{$store})) {
 7771:             $items.= &escape($key).'='.&escape($value).'&';
 7772:         }
 7773:     }
 7774:     $items=~s/\&$//;
 7775:     if ($critical) {
 7776: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
 7777:     } else {
 7778: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
 7779:     }
 7780: }
 7781: 
 7782: # --------------------------------------------------------------- put interface
 7783: 
 7784: sub put {
 7785:    my ($namespace,$storehash,$udomain,$uname,$encrypt)=@_;
 7786:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 7787:    if (!$uname) { $uname=$env{'user.name'}; }
 7788:    my $uhome=&homeserver($uname,$udomain);
 7789:    my $items='';
 7790:    foreach my $item (keys(%$storehash)) {
 7791:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 7792:    }
 7793:    $items=~s/\&$//;
 7794:    if ($encrypt) {
 7795:        return &reply("encrypt:put:$udomain:$uname:$namespace:$items",$uhome);
 7796:    } else {
 7797:        return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 7798:    }
 7799: }
 7800: 
 7801: # ------------------------------------------------------------ newput interface
 7802: 
 7803: sub newput {
 7804:    my ($namespace,$storehash,$udomain,$uname)=@_;
 7805:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 7806:    if (!$uname) { $uname=$env{'user.name'}; }
 7807:    my $uhome=&homeserver($uname,$udomain);
 7808:    my $items='';
 7809:    foreach my $key (keys(%$storehash)) {
 7810:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 7811:    }
 7812:    $items=~s/\&$//;
 7813:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
 7814: }
 7815: 
 7816: # ---------------------------------------------------------  putstore interface
 7817: 
 7818: sub putstore {
 7819:    my ($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog)=@_;
 7820:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 7821:    if (!$uname) { $uname=$env{'user.name'}; }
 7822:    my $uhome=&homeserver($uname,$udomain);
 7823:    my $items='';
 7824:    foreach my $key (keys(%$storehash)) {
 7825:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
 7826:    }
 7827:    $items=~s/\&$//;
 7828:    my $esc_symb=&escape($symb);
 7829:    my $esc_v=&escape($version);
 7830:    my $reply =
 7831:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
 7832: 	      $uhome);
 7833:    if (($tolog) && ($reply eq 'ok')) {
 7834:        my $namevalue='';
 7835:        foreach my $key (keys(%{$storehash})) {
 7836:            $namevalue.=&escape($key).'='.&freeze_escape($storehash->{$key}).'&';
 7837:        }
 7838:        my $ip = &get_requestor_ip();
 7839:        $namevalue .= 'ip='.&escape($ip).
 7840:                      '&host='.&escape($perlvar{'lonHostID'}).
 7841:                      '&version='.$esc_v.
 7842:                      '&by='.&escape($env{'user.name'}.':'.$env{'user.domain'});
 7843:        &courselog($symb.':'.$uname.':'.$udomain.':PUTSTORE:'.$namevalue);
 7844:    }
 7845:    if ($reply eq 'unknown_cmd') {
 7846:        # gfall back to way things use to be done
 7847:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
 7848: 			    $uname);
 7849:    }
 7850:    return $reply;
 7851: }
 7852: 
 7853: sub old_putstore {
 7854:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
 7855:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 7856:     if (!$uname) { $uname=$env{'user.name'}; }
 7857:     my $uhome=&homeserver($uname,$udomain);
 7858:     my %newstorehash;
 7859:     foreach my $item (keys(%$storehash)) {
 7860: 	my $key = $version.':'.&escape($symb).':'.$item;
 7861: 	$newstorehash{$key} = $storehash->{$item};
 7862:     }
 7863:     my $items='';
 7864:     my %allitems = ();
 7865:     foreach my $item (keys(%newstorehash)) {
 7866: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
 7867: 	    my $key = $1.':keys:'.$2;
 7868: 	    $allitems{$key} .= $3.':';
 7869: 	}
 7870: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
 7871:     }
 7872:     foreach my $item (keys(%allitems)) {
 7873: 	$allitems{$item} =~ s/\:$//;
 7874: 	$items.= $item.'='.$allitems{$item}.'&';
 7875:     }
 7876:     $items=~s/\&$//;
 7877:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 7878: }
 7879: 
 7880: # ------------------------------------------------------ critical put interface
 7881: 
 7882: sub cput {
 7883:    my ($namespace,$storehash,$udomain,$uname)=@_;
 7884:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 7885:    if (!$uname) { $uname=$env{'user.name'}; }
 7886:    my $uhome=&homeserver($uname,$udomain);
 7887:    my $items='';
 7888:    foreach my $item (keys(%$storehash)) {
 7889:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 7890:    }
 7891:    $items=~s/\&$//;
 7892:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
 7893: }
 7894: 
 7895: # -------------------------------------------------------------- eget interface
 7896: 
 7897: sub eget {
 7898:    my ($namespace,$storearr,$udomain,$uname)=@_;
 7899:    my $items='';
 7900:    foreach my $item (@$storearr) {
 7901:        $items.=&escape($item).'&';
 7902:    }
 7903:    $items=~s/\&$//;
 7904:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 7905:    if (!$uname) { $uname=$env{'user.name'}; }
 7906:    my $uhome=&homeserver($uname,$udomain);
 7907:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
 7908:    my @pairs=split(/\&/,$rep);
 7909:    my %returnhash=();
 7910:    my $i=0;
 7911:    foreach my $item (@$storearr) {
 7912:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 7913:       $i++;
 7914:    }
 7915:    return %returnhash;
 7916: }
 7917: 
 7918: # ------------------------------------------------------------ tmpput interface
 7919: sub tmpput {
 7920:     my ($storehash,$server,$context)=@_;
 7921:     my $items='';
 7922:     foreach my $item (keys(%$storehash)) {
 7923: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 7924:     }
 7925:     $items=~s/\&$//;
 7926:     if (defined($context)) {
 7927:         $items .= ':'.&escape($context);
 7928:     }
 7929:     return &reply("tmpput:$items",$server);
 7930: }
 7931: 
 7932: # ------------------------------------------------------------ tmpget interface
 7933: sub tmpget {
 7934:     my ($token,$server)=@_;
 7935:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 7936:     my $rep=&reply("tmpget:$token",$server);
 7937:     my %returnhash;
 7938:     if ($rep =~ /^(con_lost|error|no_such_host)/i) {
 7939:         return %returnhash;
 7940:     }
 7941:     foreach my $item (split(/\&/,$rep)) {
 7942: 	my ($key,$value)=split(/=/,$item);
 7943: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
 7944:     }
 7945:     return %returnhash;
 7946: }
 7947: 
 7948: # ------------------------------------------------------------ tmpdel interface
 7949: sub tmpdel {
 7950:     my ($token,$server)=@_;
 7951:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 7952:     return &reply("tmpdel:$token",$server);
 7953: }
 7954: 
 7955: # ------------------------------------------------------------ get_timebased_id 
 7956: 
 7957: sub get_timebased_id {
 7958:     my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
 7959:         $maxtries) = @_;
 7960:     my ($newid,$error,$dellock);
 7961:     unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {  
 7962:         return ('','ok','invalid call to get suffix');
 7963:     }
 7964: 
 7965: # set defaults for any optional args for which values were not supplied
 7966:     if ($who eq '') {
 7967:         $who = $env{'user.name'}.':'.$env{'user.domain'};
 7968:     }
 7969:     if (!$locktries) {
 7970:         $locktries = 3;
 7971:     }
 7972:     if (!$maxtries) {
 7973:         $maxtries = 10;
 7974:     }
 7975:     
 7976:     if (($cdom eq '') || ($cnum eq '')) {
 7977:         if ($env{'request.course.id'}) {
 7978:             $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 7979:             $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 7980:         }
 7981:         if (($cdom eq '') || ($cnum eq '')) {
 7982:             return ('','ok','call to get suffix not in course context');
 7983:         }
 7984:     }
 7985: 
 7986: # construct locking item
 7987:     my $lockhash = {
 7988:                       $prefix."\0".'locked_'.$keyid => $who,
 7989:                    };
 7990:     my $tries = 0;
 7991: 
 7992: # attempt to get lock on nohist_$namespace file
 7993:     my $gotlock = &newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
 7994:     while (($gotlock ne 'ok') && $tries <$locktries) {
 7995:         $tries ++;
 7996:         sleep 1;
 7997:         $gotlock = &newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
 7998:     }
 7999: 
 8000: # attempt to get unique identifier, based on current timestamp
 8001:     if ($gotlock eq 'ok') {
 8002:         my %inuse = &dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
 8003:         my $id = time;
 8004:         $newid = $id;
 8005:         if ($idtype eq 'addcode') {
 8006:             $newid .= &sixnum_code();
 8007:         }
 8008:         my $idtries = 0;
 8009:         while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
 8010:             if ($idtype eq 'concat') {
 8011:                 $newid = $id.$idtries;
 8012:             } elsif ($idtype eq 'addcode') {
 8013:                 $newid = $newid.&sixnum_code();
 8014:             } else {
 8015:                 $newid ++;
 8016:             }
 8017:             $idtries ++;
 8018:         }
 8019:         if (!exists($inuse{$prefix."\0".$newid})) {
 8020:             my %new_item =  (
 8021:                               $prefix."\0".$newid => $who,
 8022:                             );
 8023:             my $putresult = &put('nohist_'.$namespace,\%new_item,
 8024:                                                  $cdom,$cnum);
 8025:             if ($putresult ne 'ok') {
 8026:                 undef($newid);
 8027:                 $error = 'error saving new item: '.$putresult;
 8028:             }
 8029:         } else {
 8030:              undef($newid);
 8031:              $error = ('error: no unique suffix available for the new item ');
 8032:         }
 8033: #  remove lock
 8034:         my @del_lock = ($prefix."\0".'locked_'.$keyid);
 8035:         $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
 8036:     } else {
 8037:         $error = "error: could not obtain lockfile\n";
 8038:         $dellock = 'ok';
 8039:         if (($prefix eq 'paste') && ($namespace eq 'courseeditor') && ($keyid eq 'num')) {
 8040:             $dellock = 'nolock';
 8041:         }
 8042:     }
 8043:     return ($newid,$dellock,$error);
 8044: }
 8045: 
 8046: sub sixnum_code {
 8047:     my $code;
 8048:     for (0..6) {
 8049:         $code .= int( rand(9) );
 8050:     }
 8051:     return $code;
 8052: }
 8053: 
 8054: # -------------------------------------------------- portfolio access checking
 8055: 
 8056: sub portfolio_access {
 8057:     my ($requrl,$clientip) = @_;
 8058:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
 8059:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group,$clientip);
 8060:     if ($result) {
 8061:         my %setters;
 8062:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 8063:             my ($startblock,$endblock,$triggerblock,$by_ip,$blockdom) =
 8064:                 &Apache::loncommon::blockcheck(\%setters,'port',$clientip,$unum,$udom);
 8065:             if (($startblock && $endblock) || ($by_ip)) {
 8066:                 return 'B';
 8067:             }
 8068:         } else {
 8069:             my ($startblock,$endblock,$triggerblock,$by_ip,$blockdom) =
 8070:                 &Apache::loncommon::blockcheck(\%setters,'port',$clientip);
 8071:             if (($startblock && $endblock) || ($by_ip)) {
 8072:                 return 'B';
 8073:             }
 8074:         }
 8075:     }
 8076:     if ($result eq 'ok') {
 8077:        return 'F';
 8078:     } elsif ($result =~ /^[^:]+:guest_/) {
 8079:        return 'A';
 8080:     }
 8081:     return '';
 8082: }
 8083: 
 8084: sub get_portfolio_access {
 8085:     my ($udom,$unum,$file_name,$group,$clientip,$access_hash,$portaccessref) = @_;
 8086: 
 8087:     if (!ref($access_hash)) {
 8088: 	my $current_perms = &get_portfile_permissions($udom,$unum);
 8089: 	my %access_controls = &get_access_controls($current_perms,$group,
 8090: 						   $file_name);
 8091: 	$access_hash = $access_controls{$file_name};
 8092:     }
 8093: 
 8094:     my $portaccess;
 8095:     if (ref($portaccess) eq 'SCALAR') {
 8096:         $portaccess = $$portaccessref;
 8097:     } else {
 8098:         $portaccess = &usertools_access($unum,$udom,'portaccess',undef,'tools');
 8099:     }
 8100: 
 8101:     my ($public,$guest,@domains,@users,@courses,@groups,@ips,@userips);
 8102:     my $now = time;
 8103:     if (ref($access_hash) eq 'HASH') {
 8104:         foreach my $key (keys(%{$access_hash})) {
 8105:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
 8106:             next if (($scope ne 'ip') && ($portaccess == 0));
 8107:             if ($start > $now) {
 8108:                 next;
 8109:             }
 8110:             if ($end && $end<$now) {
 8111:                 next;
 8112:             }
 8113:             if ($scope eq 'public') {
 8114:                 $public = $key;
 8115:                 last;
 8116:             } elsif ($scope eq 'guest') {
 8117:                 $guest = $key;
 8118:             } elsif ($scope eq 'domains') {
 8119:                 push(@domains,$key);
 8120:             } elsif ($scope eq 'users') {
 8121:                 push(@users,$key);
 8122:             } elsif ($scope eq 'course') {
 8123:                 push(@courses,$key);
 8124:             } elsif ($scope eq 'group') {
 8125:                 push(@groups,$key);
 8126:             } elsif ($scope eq 'ip') {
 8127:                 push(@ips,$key);
 8128:             } elsif ($scope eq 'userip') {
 8129:                 push(@userips,$key);
 8130:             }
 8131:         }
 8132:         if ($public) {
 8133:             return 'ok';
 8134:         } elsif (@ips > 0) {
 8135:             my $allowed;
 8136:             foreach my $ipkey (@ips) {
 8137:                 if (ref($access_hash->{$ipkey}{'ip'}) eq 'ARRAY') {
 8138:                     if (&Apache::loncommon::check_ip_acc(join(',',@{$access_hash->{$ipkey}{'ip'}}),$clientip)) {
 8139:                         $allowed = 1;
 8140:                         last; 
 8141:                     }
 8142:                 }
 8143:             }
 8144:             if ($allowed) {
 8145:                 return 'ok';
 8146:             }
 8147:         } elsif (@userips > 0) {
 8148:             my $allowed;
 8149:             foreach my $useripkey (@userips) {
 8150:                 if (ref($access_hash->{$useripkey}{'ip'}) eq 'ARRAY') {
 8151:                     if (&Apache::loncommon::check_ip_acc(join(',',@{$access_hash->{$useripkey}{'ip'}}),$clientip)) {
 8152:                         $allowed = 1;
 8153:                         last;
 8154:                     }
 8155:                 }
 8156:             }
 8157:             if ($allowed) {
 8158:                 return 'ok';
 8159:             }
 8160:         }
 8161:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 8162:             if ($guest) {
 8163:                 return $guest;
 8164:             }
 8165:         } else {
 8166:             if (@domains > 0) {
 8167:                 foreach my $domkey (@domains) {
 8168:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
 8169:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
 8170:                             return 'ok';
 8171:                         }
 8172:                     }
 8173:                 }
 8174:             }
 8175:             if (@users > 0) {
 8176:                 foreach my $userkey (@users) {
 8177:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
 8178:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
 8179:                             if (ref($item) eq 'HASH') {
 8180:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
 8181:                                     ($item->{'udom'} eq $env{'user.domain'})) {
 8182:                                     return 'ok';
 8183:                                 }
 8184:                             }
 8185:                         }
 8186:                     } 
 8187:                 }
 8188:             }
 8189:             my %roleshash;
 8190:             my @courses_and_groups = @courses;
 8191:             push(@courses_and_groups,@groups); 
 8192:             if (@courses_and_groups > 0) {
 8193:                 my (%allgroups,%allroles); 
 8194:                 my ($start,$end,$role,$sec,$group);
 8195:                 foreach my $envkey (%env) {
 8196:                     if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
 8197:                         my $cid = $2.'_'.$3; 
 8198:                         if ($1 eq 'gr') {
 8199:                             $group = $4;
 8200:                             $allgroups{$cid}{$group} = $env{$envkey};
 8201:                         } else {
 8202:                             if ($4 eq '') {
 8203:                                 $sec = 'none';
 8204:                             } else {
 8205:                                 $sec = $4;
 8206:                             }
 8207:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
 8208:                         }
 8209:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
 8210:                         my $cid = $2.'_'.$3;
 8211:                         if ($4 eq '') {
 8212:                             $sec = 'none';
 8213:                         } else {
 8214:                             $sec = $4;
 8215:                         }
 8216:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
 8217:                     }
 8218:                 }
 8219:                 if (keys(%allroles) == 0) {
 8220:                     return;
 8221:                 }
 8222:                 foreach my $key (@courses_and_groups) {
 8223:                     my %content = %{$$access_hash{$key}};
 8224:                     my $cnum = $content{'number'};
 8225:                     my $cdom = $content{'domain'};
 8226:                     my $cid = $cdom.'_'.$cnum;
 8227:                     if (!exists($allroles{$cid})) {
 8228:                         next;
 8229:                     }    
 8230:                     foreach my $role_id (keys(%{$content{'roles'}})) {
 8231:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
 8232:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
 8233:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
 8234:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
 8235:                         foreach my $role (keys(%{$allroles{$cid}})) {
 8236:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
 8237:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
 8238:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
 8239:                                         if (grep/^all$/,@sections) {
 8240:                                             return 'ok';
 8241:                                         } else {
 8242:                                             if (grep/^$sec$/,@sections) {
 8243:                                                 return 'ok';
 8244:                                             }
 8245:                                         }
 8246:                                     }
 8247:                                 }
 8248:                                 if (keys(%{$allgroups{$cid}}) == 0) {
 8249:                                     if (grep/^none$/,@groups) {
 8250:                                         return 'ok';
 8251:                                     }
 8252:                                 } else {
 8253:                                     if (grep/^all$/,@groups) {
 8254:                                         return 'ok';
 8255:                                     } 
 8256:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
 8257:                                         if (grep/^$group$/,@groups) {
 8258:                                             return 'ok';
 8259:                                         }
 8260:                                     }
 8261:                                 } 
 8262:                             }
 8263:                         }
 8264:                     }
 8265:                 }
 8266:             }
 8267:             if ($guest) {
 8268:                 return $guest;
 8269:             }
 8270:         }
 8271:     }
 8272:     return;
 8273: }
 8274: 
 8275: sub course_group_datechecker {
 8276:     my ($dates,$now,$status) = @_;
 8277:     my ($start,$end) = split(/\./,$dates);
 8278:     if (!$start && !$end) {
 8279:         return 'ok';
 8280:     }
 8281:     if (grep/^active$/,@{$status}) {
 8282:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
 8283:             return 'ok';
 8284:         }
 8285:     }
 8286:     if (grep/^previous$/,@{$status}) {
 8287:         if ($end > $now ) {
 8288:             return 'ok';
 8289:         }
 8290:     }
 8291:     if (grep/^future$/,@{$status}) {
 8292:         if ($start > $now) {
 8293:             return 'ok';
 8294:         }
 8295:     }
 8296:     return; 
 8297: }
 8298: 
 8299: sub parse_portfolio_url {
 8300:     my ($url) = @_;
 8301: 
 8302:     my ($type,$udom,$unum,$group,$file_name);
 8303:     
 8304:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
 8305: 	$type = 1;
 8306:         $udom = $1;
 8307:         $unum = $2;
 8308:         $file_name = $3;
 8309:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
 8310: 	$type = 2;
 8311:         $udom = $1;
 8312:         $unum = $2;
 8313:         $group = $3;
 8314:         $file_name = $3.'/'.$4;
 8315:     }
 8316:     if (wantarray) {
 8317: 	return ($type,$udom,$unum,$file_name,$group);
 8318:     }
 8319:     return $type;
 8320: }
 8321: 
 8322: sub is_portfolio_url {
 8323:     my ($url) = @_;
 8324:     return scalar(&parse_portfolio_url($url));
 8325: }
 8326: 
 8327: sub is_portfolio_file {
 8328:     my ($file) = @_;
 8329:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
 8330:         return 1;
 8331:     }
 8332:     return;
 8333: }
 8334: 
 8335: sub is_coursetool_logo {
 8336:     my ($uri) = @_;
 8337:     if ($env{'request.course.id'}) {
 8338:         my $courseurl = &courseid_to_courseurl($env{'request.course.id'});
 8339:         if ($uri =~ m{^/*uploaded\Q$courseurl\E/toollogo/\d+/[^/]+$}) {
 8340:             return 1;
 8341:         }
 8342:     }
 8343:     return;
 8344: }
 8345: 
 8346: sub usertools_access {
 8347:     my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
 8348:     my ($access,%tools);
 8349:     if ($context eq '') {
 8350:         $context = 'tools';
 8351:     }
 8352:     if ($context eq 'requestcourses') {
 8353:         %tools = (
 8354:                       official   => 1,
 8355:                       unofficial => 1,
 8356:                       community  => 1,
 8357:                       textbook   => 1,
 8358:                       placement  => 1,
 8359:                       lti        => 1,
 8360:                  );
 8361:     } elsif ($context eq 'requestauthor') {
 8362:         %tools = (
 8363:                       requestauthor => 1,
 8364:                  );
 8365:     } elsif ($context eq 'authordefaults') {
 8366:         %tools = (
 8367:                       webdav    => 1,
 8368:                  );
 8369:     } else {
 8370:         %tools = (
 8371:                       aboutme   => 1,
 8372:                       blog      => 1,
 8373:                       webdav    => 1,
 8374:                       portfolio => 1,
 8375:                       portaccess => 1,
 8376:                       timezone  => 1,
 8377:                  );
 8378:     }
 8379:     return if (!defined($tools{$tool}));
 8380: 
 8381:     if (($udom eq '') || ($uname eq '')) {
 8382:         $udom = $env{'user.domain'};
 8383:         $uname = $env{'user.name'};
 8384:     }
 8385: 
 8386:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 8387:         if ($action ne 'reload') {
 8388:             if ($context eq 'requestcourses') {
 8389:                 return $env{'environment.canrequest.'.$tool};
 8390:             } elsif ($context eq 'requestauthor') {
 8391:                 return $env{'environment.canrequest.author'};
 8392:             } elsif ($context eq 'authordefaults') {
 8393:                 if ($tool eq 'webdav') {
 8394:                     return $env{'environment.availabletools.'.$tool};
 8395:                 }
 8396:             } else {
 8397:                 return $env{'environment.availabletools.'.$tool};
 8398:             }
 8399:         }
 8400:     }
 8401: 
 8402:     my ($toolstatus,$inststatus,$envkey);
 8403:     if ($context eq 'requestauthor') {
 8404:         $envkey = $context;
 8405:     } elsif ($context eq 'authordefaults') {
 8406:         if ($tool eq 'webdav') {
 8407:             $envkey = 'tools.'.$tool;
 8408:         }
 8409:     } else {
 8410:         $envkey = $context.'.'.$tool;
 8411:     }
 8412: 
 8413:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
 8414:          ($action ne 'reload')) {
 8415:         $toolstatus = $env{'environment.'.$envkey};
 8416:         $inststatus = $env{'environment.inststatus'};
 8417:     } else {
 8418:         if (ref($userenvref) eq 'HASH') {
 8419:             $toolstatus = $userenvref->{$envkey};
 8420:             $inststatus = $userenvref->{'inststatus'};
 8421:         } else {
 8422:             my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
 8423:             $toolstatus = $userenv{$envkey};
 8424:             $inststatus = $userenv{'inststatus'};
 8425:         }
 8426:     }
 8427: 
 8428:     if ($toolstatus ne '') {
 8429:         if ($toolstatus) {
 8430:             $access = 1;
 8431:         } else {
 8432:             $access = 0;
 8433:         }
 8434:         return $access;
 8435:     }
 8436: 
 8437:     my ($is_adv,%domdef);
 8438:     if (ref($is_advref) eq 'HASH') {
 8439:         $is_adv = $is_advref->{'is_adv'};
 8440:     } else {
 8441:         $is_adv = &is_advanced_user($udom,$uname);
 8442:     }
 8443:     if (ref($domdefref) eq 'HASH') {
 8444:         %domdef = %{$domdefref};
 8445:     } else {
 8446:         %domdef = &get_domain_defaults($udom);
 8447:     }
 8448:     if (ref($domdef{$tool}) eq 'HASH') {
 8449:         if ($is_adv) {
 8450:             if ($domdef{$tool}{'_LC_adv'} ne '') {
 8451:                 if ($domdef{$tool}{'_LC_adv'}) { 
 8452:                     $access = 1;
 8453:                 } else {
 8454:                     $access = 0;
 8455:                 }
 8456:                 return $access;
 8457:             }
 8458:         }
 8459:         if ($inststatus ne '') {
 8460:             my ($hasaccess,$hasnoaccess);
 8461:             foreach my $affiliation (split(/:/,$inststatus)) {
 8462:                 if ($domdef{$tool}{$affiliation} ne '') { 
 8463:                     if ($domdef{$tool}{$affiliation}) {
 8464:                         $hasaccess = 1;
 8465:                     } else {
 8466:                         $hasnoaccess = 1;
 8467:                     }
 8468:                 }
 8469:             }
 8470:             if ($hasaccess || $hasnoaccess) {
 8471:                 if ($hasaccess) {
 8472:                     $access = 1;
 8473:                 } elsif ($hasnoaccess) {
 8474:                     $access = 0; 
 8475:                 }
 8476:                 return $access;
 8477:             }
 8478:         } else {
 8479:             if ($domdef{$tool}{'default'} ne '') {
 8480:                 if ($domdef{$tool}{'default'}) {
 8481:                     $access = 1;
 8482:                 } elsif ($domdef{$tool}{'default'} == 0) {
 8483:                     $access = 0;
 8484:                 }
 8485:                 return $access;
 8486:             }
 8487:         }
 8488:     } else {
 8489:         if (($context eq 'tools') && ($tool ne 'webdav')) {
 8490:             $access = 1;
 8491:         } else {
 8492:             $access = 0;
 8493:         }
 8494:         return $access;
 8495:     }
 8496: }
 8497: 
 8498: sub is_course_owner {
 8499:     my ($cdom,$cnum,$udom,$uname) = @_;
 8500:     if (($udom eq '') || ($uname eq '')) {
 8501:         $udom = $env{'user.domain'};
 8502:         $uname = $env{'user.name'};
 8503:     }
 8504:     unless (($udom eq '') || ($uname eq '')) {
 8505:         if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
 8506:             if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
 8507:                 return 1;
 8508:             } else {
 8509:                 my %courseinfo = &coursedescription($cdom.'/'.$cnum);
 8510:                 if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
 8511:                     return 1;
 8512:                 }
 8513:             }
 8514:         }
 8515:     }
 8516:     return;
 8517: }
 8518: 
 8519: sub is_advanced_user {
 8520:     my ($udom,$uname,$nocache) = @_;
 8521:     my ($is_adv,$is_author,$use_cache,$hashid);
 8522:     if ($udom ne '' && $uname ne '') {
 8523:         if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 8524:             if (wantarray) {
 8525:                 return ($env{'user.adv'},$env{'user.author'});
 8526:             } else {
 8527:                 return $env{'user.adv'};
 8528:             }
 8529:         } elsif (!$nocache) {
 8530:             $use_cache = 1;
 8531:             $hashid = "$udom:$uname";  
 8532:             my ($info,$cached)=&is_cached_new('isadvau',$hashid);
 8533:             if ($cached) {
 8534:                 ($is_adv,$is_author) = split(/:/,$info);
 8535:                 if (wantarray) {
 8536:                     return ($is_adv,$is_author);
 8537:                 }
 8538:                 return $is_adv; 
 8539:             }
 8540:         }
 8541:     }
 8542:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
 8543:     my %allroles;
 8544:     foreach my $role (keys(%roleshash)) {
 8545:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
 8546:         my $area = '/'.$tdomain.'/'.$trest;
 8547:         if ($sec ne '') {
 8548:             $area .= '/'.$sec;
 8549:         }
 8550:         if (($area ne '') && ($trole ne '')) {
 8551:             my $spec=$trole.'.'.$area;
 8552:             if ($trole =~ /^cr\//) {
 8553:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
 8554:             } elsif ($trole ne 'gr') {
 8555:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
 8556:             }
 8557:             if ($trole eq 'au') {
 8558:                 $is_author = 1;
 8559:             }
 8560:         }
 8561:     }
 8562:     foreach my $role (keys(%allroles)) {
 8563:         last if ($is_adv);
 8564:         foreach my $item (split(/:/,$allroles{$role})) {
 8565:             if ($item ne '') {
 8566:                 my ($privilege,$restrictions)=split(/&/,$item);
 8567:                 if ($privilege eq 'adv') {
 8568:                     $is_adv = 1;
 8569:                     last;
 8570:                 }
 8571:             }
 8572:         }
 8573:     }
 8574:     if ($use_cache) {
 8575:         my $cachetime = 600;
 8576:         &do_cache_new('isadvau',$hashid,$is_adv.':'.$is_author,$cachetime);
 8577:     }
 8578:     if (wantarray) {
 8579:         return ($is_adv,$is_author);
 8580:     }
 8581:     return $is_adv;
 8582: }
 8583: 
 8584: sub check_can_request {
 8585:     my ($dom,$can_request,$request_domains,$uname,$udom) = @_;
 8586:     my $canreq = 0;
 8587:     if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
 8588:         $uname = $env{'user.name'};
 8589:         $udom = $env{'user.domain'};
 8590:     }
 8591:     my ($types,$typename) = &Apache::loncommon::course_types();
 8592:     my @options = ('approval','validate','autolimit');
 8593:     my $optregex = join('|',@options);
 8594:     if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
 8595:         my %willtrust;
 8596:         foreach my $type (@{$types}) {
 8597:             if (&usertools_access($uname,$udom,$type,undef,
 8598:                                   'requestcourses')) {
 8599:                 $canreq ++;
 8600:                 if (ref($request_domains) eq 'HASH') {
 8601:                     push(@{$request_domains->{$type}},$udom);
 8602:                 }
 8603:                 if ($dom eq $udom) {
 8604:                     $can_request->{$type} = 1;
 8605:                 }
 8606:             }
 8607:             if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '') &&
 8608:                 ($env{'environment.reqcrsotherdom.'.$type} ne '')) {
 8609:                 my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
 8610:                 if (@curr > 0) {
 8611:                     foreach my $item (@curr) {
 8612:                         if (ref($request_domains) eq 'HASH') {
 8613:                             my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
 8614:                             if ($otherdom ne '') {
 8615:                                 unless (exists($willtrust{$otherdom})) {
 8616:                                     $willtrust{$otherdom} = &will_trust('reqcrs',$env{'user.domain'},$otherdom);
 8617:                                 }
 8618:                                 if ($willtrust{$otherdom}) {
 8619:                                     if (ref($request_domains->{$type}) eq 'ARRAY') {
 8620:                                         unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
 8621:                                             push(@{$request_domains->{$type}},$otherdom);
 8622:                                         }
 8623:                                     } else {
 8624:                                         push(@{$request_domains->{$type}},$otherdom);
 8625:                                     }
 8626:                                 }
 8627:                             }
 8628:                         }
 8629:                     }
 8630:                     unless ($dom eq $env{'user.domain'}) {
 8631:                         $canreq ++;
 8632:                         if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
 8633:                             $can_request->{$type} = 1;
 8634:                         }
 8635:                     }
 8636:                 }
 8637:             }
 8638:         }
 8639:     }
 8640:     return $canreq;
 8641: }
 8642: 
 8643: # ---------------------------------------------- Custom access rule evaluation
 8644: 
 8645: sub customaccess {
 8646:     my ($priv,$uri)=@_;
 8647:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
 8648:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
 8649:     $udom = &LONCAPA::clean_domain($udom);
 8650:     $ucrs = &LONCAPA::clean_username($ucrs);
 8651:     my $access=0;
 8652:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
 8653: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
 8654: 	if ($type eq 'user') {
 8655: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
 8656: 		my ($tdom,$tuname)=split(m{/},$scope);
 8657: 		if ($tdom) {
 8658: 		    if ($tdom ne $env{'user.domain'}) { next; }
 8659: 		}
 8660: 		if ($tuname) {
 8661: 		    if ($tuname ne $env{'user.name'}) { next; }
 8662: 		}
 8663: 		$access=($effect eq 'allow');
 8664: 		last;
 8665: 	    }
 8666: 	} else {
 8667: 	    if ($role) {
 8668: 		if ($role ne $urole) { next; }
 8669: 	    }
 8670: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
 8671: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
 8672: 		if ($tdom) {
 8673: 		    if ($tdom ne $udom) { next; }
 8674: 		}
 8675: 		if ($tcrs) {
 8676: 		    if ($tcrs ne $ucrs) { next; }
 8677: 		}
 8678: 		if ($tsec) {
 8679: 		    if ($tsec ne $usec) { next; }
 8680: 		}
 8681: 		$access=($effect eq 'allow');
 8682: 		last;
 8683: 	    }
 8684: 	    if ($realm eq '' && $role eq '') {
 8685: 		$access=($effect eq 'allow');
 8686: 	    }
 8687: 	}
 8688:     }
 8689:     return $access;
 8690: }
 8691: 
 8692: # ------------------------------------------------- Check for a user privilege
 8693: 
 8694: sub allowed {
 8695:     my ($priv,$uri,$symb,$role,$clientip,$noblockcheck,$ignorecache,$nodeeplinkcheck,$nodeeplinkout)=@_;
 8696:     my $ver_orguri=$uri;
 8697:     $uri=&deversion($uri);
 8698:     my $orguri=$uri;
 8699:     $uri=&declutter($uri);
 8700: 
 8701:     if ($priv eq 'evb') {
 8702: # Evade communication block restrictions for specified role in a course or domain
 8703:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
 8704:             return $1;
 8705:         } else {
 8706:             return;
 8707:         }
 8708:     }
 8709: 
 8710:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
 8711: # Free bre access to adm and meta resources
 8712:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard|viewclasslist|aboutme|ext\.tool)$})) 
 8713: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
 8714: 	&& ($priv eq 'bre')) {
 8715: 	return 'F';
 8716:     }
 8717: 
 8718: # Free bre access to user's own portfolio contents
 8719:     my ($space,$domain,$name,@dir)=split('/',$uri);
 8720:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
 8721: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
 8722:         my %setters;
 8723:         my ($startblock,$endblock,$triggerblock,$by_ip,$blockdom) = 
 8724:             &Apache::loncommon::blockcheck(\%setters,'port',$clientip);
 8725:         if (($startblock && $endblock) || ($by_ip)) {
 8726:             return 'B';
 8727:         } else {
 8728:             return 'F';
 8729:         }
 8730:     }
 8731: 
 8732: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
 8733:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
 8734:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
 8735:         if (exists($env{'request.course.id'})) {
 8736:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 8737:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 8738:             if (($domain eq $cdom) && ($name eq $cnum)) {
 8739:                 my $courseprivid=$env{'request.course.id'};
 8740:                 $courseprivid=~s/\_/\//;
 8741:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
 8742:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
 8743:                     return $1; 
 8744:                 } else {
 8745:                     if ($env{'request.course.sec'}) {
 8746:                         $courseprivid.='/'.$env{'request.course.sec'};
 8747:                     }
 8748:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
 8749:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
 8750:                         return $2;
 8751:                     }
 8752:                 }
 8753:             }
 8754:         }
 8755:     }
 8756: 
 8757: # Free bre to public access
 8758: 
 8759:     if ($priv eq 'bre') {
 8760:         my $copyright;
 8761:         unless ($uri =~ /ext\.tool/) {
 8762:             $copyright=&metadata($uri,'copyright');
 8763:         }
 8764: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
 8765:            return 'F'; 
 8766:         }
 8767:         if ($copyright eq 'priv') {
 8768:             $uri=~/([^\/]+)\/([^\/]+)\//;
 8769: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
 8770: 		return '';
 8771:             }
 8772:         }
 8773:         if ($copyright eq 'domain') {
 8774:             $uri=~/([^\/]+)\/([^\/]+)\//;
 8775: 	    unless (($env{'user.domain'} eq $1) ||
 8776:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
 8777: 		return '';
 8778:             }
 8779:         }
 8780:         if ($env{'request.role'}=~ /li\.\//) {
 8781:             # Library role, so allow browsing of resources in this domain.
 8782:             return 'F';
 8783:         }
 8784:         if ($copyright eq 'custom') {
 8785: 	    unless (&customaccess($priv,$uri)) { return ''; }
 8786:         }
 8787:     }
 8788:     # Domain coordinator is trying to create a course
 8789:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
 8790:         # uri is the requested domain in this case.
 8791:         # comparison to 'request.role.domain' shows if the user has selected
 8792:         # a role of dc for the domain in question.
 8793:         return 'F' if ($uri eq $env{'request.role.domain'});
 8794:     }
 8795: 
 8796:     my $thisallowed='';
 8797:     my $statecond=0;
 8798:     my $courseprivid='';
 8799: 
 8800:     my $ownaccess;
 8801:     # Community Coordinator or Assistant Co-author browsing resource space.
 8802:     if (($priv eq 'bro') && ($env{'user.author'})) {
 8803:         if ($uri eq '') {
 8804:             $ownaccess = 1;
 8805:         } else {
 8806:             if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
 8807:                 my $udom = $env{'user.domain'};
 8808:                 my $uname = $env{'user.name'};
 8809:                 if ($uri =~ m{^\Q$udom\E/?$}) {
 8810:                     $ownaccess = 1;
 8811:                 } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
 8812:                     unless ($uri =~ m{\.\./}) {
 8813:                         $ownaccess = 1;
 8814:                     }
 8815:                 } elsif (($udom ne 'public') && ($uname ne 'public')) {
 8816:                     my $now = time;
 8817:                     if ($uri =~ m{^([^/]+)/?$}) {
 8818:                         my $adom = $1;
 8819:                         foreach my $key (keys(%env)) {
 8820:                             if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
 8821:                                 my ($start,$end) = split(/\./,$env{$key});
 8822:                                 if (($now >= $start) && (!$end || $end > $now)) {
 8823:                                     $ownaccess = 1;
 8824:                                     last;
 8825:                                 }
 8826:                             }
 8827:                         }
 8828:                     } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
 8829:                         my $adom = $1;
 8830:                         my $aname = $2;
 8831:                         foreach my $role ('ca','aa') { 
 8832:                             if ($env{"user.role.$role./$adom/$aname"}) {
 8833:                                 my ($start,$end) =
 8834:                                     split(/\./,$env{"user.role.$role./$adom/$aname"});
 8835:                                 if (($now >= $start) && (!$end || $end > $now)) {
 8836:                                     $ownaccess = 1;
 8837:                                     last;
 8838:                                 }
 8839:                             }
 8840:                         }
 8841:                     }
 8842:                 }
 8843:             }
 8844:         }
 8845:     }
 8846: 
 8847: # Course
 8848: 
 8849:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
 8850:         unless (($priv eq 'bro') && (!$ownaccess)) {
 8851:             $thisallowed.=$1;
 8852:         }
 8853:     }
 8854: 
 8855: # Domain
 8856: 
 8857:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
 8858:        =~/\Q$priv\E\&([^\:]*)/) {
 8859:         unless (($priv eq 'bro') && (!$ownaccess)) {
 8860:             $thisallowed.=$1;
 8861:         }
 8862:     }
 8863: 
 8864: # User who is not author or co-author might still be able to edit
 8865: # resource of an author in the domain (e.g., if Domain Coordinator).
 8866:     if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
 8867:         (&allowed('mdc',$env{'request.course.id'}))) {
 8868:         if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
 8869:             $thisallowed.=$1;
 8870:         }
 8871:     }
 8872: 
 8873: # Course: uri itself is a course
 8874:     my $courseuri=$uri;
 8875:     $courseuri=~s/\_(\d)/\/$1/;
 8876:     $courseuri=~s/^([^\/])/\/$1/;
 8877: 
 8878:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
 8879:        =~/\Q$priv\E\&([^\:]*)/) {
 8880:         if ($priv eq 'mip') {
 8881:             my $rem = $1;
 8882:             if (($uri ne '') && ($env{'request.course.id'} eq $uri) &&
 8883:                 ($env{'course.'.$env{'request.course.id'}.'.internal.courseowner'} eq $env{'user.name'}.':'.$env{'user.domain'})) {
 8884:                 my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 8885:                 if ($cdom ne '') {
 8886:                     my %passwdconf = &get_passwdconf($cdom);
 8887:                     if (ref($passwdconf{'crsownerchg'}) eq 'HASH') {
 8888:                         if (ref($passwdconf{'crsownerchg'}{'by'}) eq 'ARRAY') {
 8889:                             if (@{$passwdconf{'crsownerchg'}{'by'}}) {
 8890:                                 my @inststatuses = split(':',$env{'environment.inststatus'});
 8891:                                 unless (@inststatuses) {
 8892:                                     @inststatuses = ('default');
 8893:                                 }
 8894:                                 foreach my $status (@inststatuses) {
 8895:                                     if (grep(/^\Q$status\E$/,@{$passwdconf{'crsownerchg'}{'by'}})) {
 8896:                                         $thisallowed.=$rem;
 8897:                                     }
 8898:                                 }
 8899:                             }
 8900:                         }
 8901:                     }
 8902:                 }
 8903:             }
 8904:         } else {
 8905:             unless (($priv eq 'bro') && (!$ownaccess)) {
 8906:                 $thisallowed.=$1;
 8907:             }
 8908:         }
 8909:     }
 8910: 
 8911: # URI is an uploaded document for this course, default permissions don't matter
 8912: # not allowing 'edit' access (editupload) to uploaded course docs
 8913:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
 8914: 	$thisallowed='';
 8915:         my ($match)=&is_on_map($uri);
 8916:         if ($match) {
 8917:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
 8918:                   =~/\Q$priv\E\&([^\:]*)/) {
 8919:                 my $value = $1;
 8920:                 my $deeplinkblock;
 8921:                 unless ($nodeeplinkcheck) {
 8922:                     $deeplinkblock = &deeplink_check($priv,$symb,$uri);
 8923:                 }
 8924:                 if ($deeplinkblock) {
 8925:                     $thisallowed='D';
 8926:                 } elsif ($noblockcheck) {
 8927:                     $thisallowed.=$value;
 8928:                 } else {
 8929:                     my @blockers = &has_comm_blocking($priv,$symb,$uri,$ignorecache);
 8930:                     if (@blockers > 0) {
 8931:                         $thisallowed = 'B';
 8932:                     } else {
 8933:                         $thisallowed.=$value;
 8934:                     }
 8935:                 }
 8936:             }
 8937:         } else {
 8938:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
 8939:             if ($refuri) {
 8940:                 if ($refuri =~ m|^/adm/|) {
 8941:                     $thisallowed='F';
 8942:                 } else {
 8943:                     $refuri=&declutter($refuri);
 8944:                     my ($match) = &is_on_map($refuri);
 8945:                     if ($match) {
 8946:                         my $deeplinkblock;
 8947:                         unless ($nodeeplinkcheck) {
 8948:                             $deeplinkblock = &deeplink_check($priv,$symb,$refuri);
 8949:                         }
 8950:                         if ($deeplinkblock) {
 8951:                             $thisallowed='D';
 8952:                         } elsif ($noblockcheck) {
 8953:                             $thisallowed='F';
 8954:                         } else {
 8955:                             my @blockers = &has_comm_blocking($priv,'',$refuri,'',1);
 8956:                             if (@blockers > 0) {
 8957:                                 $thisallowed = 'B';
 8958:                             } else {
 8959:                                 $thisallowed='F';
 8960:                             }
 8961:                         }
 8962:                     }
 8963:                 }
 8964:             }
 8965:         }
 8966:     }
 8967: 
 8968:     if ($priv eq 'bre'
 8969: 	&& $thisallowed ne 'F' 
 8970: 	&& $thisallowed ne '2'
 8971: 	&& &is_portfolio_url($uri)) {
 8972: 	$thisallowed = &portfolio_access($uri,$clientip);
 8973:     }
 8974: 
 8975: # Full access at system, domain or course-wide level? Exit.
 8976:     if ($thisallowed=~/F/) {
 8977: 	return 'F';
 8978:     }
 8979: 
 8980: # If this is generating or modifying users, exit with special codes
 8981: 
 8982:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:vca:vaa:'=~/\:\Q$priv\E\:/) {
 8983: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
 8984: 	    my ($audom,$auname)=split('/',$uri);
 8985: # no author name given, so this just checks on the general right to make a co-author in this domain
 8986: 	    unless ($auname) { return $thisallowed; }
 8987: # an author name is given, so we are about to actually make a co-author for a certain account
 8988: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
 8989: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
 8990: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
 8991: 	} elsif (($priv eq 'vca') || ($priv eq 'vaa')) {
 8992:             my ($audom,$auname)=split('/',$uri);
 8993:             unless ($auname) { return $thisallowed; }
 8994:             unless (($env{'request.role'} eq "dc./$audom") ||
 8995:                     ($env{'request.role'} eq "ca./$uri")) {
 8996:                 return '';
 8997:             }
 8998: 	}
 8999: 	return $thisallowed;
 9000:     }
 9001: #
 9002: # Gathered so far: system, domain and course wide privileges
 9003: #
 9004: # Course: See if uri or referer is an individual resource that is part of 
 9005: # the course
 9006: 
 9007:     if ($env{'request.course.id'}) {
 9008: 
 9009:         if ($priv eq 'bre') {
 9010:             if (&is_coursetool_logo($uri)) {
 9011:                 return 'F';
 9012:             }
 9013:         }
 9014: 
 9015: # If this is modifying password (internal auth) domains must match for user and user's role.
 9016: 
 9017:         if ($priv eq 'mip') {
 9018:             if ($env{'user.domain'} eq $env{'request.role.domain'}) {
 9019:                 return $thisallowed;
 9020:             } else {
 9021:                 return '';
 9022:             }
 9023:         }
 9024: 
 9025:        $courseprivid=$env{'request.course.id'};
 9026:        if ($env{'request.course.sec'}) {
 9027:           $courseprivid.='/'.$env{'request.course.sec'};
 9028:        }
 9029:        $courseprivid=~s/\_/\//;
 9030:        my $checkreferer=1;
 9031:        my ($match,$cond)=&is_on_map($uri);
 9032:        if ($match) {
 9033:            $statecond=$cond;
 9034:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 9035:                =~/\Q$priv\E\&([^\:]*)/) {
 9036:                my $value = $1;
 9037:                if ($priv eq 'bre') {
 9038:                    my $deeplinkblock;
 9039:                    unless ($nodeeplinkcheck) {
 9040:                        $deeplinkblock = &deeplink_check($priv,$symb,$uri);
 9041:                    }
 9042:                    if ($deeplinkblock) {
 9043:                        $thisallowed = 'D';
 9044:                    } elsif ($noblockcheck) {
 9045:                        $thisallowed.=$value;
 9046:                    } else {
 9047:                        my @blockers = &has_comm_blocking($priv,$symb,$uri,$ignorecache);
 9048:                        if (@blockers > 0) {
 9049:                            $thisallowed = 'B';
 9050:                        } else {
 9051:                            $thisallowed.=$value;
 9052:                        }
 9053:                    }
 9054:                } else {
 9055:                    $thisallowed.=$value;
 9056:                }
 9057:                $checkreferer=0;
 9058:            }
 9059:        }
 9060: 
 9061:        if ($checkreferer) {
 9062: 	  my $refuri=$env{'httpref.'.$orguri};
 9063:             unless ($refuri) {
 9064:                 foreach my $key (keys(%env)) {
 9065: 		    if ($key=~/^httpref\..*\*/) {
 9066: 			my $pattern=$key;
 9067:                         $pattern=~s/^httpref\.\/res\///;
 9068:                         $pattern=~s/\*/\[\^\/\]\+/g;
 9069:                         $pattern=~s/\//\\\//g;
 9070:                         if ($orguri=~/$pattern/) {
 9071: 			    $refuri=$env{$key};
 9072:                         }
 9073:                     }
 9074:                 }
 9075:             }
 9076: 
 9077:          if ($refuri) { 
 9078: 	  $refuri=&declutter($refuri);
 9079:           my ($match,$cond)=&is_on_map($refuri);
 9080:             if ($match) {
 9081:               my $refstatecond=$cond;
 9082:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 9083:                   =~/\Q$priv\E\&([^\:]*)/) {
 9084:                   my $value = $1;
 9085:                   if ($priv eq 'bre') {
 9086:                       my $deeplinkblock;
 9087:                       unless ($nodeeplinkcheck) {
 9088:                           $deeplinkblock = &deeplink_check($priv,$symb,$refuri);
 9089:                       }
 9090:                       if ($deeplinkblock) {
 9091:                           $thisallowed = 'D';
 9092:                       } elsif ($noblockcheck) {
 9093:                           $thisallowed.=$value;
 9094:                       } else {
 9095:                           my @blockers = &has_comm_blocking($priv,'',$refuri,'',1);
 9096:                           if (@blockers > 0) {
 9097:                               $thisallowed = 'B';
 9098:                           } else {
 9099:                               $thisallowed.=$value;
 9100:                           }
 9101:                       }
 9102:                   } else {
 9103:                       $thisallowed.=$value;
 9104:                   }
 9105:                   $uri=$refuri;
 9106:                   $statecond=$refstatecond;
 9107:               }
 9108:           }
 9109:         }
 9110:        }
 9111:    }
 9112: 
 9113: #
 9114: # Gathered now: all privileges that could apply, and condition number
 9115: # 
 9116: #
 9117: # Full or no access?
 9118: #
 9119: 
 9120:     if ($thisallowed=~/F/) {
 9121: 	return 'F';
 9122:     }
 9123: 
 9124:     unless ($thisallowed) {
 9125:         return '';
 9126:     }
 9127: 
 9128: # Restrictions exist, deal with them
 9129: #
 9130: #   C:according to course preferences
 9131: #   R:according to resource settings
 9132: #   L:unless locked
 9133: #   X:according to user session state
 9134: #
 9135: 
 9136: # Possibly locked functionality, check all courses
 9137: # In roles.tab, L (unless locked) available for bre, pch, plc, pac and sma.
 9138: # Locks might take effect only after 10 minutes cache expiration for other
 9139: # courses, and 2 minutes for current course, in which user has st or ta role
 9140: # which is neither expired nor a future role (unless current course).
 9141: 
 9142:     my ($needlockcheck,$now,$crsonly);
 9143:     if ($thisallowed=~/L/) {
 9144:         $now = time;
 9145:         if ($priv eq 'bre') {
 9146:             if ($uri ne '') {
 9147:                 if ($orguri =~ m{^/+res/}) {
 9148:                     if ($uri =~ m{^lib/templates/}) {
 9149:                         if ($env{'request.course.id'}) {
 9150:                             $crsonly = 1;
 9151:                             $needlockcheck = 1;
 9152:                         }
 9153:                     } else {
 9154:                         $needlockcheck = 1;
 9155:                     }
 9156:                 } elsif ($env{'request.course.id'}) {
 9157:                     my ($crsdom,$crsnum) = split('_',$env{'request.course.id'});
 9158:                     if (($uri =~ m{^(adm|uploaded|public)/$crsdom/$crsnum/}) ||
 9159:                         ($uri =~ m{^adm/$match_domain/$match_username/\d+/(smppg|bulletinboard)$})) {
 9160:                         $crsonly = 1;
 9161:                     }
 9162:                     $needlockcheck = 1;
 9163:                 }
 9164:             }
 9165:         } elsif (($priv eq 'pch') || ($priv eq 'plc') || ($priv eq 'pac') || ($priv eq 'sma')) {
 9166:             $needlockcheck = 1;
 9167:         }
 9168:     }
 9169:     if ($needlockcheck) {
 9170:         foreach my $envkey (keys(%env)) {
 9171:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
 9172:                my $courseid=$2;
 9173:                my $roleid=$1.'.'.$2;
 9174:                $courseid=~s/^\///;
 9175:                unless ($env{'request.role'} eq $roleid) {
 9176:                    my ($start,$end) = split(/\./,$env{$envkey});
 9177:                    next unless (($now >= $start) && (!$end || $end > $now));
 9178:                }
 9179:                my $expiretime=600;
 9180:                if ($env{'request.role'} eq $roleid) {
 9181: 		  $expiretime=120;
 9182:                }
 9183: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
 9184:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
 9185:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
 9186: 		   &coursedescription($courseid,{'freshen_cache' => 1});
 9187:                }
 9188:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
 9189:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
 9190: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
 9191:                        &log($env{'user.domain'},$env{'user.name'},
 9192:                             $env{'user.home'},
 9193:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
 9194:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 9195:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 9196: 		       return '';
 9197:                    }
 9198:                }
 9199:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
 9200:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
 9201: 		   if ($env{$prefix.'priv.'.$priv.'.lock.expire'}>time) {
 9202:                        &log($env{'user.domain'},$env{'user.name'},
 9203:                             $env{'user.home'},
 9204:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
 9205:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 9206:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 9207: 		       return '';
 9208:                    }
 9209:                }
 9210: 	   }
 9211:        }
 9212:     }
 9213: 
 9214: #
 9215: # Rest of the restrictions depend on selected course
 9216: #
 9217: 
 9218:     unless ($env{'request.course.id'}) {
 9219: 	if ($thisallowed eq 'A') {
 9220: 	    return 'A';
 9221:         } elsif ($thisallowed eq 'B') {
 9222:             return 'B';
 9223: 	} else {
 9224: 	    return '1';
 9225: 	}
 9226:     }
 9227: 
 9228: #
 9229: # Now user is definitely in a course
 9230: #
 9231: 
 9232: 
 9233: # Course preferences
 9234: 
 9235:    if ($thisallowed=~/C/) {
 9236:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 9237:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
 9238:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
 9239: 	   =~/\Q$rolecode\E/) {
 9240: 	   if (($priv ne 'pch') && ($priv ne 'plc') && ($priv ne 'pac')) {
 9241: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 9242: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
 9243: 			$env{'request.course.id'});
 9244: 	   }
 9245:            return '';
 9246:        }
 9247: 
 9248:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
 9249: 	   =~/\Q$unamedom\E/) {
 9250: 	   if (($priv ne 'pch') && ($priv ne 'plc') && ($priv ne 'pac')) {
 9251: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
 9252: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
 9253: 			$env{'request.course.id'});
 9254: 	   }
 9255:            return '';
 9256:        }
 9257:    }
 9258: 
 9259: # Resource preferences
 9260: 
 9261:    if ($thisallowed=~/R/) {
 9262:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 9263:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
 9264: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
 9265: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 9266: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
 9267: 	   }
 9268: 	   return '';
 9269:        }
 9270:    }
 9271: 
 9272: # Restricted for deeplinked session?
 9273: 
 9274:     if ($env{'request.deeplink.login'}) {
 9275:         if ($env{'acc.deeplinkout'} && !$nodeeplinkout) {
 9276:             if (!$symb) { $symb=&symbread($uri,1); }
 9277:             if (($symb) && ($env{'acc.deeplinkout'}=~/\&\Q$symb\E\&/)) {
 9278:                 return '';
 9279:             }
 9280:         }
 9281:     }
 9282: 
 9283: # Restricted by state or randomout?
 9284: 
 9285:    if ($thisallowed=~/X/) {
 9286:       if ($env{'acc.randomout'}) {
 9287: 	 if (!$symb) { $symb=&symbread($uri,1); }
 9288:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
 9289:             return ''; 
 9290:          }
 9291:       }
 9292:       if (&condval($statecond)) {
 9293: 	 return '2';
 9294:       } else {
 9295:          return '';
 9296:       }
 9297:    }
 9298: 
 9299:     if ($thisallowed eq 'A') {
 9300: 	return 'A';
 9301:     } elsif ($thisallowed eq 'B') {
 9302:         return 'B';
 9303:     } elsif ($thisallowed eq 'D') {
 9304:         return 'D';
 9305:     }
 9306:    return 'F';
 9307: }
 9308: 
 9309: # ------------------------------------------- Check construction space access
 9310: 
 9311: sub constructaccess {
 9312:     my ($url,$setpriv)=@_;
 9313: 
 9314: # We do not allow editing of previous versions of files
 9315:     if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
 9316: 
 9317: # Get username and domain from URL
 9318:     my ($ownername,$ownerdomain,$ownerhome);
 9319: 
 9320:     ($ownerdomain,$ownername) =
 9321:         ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)(?:/daxepage|/daxeopen)?/priv/($match_domain)/($match_username)(?:/|$)});
 9322: 
 9323: # The URL does not really point to any authorspace, forget it
 9324:     unless (($ownername) && ($ownerdomain)) { return ''; }
 9325: 
 9326: # Now we need to see if the user has access to the authorspace of
 9327: # $ownername at $ownerdomain
 9328: 
 9329:     if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
 9330: # Real author for this?
 9331:        $ownerhome = $env{'user.home'};
 9332:        if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
 9333:           return ($ownername,$ownerdomain,$ownerhome);
 9334:        }
 9335:     } elsif (&is_course($ownerdomain,$ownername)) {
 9336: # Course Authoring Space?
 9337:         if ($env{'request.course.id'}) {
 9338:             if (($ownername eq $env{'course.'.$env{'request.course.id'}.'.num'}) &&
 9339:                 ($ownerdomain eq $env{'course.'.$env{'request.course.id'}.'.domain'})) {
 9340:                 if (&allowed('mdc',$env{'request.course.id'})) {
 9341:                     return if ($env{'course.'.$env{'request.course.id'}.'.internal.crsauthor'} eq '0');
 9342:                     unless ($env{'course.'.$env{'request.course.id'}.'.internal.crsauthor'}) {
 9343:                         my %domdefs = &get_domain_defaults($ownerdomain);
 9344:                         my $type = lc($env{'course.'.$env{'request.course.id'}.'.type'});
 9345:                         unless (($type eq 'community') || ($type eq 'placement')) {
 9346:                             $type = 'unofficial';
 9347:                             if ($env{'course.'.$env{'request.course.id'}.'internal.coursecode'} ne '') {
 9348:                                 $type = 'official';
 9349:                             } elsif ($env{'course.'.$env{'request.course.id'}.'internal.textbook'} ne '') {
 9350:                                 $type = 'textbook';
 9351:                             } else {
 9352:                                 $type = 'unofficial';
 9353:                             }
 9354:                         }
 9355:                         return if ($domdefs{$type.'crsauthor'} eq '0');
 9356:                     }
 9357:                     $ownerhome = $env{'course.'.$env{'request.course.id'}.'.home'};
 9358:                     return ($ownername,$ownerdomain,$ownerhome);
 9359:                 }
 9360:             }
 9361:         }
 9362:         return '';
 9363:     } else {
 9364: # Co-author for this?
 9365:         if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
 9366:             exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
 9367:             $ownerhome = &homeserver($ownername,$ownerdomain);
 9368:             return ($ownername,$ownerdomain,$ownerhome);
 9369:         }
 9370:     }
 9371: 
 9372: # We don't have any access right now. If we are not possibly going to do anything about this,
 9373: # we might as well leave
 9374:    unless ($setpriv) { return ''; }
 9375: 
 9376: # Backdoor access?
 9377:     my $allowed=&allowed('eco',$ownerdomain);
 9378: # Nope
 9379:     unless ($allowed) { return ''; }
 9380: # Looks like we may have access, but could be locked by the owner of the construction space
 9381:     if ($allowed eq 'U') {
 9382:         my %blocked=&get('environment',['domcoord.author'],
 9383:                          $ownerdomain,$ownername);
 9384: # Is blocked by owner
 9385:         if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
 9386:     }
 9387:     if (($allowed eq 'F') || ($allowed eq 'U')) {
 9388: # Grant temporary access
 9389:         my $then=$env{'user.login.time'};
 9390:         my $update=$env{'user.update.time'};
 9391:         if (!$update) { $update = $then; }
 9392:         my $refresh=$env{'user.refresh.time'};
 9393:         if (!$refresh) { $refresh = $update; }
 9394:         my $now = time;
 9395:         &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
 9396:                            $now,'ca','constructaccess');
 9397:         $ownerhome = &homeserver($ownername,$ownerdomain);
 9398:         return($ownername,$ownerdomain,$ownerhome);
 9399:     }
 9400: # No business here
 9401:     return '';
 9402: }
 9403: 
 9404: # ----------------------------------------------------------- Content Blocking
 9405: 
 9406: {
 9407: # Caches for faster Course Contents display where content blocking
 9408: # is in operation (i.e., interval param set) for timed quiz.
 9409: #
 9410: # User for whom data are being temporarily cached.
 9411: my $cacheduser='';
 9412: # Course for which data are being temporarily cached.
 9413: my $cachedcid='';
 9414: # Cached blockers for this user (a hash of blocking items). 
 9415: my %cachedblockers=();
 9416: # When the data were last cached.
 9417: my $cachedlast='';
 9418: 
 9419: sub load_all_blockers {
 9420:     my ($uname,$udom)=@_;
 9421:     if (($uname ne '') && ($udom ne '')) { 
 9422:         if (($cacheduser eq $uname.':'.$udom) &&
 9423:             ($cachedcid eq $env{'request.course.id'}) &&
 9424:             (abs($cachedlast-time)<5)) {
 9425:             return;
 9426:         }
 9427:     }
 9428:     $cachedlast=time;
 9429:     $cacheduser=$uname.':'.$udom;
 9430:     $cachedcid=$env{'request.course.id'};
 9431:     %cachedblockers = &get_commblock_resources();
 9432:     return;
 9433: }
 9434: 
 9435: sub get_comm_blocks {
 9436:     my ($cdom,$cnum) = @_;
 9437:     if ($cdom eq '' || $cnum eq '') {
 9438:         return unless ($env{'request.course.id'});
 9439:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 9440:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 9441:     }
 9442:     my %commblocks;
 9443:     my $hashid=$cdom.'_'.$cnum;
 9444:     my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
 9445:     if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
 9446:         %commblocks = %{$blocksref};
 9447:     } else {
 9448:         %commblocks = &dump('comm_block',$cdom,$cnum);
 9449:         my $cachetime = 600;
 9450:         &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
 9451:     }
 9452:     return %commblocks;
 9453: }
 9454: 
 9455: sub get_commblock_resources {
 9456:     my ($blocks) = @_;
 9457:     my %blockers = ();
 9458:     return %blockers unless ($env{'request.course.id'});
 9459:     my $courseurl = &courseid_to_courseurl($env{'request.course.id'});
 9460:     if ($env{'request.course.sec'}) {
 9461:         $courseurl .= '/'.$env{'request.course.sec'};
 9462:     }
 9463:     return %blockers if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseurl} =~/evb\&([^\:]*)/);
 9464:     my %commblocks;
 9465:     if (ref($blocks) eq 'HASH') {
 9466:         %commblocks = %{$blocks};
 9467:     } else {
 9468:         %commblocks = &get_comm_blocks();
 9469:     }
 9470:     return %blockers unless (keys(%commblocks) > 0); 
 9471:     my $navmap = Apache::lonnavmaps::navmap->new();
 9472:     return %blockers unless (ref($navmap));
 9473:     my $now = time;
 9474:     foreach my $block (keys(%commblocks)) {
 9475:         if ($block =~ /^(\d+)____(\d+)$/) {
 9476:             my ($start,$end) = ($1,$2);
 9477:             if ($start <= $now && $end >= $now) {
 9478:                 if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
 9479:                     if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
 9480:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
 9481:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
 9482:                                 $blockers{$block}{maps} = $commblocks{$block}{'blocks'}{'docs'}{'maps'}; 
 9483:                             }
 9484:                         }
 9485:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
 9486:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
 9487:                                 $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
 9488:                             }
 9489:                         }
 9490:                     }
 9491:                 }
 9492:             }
 9493:         } elsif ($block =~ /^firstaccess____(.+)$/) {
 9494:             my $item = $1;
 9495:             if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
 9496:                 if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
 9497:                     my (@interval,$mapname);
 9498:                     my $type = 'map';
 9499:                     if ($item eq 'course') {
 9500:                         $type = 'course';
 9501:                         @interval=&EXT("resource.0.interval");
 9502:                     } else {
 9503:                         if ($item =~ /___\d+___/) {
 9504:                             $type = 'resource';
 9505:                             @interval=&EXT("resource.0.interval",$item);
 9506:                         } else {
 9507:                             $mapname = &deversion($item);
 9508:                             if (ref($navmap)) {
 9509:                                 my $timelimit = $navmap->get_mapparam(undef,$mapname,'0.interval');
 9510:                                 @interval = ($timelimit,'map');
 9511:                             }
 9512:                         }
 9513:                     }
 9514:                     if ($interval[0] =~ /^(\d+)/) {
 9515:                         my $timelimit = $1; 
 9516:                         my $first_access;
 9517:                         if ($type eq 'resource') {
 9518:                             $first_access=&get_first_access($interval[1],$item);
 9519:                         } elsif ($type eq 'map') {
 9520:                             $first_access=&get_first_access($interval[1],undef,$item);
 9521:                         } else {
 9522:                             $first_access=&get_first_access($interval[1]);
 9523:                         }
 9524:                         if ($first_access) {
 9525:                             my $timesup = $first_access+$timelimit;
 9526:                             if ($timesup > $now) {
 9527:                                 my $activeblock;
 9528:                                 if ($type eq 'resource') {
 9529:                                     if (ref($navmap)) {
 9530:                                         my $res = $navmap->getBySymb($item);
 9531:                                         if ($res->answerable()) {
 9532:                                             $activeblock = 1;
 9533:                                         }
 9534:                                     }
 9535:                                 } elsif ($type eq 'map') {
 9536:                                     my $mapsymb = &symbread($mapname,1);
 9537:                                     if (($mapsymb) && (ref($navmap))) {
 9538:                                         my $mapres = $navmap->getBySymb($mapsymb);
 9539:                                         if (ref($mapres)) {
 9540:                                             my $first = $mapres->map_start();
 9541:                                             my $finish = $mapres->map_finish();
 9542:                                             my $it = $navmap->getIterator($first,$finish,undef,0,0);
 9543:                                             if (ref($it)) {
 9544:                                                 my $res;
 9545:                                                 while ($res = $it->next(undef,1)) {
 9546:                                                     next unless (ref($res));
 9547:                                                     my $symb = $res->symb();
 9548:                                                     next if (($symb eq $mapsymb) || ($symb eq ''));
 9549:                                                     @interval=&EXT("resource.0.interval",$symb);
 9550:                                                     if ($interval[1] eq 'map') {
 9551:                                                         if ($res->answerable()) {
 9552:                                                             $activeblock = 1;
 9553:                                                             last;
 9554:                                                         }
 9555:                                                     }
 9556:                                                 }
 9557:                                             }
 9558:                                         }
 9559:                                     }
 9560:                                 }
 9561:                                 if ($activeblock) {
 9562:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
 9563:                                          if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
 9564:                                              $blockers{$block}{'maps'} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
 9565:                                          }
 9566:                                     }
 9567:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
 9568:                                         if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
 9569:                                             $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
 9570:                                         }
 9571:                                     }
 9572:                                 }
 9573:                             }
 9574:                         }
 9575:                     }
 9576:                 }
 9577:             }
 9578:         }
 9579:     }
 9580:     return %blockers;
 9581: }
 9582: 
 9583: sub has_comm_blocking {
 9584:     my ($priv,$symb,$uri,$ignoresymbdb,$noenccheck,$blocked,$blocks) = @_;
 9585:     my @blockers;
 9586:     return unless ($env{'request.course.id'});
 9587:     return unless ($priv eq 'bre');
 9588:     return if ($env{'request.state'} eq 'construct');
 9589:     my $courseurl = &courseid_to_courseurl($env{'request.course.id'});
 9590:     if ($env{'request.course.sec'}) {
 9591:         $courseurl .= '/'.$env{'request.course.sec'};
 9592:     }
 9593:     return if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseurl} =~/evb\&([^\:]*)/);
 9594:     my %blockinfo;
 9595:     if (ref($blocks) eq 'HASH') {
 9596:         %blockinfo = &get_commblock_resources($blocks);
 9597:     } else {
 9598:         &load_all_blockers($env{'user.name'},$env{'user.domain'});
 9599:         %blockinfo = %cachedblockers;
 9600:     }
 9601:     return unless (keys(%blockinfo) > 0);
 9602:     my (%possibles,@symbs);
 9603:     if (!$symb) {
 9604:         $symb = &symbread($uri,1,1,1,\%possibles,$ignoresymbdb,$noenccheck);
 9605:     }
 9606:     if ($symb) {
 9607:         @symbs = ($symb);
 9608:     } elsif (keys(%possibles)) { 
 9609:         @symbs = keys(%possibles);
 9610:     }
 9611:     my $noblock;
 9612:     foreach my $symb (@symbs) {
 9613:         last if ($noblock);
 9614:         my ($map,$resid,$resurl)=&decode_symb($symb);
 9615:         foreach my $block (keys(%blockinfo)) {
 9616:             if ($block =~ /^firstaccess____(.+)$/) {
 9617:                 my $item = $1;
 9618:                 unless ($blocked) {
 9619:                     if (($item eq $map) || ($item eq $symb)) {
 9620:                         $noblock = 1;
 9621:                         last;
 9622:                     }
 9623:                 }
 9624:             }
 9625:             if (ref($blockinfo{$block}) eq 'HASH') {
 9626:                 if (ref($blockinfo{$block}{'resources'}) eq 'HASH') {
 9627:                     if ($blockinfo{$block}{'resources'}{$symb}) {
 9628:                         unless (grep(/^\Q$block\E$/,@blockers)) {
 9629:                             push(@blockers,$block);
 9630:                         }
 9631:                     }
 9632:                 }
 9633:                 if (ref($blockinfo{$block}{'maps'}) eq 'HASH') {
 9634:                     if ($blockinfo{$block}{'maps'}{$map}) {
 9635:                         unless (grep(/^\Q$block\E$/,@blockers)) {
 9636:                             push(@blockers,$block);
 9637:                         }
 9638:                     }
 9639:                 }
 9640:             }
 9641:         }
 9642:     }
 9643:     unless ($noblock) { 
 9644:         return @blockers;
 9645:     }
 9646:     return;
 9647: }
 9648: }
 9649: 
 9650: sub deeplink_check {
 9651:     my ($priv,$symb,$uri) = @_;
 9652:     return unless ($env{'request.course.id'});
 9653:     return unless ($priv eq 'bre');
 9654:     return if ($env{'request.state'} eq 'construct');
 9655:     return if ($env{'request.role.adv'});
 9656:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 9657:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 9658:     my (%possibles,@symbs);
 9659:     if (!$symb) {
 9660:         $symb = &symbread($uri,1,1,1,\%possibles);
 9661:     }
 9662:     if ($symb) {
 9663:         @symbs = ($symb);
 9664:     } elsif (keys(%possibles)) {
 9665:         @symbs = keys(%possibles);
 9666:     }
 9667: 
 9668:     my ($deeplink_symb,$allow);
 9669:     if ($env{'request.deeplink.login'}) {
 9670:         $deeplink_symb = &Apache::loncommon::deeplink_login_symb($cnum,$cdom);
 9671:     }
 9672:     foreach my $symb (@symbs) {
 9673:         last if ($allow);
 9674:         my $deeplink = &EXT("resource.0.deeplink",$symb);
 9675:         if ($deeplink eq '') {
 9676:             $allow = 1;
 9677:         } else {
 9678:             my ($state,$others,$listed,$scope,$protect) = split(/,/,$deeplink);
 9679:             if ($state ne 'only') {
 9680:                 $allow = 1;
 9681:             } else {
 9682:                 my $check_deeplink_entry;
 9683:                 if ($protect ne 'none') {
 9684:                     my ($acctype,$item) = split(/:/,$protect);
 9685:                     if (($acctype eq 'ltic') && ($env{'user.linkprotector'})) {
 9686:                         if (grep(/^\Q$item\Ec$/,split(/,/,$env{'user.linkprotector'}))) {
 9687:                             $check_deeplink_entry = 1
 9688:                         }
 9689:                     } elsif (($acctype eq 'ltid') && ($env{'user.linkprotector'})) {
 9690:                         if (grep(/^\Q$item\Ed$/,split(/,/,$env{'user.linkprotector'}))) {
 9691:                             $check_deeplink_entry = 1;
 9692:                         }
 9693:                     } elsif (($acctype eq 'key') && ($env{'user.deeplinkkey'})) {
 9694:                         if (grep(/^\Q$item\E$/,split(/,/,$env{'user.deeplinkkey'}))) {
 9695:                             $check_deeplink_entry = 1;
 9696:                         }
 9697:                     }
 9698:                 }
 9699:                 if (($protect eq 'none') || ($check_deeplink_entry)) {
 9700:                     if ($scope eq 'res') {
 9701:                         if ($symb eq $deeplink_symb) {
 9702:                             $allow = 1;
 9703:                         }
 9704:                     } elsif (($scope eq 'map') || ($scope eq 'rec')) {
 9705:                         my ($map_from_symb,$map_from_login);
 9706:                         $map_from_symb = &deversion((&decode_symb($symb))[0]);
 9707:                         if ($deeplink_symb =~ /\.(page|sequence)$/) {
 9708:                             $map_from_login = &deversion((&decode_symb($deeplink_symb))[2]);
 9709:                         } else {
 9710:                             $map_from_login = &deversion((&decode_symb($deeplink_symb))[0]);
 9711:                         }
 9712:                         if (($map_from_symb) && ($map_from_login)) {
 9713:                             if ($map_from_symb eq $map_from_login) {
 9714:                                 $allow = 1;
 9715:                             } elsif ($scope eq 'rec') {
 9716:                                 my @recurseup = &get_map_hierarchy($map_from_symb,$env{'request.course.id'});
 9717:                                 if (grep(/^\Q$map_from_login\E$/,@recurseup)) {
 9718:                                     $allow = 1;
 9719:                                 }
 9720:                             }
 9721:                         }
 9722:                     }
 9723:                 }
 9724:             }
 9725:         }
 9726:     }
 9727:     return if ($allow);
 9728:     return 1;
 9729: }
 9730: 
 9731: # -------------------------------- Deversion and split uri into path an filename   
 9732: 
 9733: #
 9734: #   Removes the version from a URI and
 9735: #   splits it in to its filename and path to the filename.
 9736: #   Seems like File::Basename could have done this more clearly.
 9737: #   Parameters:
 9738: #      $uri   - input URI
 9739: #   Returns:
 9740: #     Two element list consisting of 
 9741: #     $pathname  - the URI up to and excluding the trailing /
 9742: #     $filename  - The part of the URI following the last /
 9743: #  NOTE:
 9744: #    Another realization of this is simply:
 9745: #    use File::Basename;
 9746: #    ...
 9747: #    $uri = shift;
 9748: #    $filename = basename($uri);
 9749: #    $path     = dirname($uri);
 9750: #    return ($filename, $path);
 9751: #
 9752: #     The implementation below is probably faster however.
 9753: #
 9754: sub split_uri_for_cond {
 9755:     my $uri=&deversion(&declutter(shift));
 9756:     my @uriparts=split(/\//,$uri);
 9757:     my $filename=pop(@uriparts);
 9758:     my $pathname=join('/',@uriparts);
 9759:     return ($pathname,$filename);
 9760: }
 9761: # --------------------------------------------------- Is a resource on the map?
 9762: 
 9763: sub is_on_map {
 9764:     my ($pathname,$filename) = &split_uri_for_cond(shift);
 9765:     #Trying to find the conditional for the file
 9766:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
 9767: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
 9768:     if ($match) {
 9769: 	return (1,$1);
 9770:     } else {
 9771: 	return (0,0);
 9772:     }
 9773: }
 9774: 
 9775: # --------------------------------------------------------- Get symb from alias
 9776: 
 9777: sub get_symb_from_alias {
 9778:     my $symb=shift;
 9779:     my ($map,$resid,$url)=&decode_symb($symb);
 9780: # Already is a symb
 9781:     if ($url) { return $symb; }
 9782: # Must be an alias
 9783:     my $aliassymb='';
 9784:     my %bighash;
 9785:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 9786:                             &GDBM_READER(),0640)) {
 9787:         my $rid=$bighash{'mapalias_'.$symb};
 9788: 	if ($rid) {
 9789: 	    my ($mapid,$resid)=split(/\./,$rid);
 9790: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
 9791: 				    $resid,$bighash{'src_'.$rid});
 9792: 	}
 9793:         untie %bighash;
 9794:     }
 9795:     return $aliassymb;
 9796: }
 9797: 
 9798: # ----------------------------------------------------------------- Define Role
 9799: 
 9800: sub definerole {
 9801:   if (allowed('mcr','/')) {
 9802:     my ($rolename,$sysrole,$domrole,$courole,$uname,$udom)=@_;
 9803:     foreach my $role (split(':',$sysrole)) {
 9804: 	my ($crole,$cqual)=split(/\&/,$role);
 9805:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
 9806:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
 9807: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 9808:                return "refused:s:$crole&$cqual"; 
 9809:             }
 9810:         }
 9811:     }
 9812:     foreach my $role (split(':',$domrole)) {
 9813: 	my ($crole,$cqual)=split(/\&/,$role);
 9814:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
 9815:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
 9816: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
 9817:                return "refused:d:$crole&$cqual"; 
 9818:             }
 9819:         }
 9820:     }
 9821:     foreach my $role (split(':',$courole)) {
 9822: 	my ($crole,$cqual)=split(/\&/,$role);
 9823:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
 9824:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
 9825: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 9826:                return "refused:c:$crole&$cqual"; 
 9827:             }
 9828:         }
 9829:     }
 9830:     my $uhome;
 9831:     if (($uname ne '') && ($udom ne '')) {
 9832:         $uhome = &homeserver($uname,$udom);
 9833:         return $uhome if ($uhome eq 'no_host');
 9834:     } else {
 9835:         $uname = $env{'user.name'};
 9836:         $udom = $env{'user.domain'};
 9837:         $uhome = $env{'user.home'};
 9838:     }
 9839:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
 9840:                 "$udom:$uname:rolesdef_$rolename=".
 9841:                 escape($sysrole.'_'.$domrole.'_'.$courole);
 9842:     return reply($command,$uhome);
 9843:   } else {
 9844:     return 'refused';
 9845:   }
 9846: }
 9847: 
 9848: # ---------------- Make a metadata query against the network of library servers
 9849: 
 9850: sub metadata_query {
 9851:     my ($query,$custom,$customshow,$server_array,$domains_hash)=@_;
 9852:     my %rhash;
 9853:     my %libserv = &all_library();
 9854:     my @server_list = (defined($server_array) ? @$server_array
 9855:                                               : keys(%libserv) );
 9856:     for my $server (@server_list) {
 9857:         my $domains = ''; 
 9858:         if (ref($domains_hash) eq 'HASH') {
 9859:             $domains = $domains_hash->{$server}; 
 9860:         }
 9861: 	unless ($custom or $customshow) {
 9862: 	    my $reply=&reply("querysend:".&escape($query).':::'.&escape($domains),$server);
 9863: 	    $rhash{$server}=$reply;
 9864: 	}
 9865: 	else {
 9866: 	    my $reply=&reply("querysend:".&escape($query).':'.
 9867: 			     &escape($custom).':'.&escape($customshow).':'.&escape($domains),
 9868: 			     $server);
 9869: 	    $rhash{$server}=$reply;
 9870: 	}
 9871:     }
 9872:     return \%rhash;
 9873: }
 9874: 
 9875: # ----------------------------------------- Send log queries and wait for reply
 9876: 
 9877: sub log_query {
 9878:     my ($uname,$udom,$query,%filters)=@_;
 9879:     my $uhome=&homeserver($uname,$udom);
 9880:     if ($uhome eq 'no_host') { return 'error: no_host'; }
 9881:     my $uhost=&hostname($uhome);
 9882:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
 9883:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
 9884:                        $uhome);
 9885:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
 9886:     return get_query_reply($queryid);
 9887: }
 9888: 
 9889: # -------------------------- Update MySQL table for portfolio file
 9890: 
 9891: sub update_portfolio_table {
 9892:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
 9893:     if ($group ne '') {
 9894:         $file_name =~s /^\Q$group\E//;
 9895:     }
 9896:     my $homeserver = &homeserver($uname,$udom);
 9897:     my $queryid=
 9898:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
 9899:                ':'.&escape($file_name).':'.$action,$homeserver);
 9900:     my $reply = &get_query_reply($queryid);
 9901:     return $reply;
 9902: }
 9903: 
 9904: # -------------------------- Update MySQL allusers table
 9905: 
 9906: sub update_allusers_table {
 9907:     my ($uname,$udom,$names) = @_;
 9908:     my $homeserver = &homeserver($uname,$udom);
 9909:     my $queryid=
 9910:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
 9911:                'lastname='.&escape($names->{'lastname'}).'%%'.
 9912:                'firstname='.&escape($names->{'firstname'}).'%%'.
 9913:                'middlename='.&escape($names->{'middlename'}).'%%'.
 9914:                'generation='.&escape($names->{'generation'}).'%%'.
 9915:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
 9916:                'id='.&escape($names->{'id'}),$homeserver);
 9917:     return;
 9918: }
 9919: 
 9920: # ------- Request retrieval of institutional classlists for course(s)
 9921: 
 9922: sub fetch_enrollment_query {
 9923:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
 9924:     my ($homeserver,$sleep,$loopmax);
 9925:     my $maxtries = 1;
 9926:     if ($context eq 'automated') {
 9927:         $homeserver = $perlvar{'lonHostID'};
 9928:         $sleep = 2;
 9929:         $loopmax = 100;
 9930:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
 9931:     } else {
 9932:         $homeserver = &homeserver($cnum,$dom);
 9933:     }
 9934:     my $host=&hostname($homeserver);
 9935:     my $cmd = '';
 9936:     foreach my $affiliate (keys(%{$affiliatesref})) {
 9937:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
 9938:     }
 9939:     $cmd =~ s/%%$//;
 9940:     $cmd = &escape($cmd);
 9941:     my $query = 'fetchenrollment';
 9942:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
 9943:     unless ($queryid=~/^\Q$host\E\_/) { 
 9944:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
 9945:         return 'error: '.$queryid;
 9946:     }
 9947:     my $reply = &get_query_reply($queryid,$sleep,$loopmax);
 9948:     my $tries = 1;
 9949:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 9950:         $reply = &get_query_reply($queryid,$sleep,$loopmax);
 9951:         $tries ++;
 9952:     }
 9953:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 9954:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 9955:     } else {
 9956:         my @responses = split(/:/,$reply);
 9957:         if (grep { $_ eq $homeserver } &current_machine_ids()) {
 9958:             foreach my $line (@responses) {
 9959:                 my ($key,$value) = split(/=/,$line,2);
 9960:                 $$replyref{$key} = $value;
 9961:             }
 9962:         } else {
 9963:             my $pathname = LONCAPA::tempdir();
 9964:             foreach my $line (@responses) {
 9965:                 my ($key,$value) = split(/=/,$line);
 9966:                 $$replyref{$key} = $value;
 9967:                 if ($value > 0) {
 9968:                     foreach my $item (@{$$affiliatesref{$key}}) {
 9969:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
 9970:                         my $destname = $pathname.'/'.$filename;
 9971:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
 9972:                         if ($xml_classlist =~ /^error/) {
 9973:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
 9974:                         } else {
 9975:                             if ( open(FILE,">",$destname) ) {
 9976:                                 print FILE &unescape($xml_classlist);
 9977:                                 close(FILE);
 9978:                             } else {
 9979:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
 9980:                             }
 9981:                         }
 9982:                     }
 9983:                 }
 9984:             }
 9985:         }
 9986:         return 'ok';
 9987:     }
 9988:     return 'error';
 9989: }
 9990: 
 9991: sub get_query_reply {
 9992:     my ($queryid,$sleep,$loopmax) = @_;
 9993:     if (($sleep eq '') || ($sleep !~ /^\d+\.?\d*$/)) {
 9994:         $sleep = 0.2;
 9995:     }
 9996:     if (($loopmax eq '') || ($loopmax =~ /\D/)) {
 9997:         $loopmax = 100;
 9998:     }
 9999:     my $replyfile=LONCAPA::tempdir().$queryid;
10000:     my $reply='';
10001:     for (1..$loopmax) {
10002: 	sleep($sleep);
10003:         if (-e $replyfile.'.end') {
10004: 	    if (open(my $fh,"<",$replyfile)) {
10005: 		$reply = join('',<$fh>);
10006: 		close($fh);
10007: 	   } else { return 'error: reply_file_error'; }
10008:            return &unescape($reply);
10009: 	}
10010:     }
10011:     return 'timeout:'.$queryid;
10012: }
10013: 
10014: sub courselog_query {
10015: #
10016: # possible filters:
10017: # url: url or symb
10018: # username
10019: # domain
10020: # action: view, submit, grade
10021: # start: timestamp
10022: # end: timestamp
10023: #
10024:     my (%filters)=@_;
10025:     unless ($env{'request.course.id'}) { return 'no_course'; }
10026:     if ($filters{'url'}) {
10027: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
10028:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
10029:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
10030:     }
10031:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
10032:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
10033:     return &log_query($cname,$cdom,'courselog',%filters);
10034: }
10035: 
10036: sub userlog_query {
10037: #
10038: # possible filters:
10039: # action: log check role
10040: # start: timestamp
10041: # end: timestamp
10042: #
10043:     my ($uname,$udom,%filters)=@_;
10044:     return &log_query($uname,$udom,'userlog',%filters);
10045: }
10046: 
10047: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
10048: 
10049: sub auto_run {
10050:     my ($cnum,$cdom) = @_;
10051:     my $response = 0;
10052:     my $settings;
10053:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
10054:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
10055:         $settings = $domconfig{'autoenroll'};
10056:         if ($settings->{'run'} eq '1') {
10057:             $response = 1;
10058:         }
10059:     } else {
10060:         my $homeserver;
10061:         if (&is_course($cdom,$cnum)) {
10062:             $homeserver = &homeserver($cnum,$cdom);
10063:         } else {
10064:             $homeserver = &domain($cdom,'primary');
10065:         }
10066:         if ($homeserver ne 'no_host') {
10067:             $response = &reply('autorun:'.$cdom,$homeserver);
10068:         }
10069:     }
10070:     return $response;
10071: }
10072: 
10073: sub auto_get_sections {
10074:     my ($cnum,$cdom,$inst_coursecode) = @_;
10075:     my $homeserver;
10076:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) { 
10077:         $homeserver = &homeserver($cnum,$cdom);
10078:     }
10079:     if (!defined($homeserver)) { 
10080:         if ($cdom =~ /^$match_domain$/) {
10081:             $homeserver = &domain($cdom,'primary');
10082:         }
10083:     }
10084:     my @secs;
10085:     if (defined($homeserver)) {
10086:         my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
10087:         unless ($response eq 'refused') {
10088:             @secs = split(/:/,$response);
10089:         }
10090:     }
10091:     return @secs;
10092: }
10093: 
10094: sub auto_new_course {
10095:     my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
10096:     my $homeserver = &homeserver($cnum,$cdom);
10097:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
10098:     return $response;
10099: }
10100: 
10101: sub auto_validate_courseID {
10102:     my ($cnum,$cdom,$inst_course_id) = @_;
10103:     my $homeserver = &homeserver($cnum,$cdom);
10104:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
10105:     return $response;
10106: }
10107: 
10108: sub auto_validate_instcode {
10109:     my ($cnum,$cdom,$instcode,$owner) = @_;
10110:     my ($homeserver,$response);
10111:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
10112:         $homeserver = &homeserver($cnum,$cdom);
10113:     }
10114:     if (!defined($homeserver)) {
10115:         if ($cdom =~ /^$match_domain$/) {
10116:             $homeserver = &domain($cdom,'primary');
10117:         }
10118:     }
10119:     $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
10120:                         &escape($instcode).':'.&escape($owner),$homeserver));
10121:     my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
10122:     return ($outcome,$description,$defaultcredits);
10123: }
10124: 
10125: sub auto_validate_inst_crosslist {
10126:     my ($cnum,$cdom,$instcode,$inst_xlist,$coowner) = @_;
10127:     my ($homeserver,$response);
10128:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
10129:         $homeserver = &homeserver($cnum,$cdom);
10130:     }
10131:     if (!defined($homeserver)) {
10132:         if ($cdom =~ /^$match_domain$/) {
10133:             $homeserver = &domain($cdom,'primary');
10134:         }
10135:     }
10136:     unless (($homeserver eq '') || ($homeserver eq 'no_host')) {
10137:         $response=&reply('autovalidateinstcrosslist:'.$cdom.':'.
10138:                          &escape($instcode).':'.&escape($inst_xlist).':'.
10139:                          &escape($coowner),$homeserver);
10140:     }
10141:     return $response;
10142: }
10143: 
10144: sub auto_create_password {
10145:     my ($cnum,$cdom,$authparam,$udom) = @_;
10146:     my ($homeserver,$response);
10147:     my $create_passwd = 0;
10148:     my $authchk = '';
10149:     if ($udom =~ /^$match_domain$/) {
10150:         $homeserver = &domain($udom,'primary');
10151:     }
10152:     if ($homeserver eq '') {
10153:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
10154:             $homeserver = &homeserver($cnum,$cdom);
10155:         }
10156:     }
10157:     if ($homeserver eq '') {
10158:         $authchk = 'nodomain';
10159:     } else {
10160:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
10161:         if ($response eq 'refused') {
10162:             $authchk = 'refused';
10163:         } else {
10164:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
10165:         }
10166:     }
10167:     return ($authparam,$create_passwd,$authchk);
10168: }
10169: 
10170: sub auto_photo_permission {
10171:     my ($cnum,$cdom,$students) = @_;
10172:     my $homeserver = &homeserver($cnum,$cdom);
10173:     my ($outcome,$perm_reqd,$conditions) = 
10174: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
10175:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
10176: 	return (undef,undef);
10177:     }
10178:     return ($outcome,$perm_reqd,$conditions);
10179: }
10180: 
10181: sub auto_checkphotos {
10182:     my ($uname,$udom,$pid) = @_;
10183:     my $homeserver = &homeserver($uname,$udom);
10184:     my ($result,$resulttype);
10185:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
10186: 				   &escape($uname).':'.&escape($pid),
10187: 				   $homeserver));
10188:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
10189: 	return (undef,undef);
10190:     }
10191:     if ($outcome) {
10192:         ($result,$resulttype) = split(/:/,$outcome);
10193:     } 
10194:     return ($result,$resulttype);
10195: }
10196: 
10197: sub auto_photochoice {
10198:     my ($cnum,$cdom) = @_;
10199:     my $homeserver = &homeserver($cnum,$cdom);
10200:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
10201: 						       &escape($cdom),
10202: 						       $homeserver)));
10203:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
10204: 	return (undef,undef);
10205:     }
10206:     return ($update,$comment);
10207: }
10208: 
10209: sub auto_photoupdate {
10210:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
10211:     my $homeserver = &homeserver($cnum,$dom);
10212:     my $host=&hostname($homeserver);
10213:     my $cmd = '';
10214:     my $maxtries = 1;
10215:     foreach my $affiliate (keys(%{$affiliatesref})) {
10216:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
10217:     }
10218:     $cmd =~ s/%%$//;
10219:     $cmd = &escape($cmd);
10220:     my $query = 'institutionalphotos';
10221:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
10222:     unless ($queryid=~/^\Q$host\E\_/) {
10223:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
10224:         return 'error: '.$queryid;
10225:     }
10226:     my $reply = &get_query_reply($queryid);
10227:     my $tries = 1;
10228:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
10229:         $reply = &get_query_reply($queryid);
10230:         $tries ++;
10231:     }
10232:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
10233:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
10234:     } else {
10235:         my @responses = split(/:/,$reply);
10236:         my $outcome = shift(@responses); 
10237:         foreach my $item (@responses) {
10238:             my ($key,$value) = split(/=/,$item);
10239:             $$photo{$key} = $value;
10240:         }
10241:         return $outcome;
10242:     }
10243:     return 'error';
10244: }
10245: 
10246: sub auto_instcode_format {
10247:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
10248: 	$cat_order) = @_;
10249:     my $courses = '';
10250:     my @homeservers;
10251:     if ($caller eq 'global') {
10252: 	my %servers = &get_servers($codedom,'library');
10253: 	foreach my $tryserver (keys(%servers)) {
10254: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
10255: 		push(@homeservers,$tryserver);
10256: 	    }
10257:         }
10258:     } elsif ($caller eq 'requests') {
10259:         if ($codedom =~ /^$match_domain$/) {
10260:             my $chome = &domain($codedom,'primary');
10261:             unless ($chome eq 'no_host') {
10262:                 push(@homeservers,$chome);
10263:             }
10264:         }
10265:     } else {
10266:         push(@homeservers,&homeserver($caller,$codedom));
10267:     }
10268:     foreach my $code (keys(%{$instcodes})) {
10269:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
10270:     }
10271:     chop($courses);
10272:     my $ok_response = 0;
10273:     my $response;
10274:     while (@homeservers > 0 && $ok_response == 0) {
10275:         my $server = shift(@homeservers); 
10276:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
10277:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
10278:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
10279: 		split(/:/,$response);
10280:             %{$codes} = (%{$codes},&str2hash($codes_str));
10281:             push(@{$codetitles},&str2array($codetitles_str));
10282:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
10283:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
10284:             $ok_response = 1;
10285:         }
10286:     }
10287:     if ($ok_response) {
10288:         return 'ok';
10289:     } else {
10290:         return $response;
10291:     }
10292: }
10293: 
10294: sub auto_instcode_defaults {
10295:     my ($domain,$returnhash,$code_order) = @_;
10296:     my @homeservers;
10297: 
10298:     my %servers = &get_servers($domain,'library');
10299:     foreach my $tryserver (keys(%servers)) {
10300: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
10301: 	    push(@homeservers,$tryserver);
10302: 	}
10303:     }
10304: 
10305:     my $response;
10306:     foreach my $server (@homeservers) {
10307:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
10308:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
10309: 	
10310: 	foreach my $pair (split(/\&/,$response)) {
10311: 	    my ($name,$value)=split(/\=/,$pair);
10312: 	    if ($name eq 'code_order') {
10313: 		@{$code_order} = split(/\&/,&unescape($value));
10314: 	    } else {
10315: 		$returnhash->{&unescape($name)}=&unescape($value);
10316: 	    }
10317: 	}
10318: 	return 'ok';
10319:     }
10320: 
10321:     return $response;
10322: }
10323: 
10324: sub auto_possible_instcodes {
10325:     my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
10326:     unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') && 
10327:             (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
10328:         return;
10329:     }
10330:     my (@homeservers,$uhome);
10331:     if (defined(&domain($domain,'primary'))) {
10332:         $uhome=&domain($domain,'primary');
10333:         push(@homeservers,&domain($domain,'primary'));
10334:     } else {
10335:         my %servers = &get_servers($domain,'library');
10336:         foreach my $tryserver (keys(%servers)) {
10337:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
10338:                 push(@homeservers,$tryserver);
10339:             }
10340:         }
10341:     }
10342:     my $response;
10343:     foreach my $server (@homeservers) {
10344:         $response=&reply('autopossibleinstcodes:'.$domain,$server);
10345:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
10346:         my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) = 
10347:             split(':',$response);
10348:         @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
10349:         @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
10350:         foreach my $item (split('&',$cat_title)) {   
10351:             my ($name,$value)=split('=',$item);
10352:             $cat_titles->{&unescape($name)}=&thaw_unescape($value);
10353:         }
10354:         foreach my $item (split('&',$cat_order)) {
10355:             my ($name,$value)=split('=',$item);
10356:             $cat_orders->{&unescape($name)}=&thaw_unescape($value);
10357:         }
10358:         return 'ok';
10359:     }
10360:     return $response;
10361: }
10362: 
10363: sub auto_courserequest_checks {
10364:     my ($dom) = @_;
10365:     my ($homeserver,%validations);
10366:     if ($dom =~ /^$match_domain$/) {
10367:         $homeserver = &domain($dom,'primary');
10368:     }
10369:     unless ($homeserver eq 'no_host') {
10370:         my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
10371:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
10372:             my @items = split(/&/,$response);
10373:             foreach my $item (@items) {
10374:                 my ($key,$value) = split('=',$item);
10375:                 $validations{&unescape($key)} = &thaw_unescape($value);
10376:             }
10377:         }
10378:     }
10379:     return %validations; 
10380: }
10381: 
10382: sub auto_courserequest_validation {
10383:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist,$custominfo) = @_;
10384:     my ($homeserver,$response);
10385:     if ($dom =~ /^$match_domain$/) {
10386:         $homeserver = &domain($dom,'primary');
10387:     }
10388:     unless ($homeserver eq 'no_host') {
10389:         my $customdata;
10390:         if (ref($custominfo) eq 'HASH') {
10391:             $customdata = &freeze_escape($custominfo);
10392:         }
10393:         $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
10394:                                     ':'.&escape($crstype).':'.&escape($inststatuslist).
10395:                                     ':'.&escape($instcode).':'.&escape($instseclist).':'.
10396:                                     $customdata,$homeserver));
10397:     }
10398:     return $response;
10399: }
10400: 
10401: sub auto_validate_class_sec {
10402:     my ($cdom,$cnum,$owners,$inst_class) = @_;
10403:     my $homeserver = &homeserver($cnum,$cdom);
10404:     my $ownerlist;
10405:     if (ref($owners) eq 'ARRAY') {
10406:         $ownerlist = join(',',@{$owners});
10407:     } else {
10408:         $ownerlist = $owners;
10409:     }
10410:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
10411:                         &escape($ownerlist).':'.$cdom,$homeserver);
10412:     return $response;
10413: }
10414: 
10415: sub auto_instsec_reformat {
10416:     my ($cdom,$action,$instsecref) = @_;
10417:     return unless(($action eq 'clutter') || ($action eq 'declutter'));
10418:     my @homeservers;
10419:     if (defined(&domain($cdom,'primary'))) {
10420:         push(@homeservers,&domain($cdom,'primary'));
10421:     } else {
10422:         my %servers = &get_servers($cdom,'library');
10423:         foreach my $tryserver (keys(%servers)) {
10424:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
10425:                 push(@homeservers,$tryserver);
10426:             }
10427:         }
10428:     }
10429:     my $response;
10430:     my %reformatted = %{$instsecref};
10431:     foreach my $server (@homeservers) {
10432:         if (ref($instsecref) eq 'HASH') {
10433:             my $info = &freeze_escape($instsecref);
10434:             my $response=&reply('autoinstsecreformat:'.$cdom.':'.
10435:                                 $action.':'.$info,$server);
10436:             next if ($response =~ /(con_lost|error|no_such_host|refused|unknown_cmd)/);
10437:             my @items = split(/&/,$response);
10438:             foreach my $item (@items) {
10439:                 my ($key,$value) = split(/=/,$item);
10440:                 $reformatted{&unescape($key)} = &thaw_unescape($value);
10441:             }
10442:         }
10443:     }
10444:     return %reformatted;
10445: }
10446: 
10447: sub auto_validate_instclasses {
10448:     my ($cdom,$cnum,$owners,$classesref) = @_;
10449:     my ($homeserver,%validations);
10450:     $homeserver = &homeserver($cnum,$cdom);
10451:     unless ($homeserver eq 'no_host') {
10452:         my $ownerlist;
10453:         if (ref($owners) eq 'ARRAY') {
10454:             $ownerlist = join(',',@{$owners});
10455:         } else {
10456:             $ownerlist = $owners;
10457:         }
10458:         if (ref($classesref) eq 'HASH') {
10459:             my $classes = &freeze_escape($classesref);
10460:             my $response=&reply('autovalidateinstclasses:'.&escape($ownerlist).
10461:                                 ':'.$cdom.':'.$classes,$homeserver);
10462:             unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
10463:                 my @items = split(/&/,$response);
10464:                 foreach my $item (@items) {
10465:                     my ($key,$value) = split('=',$item);
10466:                     $validations{&unescape($key)} = &thaw_unescape($value);
10467:                 }
10468:             }
10469:         }
10470:     }
10471:     return %validations;
10472: }
10473: 
10474: sub auto_crsreq_update {
10475:     my ($cdom,$cnum,$crstype,$action,$ownername,$ownerdomain,$fullname,$title,
10476:         $code,$accessstart,$accessend,$inbound) = @_;
10477:     my ($homeserver,%crsreqresponse);
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($inbound) eq 'HASH') {
10484:             $info = &freeze_escape($inbound);
10485:         }
10486:         my $response=&reply('autocrsrequpdate:'.$cdom.':'.$cnum.':'.&escape($crstype).
10487:                             ':'.&escape($action).':'.&escape($ownername).':'.
10488:                             &escape($ownerdomain).':'.&escape($fullname).':'.
10489:                             &escape($title).':'.&escape($code).':'.
10490:                             &escape($accessstart).':'.&escape($accessend).':'.$info,
10491:                             $homeserver);
10492:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
10493:             my @items = split(/&/,$response);
10494:             foreach my $item (@items) {
10495:                 my ($key,$value) = split('=',$item);
10496:                 $crsreqresponse{&unescape($key)} = &thaw_unescape($value);
10497:             }
10498:         }
10499:     }
10500:     return \%crsreqresponse;
10501: }
10502: 
10503: sub auto_export_grades {
10504:     my ($cdom,$cnum,$inforef,$gradesref) = @_;
10505:     my ($homeserver,%exportresponse);
10506:     if ($cdom =~ /^$match_domain$/) {
10507:         $homeserver = &domain($cdom,'primary');
10508:     }
10509:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
10510:         my $info;
10511:         if (ref($inforef) eq 'HASH') {
10512:             $info = &freeze_escape($inforef);
10513:         }
10514:         if (ref($gradesref) eq 'HASH') {
10515:             my $grades = &freeze_escape($gradesref);
10516:             my $response=&reply('encrypt:autoexportgrades:'.$cdom.':'.$cnum.':'.
10517:                                 $info.':'.$grades,$homeserver);
10518:             unless ($response =~ /(con_lost|error|no_such_host|refused|unknown_cmd)/) {
10519:                 my @items = split(/&/,$response);
10520:                 foreach my $item (@items) {
10521:                     my ($key,$value) = split('=',$item);
10522:                     $exportresponse{&unescape($key)} = &thaw_unescape($value);
10523:                 }
10524:             }
10525:         }
10526:     }
10527:     return \%exportresponse;
10528: }
10529: 
10530: sub check_instcode_cloning {
10531:     my ($codedefaults,$code_order,$cloner,$clonefromcode,$clonetocode) = @_;
10532:     unless ((ref($codedefaults) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
10533:         return;
10534:     }
10535:     my $canclone;
10536:     if (@{$code_order} > 0) {
10537:         my $instcoderegexp ='^';
10538:         my @clonecodes = split(/\&/,$cloner);
10539:         foreach my $item (@{$code_order}) {
10540:             if (grep(/^\Q$item\E=/,@clonecodes)) {
10541:                 foreach my $pair (@clonecodes) {
10542:                     my ($key,$val) = split(/\=/,$pair,2);
10543:                     $val = &unescape($val);
10544:                     if ($key eq $item) {
10545:                         $instcoderegexp .= '('.$val.')';
10546:                         last;
10547:                     }
10548:                 }
10549:             } else {
10550:                 $instcoderegexp .= $codedefaults->{$item};
10551:             }
10552:         }
10553:         $instcoderegexp .= '$';
10554:         my (@from,@to);
10555:         eval {
10556:                (@from) = ($clonefromcode =~ /$instcoderegexp/);
10557:                (@to) = ($clonetocode =~ /$instcoderegexp/);
10558:         };
10559:         if ((@from > 0) && (@to > 0)) {
10560:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
10561:             if (!@diffs) {
10562:                 $canclone = 1;
10563:             }
10564:         }
10565:     }
10566:     return $canclone;
10567: }
10568: 
10569: sub default_instcode_cloning {
10570:     my ($clonedom,$domdefclone,$clonefromcode,$clonetocode,$codedefaultsref,$codeorderref) = @_;
10571:     my (%codedefaults,@code_order,$canclone);
10572:     if ((ref($codedefaultsref) eq 'HASH') && (ref($codeorderref) eq 'ARRAY')) {
10573:         %codedefaults = %{$codedefaultsref};
10574:         @code_order = @{$codeorderref};
10575:     } elsif ($clonedom) {
10576:         &auto_instcode_defaults($clonedom,\%codedefaults,\@code_order);
10577:     }
10578:     if (($domdefclone) && (@code_order)) {
10579:         my @clonecodes = split(/\+/,$domdefclone);
10580:         my $instcoderegexp ='^';
10581:         foreach my $item (@code_order) {
10582:             if (grep(/^\Q$item\E$/,@clonecodes)) {
10583:                 $instcoderegexp .= '('.$codedefaults{$item}.')';
10584:             } else {
10585:                 $instcoderegexp .= $codedefaults{$item};
10586:             }
10587:         }
10588:         $instcoderegexp .= '$';
10589:         my (@from,@to);
10590:         eval {
10591:             (@from) = ($clonefromcode =~ /$instcoderegexp/);
10592:             (@to) = ($clonetocode =~ /$instcoderegexp/);
10593:         };
10594:         if ((@from > 0) && (@to > 0)) {
10595:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
10596:             if (!@diffs) {
10597:                 $canclone = 1;
10598:             }
10599:         }
10600:     }
10601:     return $canclone;
10602: }
10603: 
10604: # ------------------------------------------------------- Course Group routines
10605: 
10606: sub get_coursegroups {
10607:     my ($cdom,$cnum,$group,$namespace) = @_;
10608:     return(&dump($namespace,$cdom,$cnum,$group));
10609: }
10610: 
10611: sub modify_coursegroup {
10612:     my ($cdom,$cnum,$groupsettings) = @_;
10613:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
10614: }
10615: 
10616: sub toggle_coursegroup_status {
10617:     my ($cdom,$cnum,$group,$action) = @_;
10618:     my ($from_namespace,$to_namespace);
10619:     if ($action eq 'delete') {
10620:         $from_namespace = 'coursegroups';
10621:         $to_namespace = 'deleted_groups';
10622:     } else {
10623:         $from_namespace = 'deleted_groups';
10624:         $to_namespace = 'coursegroups';
10625:     }
10626:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
10627:     if (my $tmp = &error(%curr_group)) {
10628:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
10629:         return ('read error',$tmp);
10630:     } else {
10631:         my %savedsettings = %curr_group; 
10632:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
10633:         my $deloutcome;
10634:         if ($result eq 'ok') {
10635:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
10636:         } else {
10637:             return ('write error',$result);
10638:         }
10639:         if ($deloutcome eq 'ok') {
10640:             return 'ok';
10641:         } else {
10642:             return ('delete error',$deloutcome);
10643:         }
10644:     }
10645: }
10646: 
10647: sub modify_group_roles {
10648:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context,
10649:         $othdomby,$requester) = @_;
10650:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
10651:     my $role = 'gr/'.&escape($userprivs);
10652:     my ($uname,$udom) = split(/:/,$user);
10653:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context,
10654:                              $othdomby,$requester);
10655:     if ($result eq 'ok') {
10656:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
10657:     }
10658:     return $result;
10659: }
10660: 
10661: sub modify_coursegroup_membership {
10662:     my ($cdom,$cnum,$membership) = @_;
10663:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
10664:     return $result;
10665: }
10666: 
10667: sub get_active_groups {
10668:     my ($udom,$uname,$cdom,$cnum) = @_;
10669:     my $now = time;
10670:     my %groups = ();
10671:     foreach my $key (keys(%env)) {
10672:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
10673:             my ($start,$end) = split(/\./,$env{$key});
10674:             if (($end!=0) && ($end<$now)) { next; }
10675:             if (($start!=0) && ($start>$now)) { next; }
10676:             if ($1 eq $cdom && $2 eq $cnum) {
10677:                 $groups{$3} = $env{$key} ;
10678:             }
10679:         }
10680:     }
10681:     return %groups;
10682: }
10683: 
10684: sub get_group_membership {
10685:     my ($cdom,$cnum,$group) = @_;
10686:     return(&dump('groupmembership',$cdom,$cnum,$group));
10687: }
10688: 
10689: sub get_users_groups {
10690:     my ($udom,$uname,$courseid) = @_;
10691:     my @usersgroups;
10692:     my $cachetime=1800;
10693: 
10694:     my $hashid="$udom:$uname:$courseid";
10695:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
10696:     if (defined($cached)) {
10697:         @usersgroups = split(/:/,$grouplist);
10698:     } else {  
10699:         $grouplist = '';
10700:         my $courseurl = &courseid_to_courseurl($courseid);
10701:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
10702:         my $access_end = $env{'course.'.$courseid.
10703:                               '.default_enrollment_end_date'};
10704:         my $now = time;
10705:         foreach my $key (keys(%roleshash)) {
10706:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
10707:                 my $group = $1;
10708:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
10709:                     my $start = $2;
10710:                     my $end = $1;
10711:                     if ($start == -1) { next; } # deleted from group
10712:                     if (($start!=0) && ($start>$now)) { next; }
10713:                     if (($end!=0) && ($end<$now)) {
10714:                         if ($access_end && $access_end < $now) {
10715:                             if ($access_end - $end < 86400) {
10716:                                 push(@usersgroups,$group);
10717:                             }
10718:                         }
10719:                         next;
10720:                     }
10721:                     push(@usersgroups,$group);
10722:                 }
10723:             }
10724:         }
10725:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
10726:         $grouplist = join(':',@usersgroups);
10727:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
10728:     }
10729:     return @usersgroups;
10730: }
10731: 
10732: sub devalidate_getgroups_cache {
10733:     my ($udom,$uname,$cdom,$cnum)=@_;
10734:     my $courseid = $cdom.'_'.$cnum;
10735: 
10736:     my $hashid="$udom:$uname:$courseid";
10737:     &devalidate_cache_new('getgroups',$hashid);
10738: }
10739: 
10740: # ------------------------------------------------------------------ Plain Text
10741: 
10742: sub plaintext {
10743:     my ($short,$type,$cid,$forcedefault) = @_;
10744:     if ($short =~ m{^cr/}) {
10745: 	return (split('/',$short))[-1];
10746:     }
10747:     if (!defined($cid)) {
10748:         $cid = $env{'request.course.id'};
10749:     }
10750:     my %rolenames = (
10751:                       Course    => 'std',
10752:                       Community => 'alt1',
10753:                       Placement => 'std',
10754:                     );
10755:     if ($cid ne '') {
10756:         if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
10757:             unless ($forcedefault) {
10758:                 my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
10759:                 &Apache::lonlocal::mt_escape(\$roletext);
10760:                 return &Apache::lonlocal::mt($roletext);
10761:             }
10762:         }
10763:     }
10764:     if ((defined($type)) && (defined($rolenames{$type})) &&
10765:         (defined($rolenames{$type})) && 
10766:         (defined($prp{$short}{$rolenames{$type}}))) {
10767:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
10768:     } elsif ($cid ne '') {
10769:         my $crstype = $env{'course.'.$cid.'.type'};
10770:         if (($crstype ne '') && (defined($rolenames{$crstype})) &&
10771:             (defined($prp{$short}{$rolenames{$crstype}}))) {
10772:             return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
10773:         }
10774:     }
10775:     return &Apache::lonlocal::mt($prp{$short}{'std'});
10776: }
10777: 
10778: # ----------------------------------------------------------------- Assign Role
10779: 
10780: sub assignrole {
10781:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
10782:         $context,$othdomby,$requester,$reqsec,$reqrole)=@_;
10783:     my ($mrole,$rolelogcontext);
10784:     if ($role =~ /^cr\//) {
10785:         my $cwosec=$url;
10786:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
10787:         if ((!&allowed('ccr',$cwosec)) && (!&allowed('ccr',$udom))) {
10788:             my $refused = 1;
10789:             if ($context eq 'requestcourses') {
10790:                 if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
10791:                     if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
10792:                         if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
10793:                             my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
10794:                             my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
10795:                             if ($crsenv{'internal.courseowner'} eq
10796:                                 $env{'user.name'}.':'.$env{'user.domain'}) {
10797:                                 $refused = '';
10798:                             }
10799:                         }
10800:                     }
10801:                 }
10802:             } elsif (($context eq 'course') && ($othdomby eq 'othdombyuser')) {
10803:                 my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
10804:                 my ($sec) = ($url =~ m{^/\Q$cwosec\E/(.*)$});
10805:                 my $key = "$uname:$udom:$role:$sec";
10806:                 my %queuedrolereq = &Apache::lonnet::get('nohist_othdomqueued',[$key],$cdom,$cnum);
10807:                 if ((exists($queuedrolereq{$key})) && (ref($queuedrolereq{$key}) eq 'HASH')) {
10808:                     if (($queuedrolereq{$key}{'adj'} eq 'user') && ($queuedrolereq{$key}{'requester'} eq $requester)) {
10809:                         $refused = '';
10810:                     }
10811:                 }
10812:             }
10813:             if ($refused) {
10814:                 &logthis('Refused custom assignrole: '.
10815:                          $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
10816:                          ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
10817:                 return 'refused';
10818:             }
10819:         }
10820:         $mrole='cr';
10821:     } elsif ($role =~ /^gr\//) {
10822:         my $cwogrp=$url;
10823:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
10824:         if (!&allowed('mdg',$cwogrp)) {
10825:             my $refused = 1;
10826:             if (($refused) && ($othdomby eq 'othdombyuser') && ($requester ne '') && ($reqrole ne '')) {
10827:                 my ($cdom,$cnum) = ($cwogrp =~ m{^/?($match_domain)/($match_courseid)$});
10828:                 my $key = "$uname:$udom:$reqrole:$reqsec";
10829:                 my %queuedrolereq = &Apache::lonnet::get('nohist_othdomqueued',[$key],$cdom,$cnum);
10830:                 if ((exists($queuedrolereq{$key})) && (ref($queuedrolereq{$key}) eq 'HASH')) {
10831:                     if (($queuedrolereq{$key}{'adj'} eq 'user') && ($queuedrolereq{$key}{'requester'} eq $requester)) {
10832:                         $refused = '';
10833:                     }
10834:                 }
10835:             }
10836:             if ($refused) {
10837:                 &logthis('Refused group assignrole: '.
10838:                          $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
10839:                          $env{'user.name'}.' at '.$env{'user.domain'});
10840:                 return 'refused';
10841:             }
10842:         }
10843:         $mrole='gr';
10844:     } else {
10845:         my $cwosec=$url;
10846:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
10847:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
10848:             my $refused;
10849:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
10850:                 if (!(&allowed('c'.$role,$url))) {
10851:                     $refused = 1;
10852:                 }
10853:             } else {
10854:                 $refused = 1;
10855:             }
10856:             if ($refused) {
10857:                 my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
10858:                 if (!$selfenroll && ($othdomby ne 'othdombyuser') &&
10859:                    (($context eq 'course') || ($context eq 'ltienroll' && $env{'request.lti.login'}))) {
10860:                     my %crsenv;
10861:                     if ($role eq 'cc' || $role eq 'co') {
10862:                         %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
10863:                         if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
10864:                             if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
10865:                                 if ($crsenv{'internal.courseowner'} eq 
10866:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
10867:                                     $refused = '';
10868:                                 }
10869:                             }
10870:                         } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) { 
10871:                             if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
10872:                                 if ($crsenv{'internal.courseowner'} eq 
10873:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
10874:                                     $refused = '';
10875:                                 }
10876:                             }
10877:                         }
10878:                     }
10879:                 } elsif (($selfenroll == 1) && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
10880:                     if ($role eq 'st') {
10881:                         $refused = '';
10882:                     } elsif (($context eq 'ltienroll') && ($env{'request.lti.login'})) {
10883:                         $refused = '';
10884:                     }
10885:                 } elsif ($othdomby eq 'othdombyuser') {
10886:                     my ($key,%queuedrolereq);
10887:                     if ($context eq 'course') {
10888:                         my ($sec) = ($url =~ m{^/\Q$cwosec\E/(.*)$});
10889:                         $key = "$uname:$udom:$role:$sec";
10890:                         %queuedrolereq = &Apache::lonnet::get('nohist_othdomqueued',[$key],$cdom,$cnum);
10891:                         if ((exists($queuedrolereq{$key})) && (ref($queuedrolereq{$key}) eq 'HASH')) {
10892:                             if (($queuedrolereq{$key}{'adj'} eq 'user') && ($queuedrolereq{$key}{'requester'} eq $requester)) {
10893:                                 if ((($role eq 'cc') && ($cnum !~ /^$match_community$/)) || 
10894:                                     (($role eq 'co') && ($cnum =~ /^$match_community$/))) {
10895:                                     my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
10896:                                     if ($crsenv{'internal.courseowner'} eq $requester) {
10897:                                         $refused = '';
10898:                                     }
10899:                                 } elsif ($role =~ /^(?:in|ta|ep|st)$/) {
10900:                                     $refused = '';
10901:                                 }
10902:                             }
10903:                         }
10904:                     } elsif (($context eq 'author') && ($role =~ /^ca|aa$/)) {
10905:                         my $key = "$uname:$udom:$role"; 
10906:                         my ($audom,$auname) = ($url =~ m{^/($match_domain)/($match_username)$});
10907:                         if (($audom ne '') && ($auname ne '')) {
10908:                             my %queuedrolereq = &Apache::lonnet::get('nohist_othdomqueued',[$key],$audom,$auname);
10909:                             if ((exists($queuedrolereq{$key})) && (ref($queuedrolereq{$key}) eq 'HASH')) {
10910:                                 if (($queuedrolereq{$key}{'adj'} eq 'user') && ($queuedrolereq{$key}{'requester'} eq $requester)) {
10911:                                     $refused = '';
10912:                                 }
10913:                             }
10914:                         }
10915:                     } elsif (($context eq 'domain') && ($role ne 'dc') && ($role ne 'su')) {
10916:                         my $key = "$uname:$udom:$role";
10917:                         my ($roledom) = ($url =~ m{^/($match_domain)/\Q$role\E$});
10918:                         if ($roledom ne '') {
10919:                             my $confname = $roledom.'-domainconfig';
10920:                             my %queuedrolereq = &Apache::lonnet::get('nohist_othdomqueued',[$key],$roledom,$confname);
10921:                             if ((exists($queuedrolereq{$key})) && (ref($queuedrolereq{$key}) eq 'HASH')) {
10922:                                 if (($queuedrolereq{$key}{'adj'} eq 'user') && ($queuedrolereq{$key}{'requester'} eq $requester)) {
10923:                                     $refused = '';
10924:                                 }
10925:                             }
10926:                         }
10927:                     }
10928:                 } elsif ($context eq 'requestcourses') {
10929:                     my @possroles = ('st','ta','ep','in','cc','co');
10930:                     if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
10931:                         my $wrongcc;
10932:                         if ($cnum =~ /^$match_community$/) {
10933:                             $wrongcc = 1 if ($role eq 'cc');
10934:                         } else {
10935:                             $wrongcc = 1 if ($role eq 'co');
10936:                         }
10937:                         unless ($wrongcc) {
10938:                             my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
10939:                             if ($crsenv{'internal.courseowner'} eq 
10940:                                  $env{'user.name'}.':'.$env{'user.domain'}) {
10941:                                 $refused = '';
10942:                             }
10943:                         }
10944:                     }
10945:                 } elsif ($context eq 'requestauthor') {
10946:                     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) && 
10947:                         ($url eq '/'.$udom.'/') && ($role eq 'au')) {
10948:                         if ($env{'environment.requestauthor'} eq 'automatic') {
10949:                             $refused = '';
10950:                         } else {
10951:                             my %domdefaults = &get_domain_defaults($udom);
10952:                             if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
10953:                                 my $checkbystatus;
10954:                                 if ($env{'user.adv'}) { 
10955:                                     my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
10956:                                     if ($disposition eq 'automatic') {
10957:                                         $refused = '';
10958:                                     } elsif ($disposition eq '') {
10959:                                         $checkbystatus = 1;
10960:                                     } 
10961:                                 } else {
10962:                                     $checkbystatus = 1;
10963:                                 }
10964:                                 if ($checkbystatus) {
10965:                                     if ($env{'environment.inststatus'}) {
10966:                                         my @inststatuses = split(/,/,$env{'environment.inststatus'});
10967:                                         foreach my $type (@inststatuses) {
10968:                                             if (($type ne '') &&
10969:                                                 ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
10970:                                                 $refused = '';
10971:                                             }
10972:                                         }
10973:                                     } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
10974:                                         $refused = '';
10975:                                     }
10976:                                 }
10977:                             }
10978:                         }
10979:                     }
10980:                 } elsif (($context eq 'author') && (($role eq 'ca' || $role eq 'aa'))) {
10981:                     if ($url =~ m{^/($match_domain)/($match_username)$}) {
10982:                         my ($audom,$auname) = ($1,$2);
10983:                         if ((&Apache::lonnet::allowed('v'.$role,"$audom/$auname")) &&
10984:                             ($env{"environment.internal.manager.$url"})) {
10985:                             $refused = '';
10986:                             $rolelogcontext = 'coauthor';
10987:                         }
10988:                     }
10989:                 }
10990:                 if ($refused) {
10991:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
10992:                              ' '.$role.' '.$end.' '.$start.' by '.
10993: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
10994:                     return 'refused';
10995:                 }
10996:             }
10997:         } elsif ($role eq 'au') {
10998:             if ($url ne '/'.$udom.'/') {
10999:                 &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
11000:                          ' to assign author role for '.$uname.':'.$udom.
11001:                          ' in domain: '.$url.' refused (wrong domain).');
11002:                 return 'refused';
11003:             }
11004:         }
11005:         $mrole=$role;
11006:     }
11007:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
11008:                 "$udom:$uname:$url".'_'."$mrole=$role";
11009:     if ($end) { $command.='_'.$end; }
11010:     if ($start) {
11011: 	if ($end) { 
11012:            $command.='_'.$start; 
11013:         } else {
11014:            $command.='_0_'.$start;
11015:         }
11016:     }
11017:     my $origstart = $start;
11018:     my $origend = $end;
11019:     my $delflag;
11020: # actually delete
11021:     if ($deleteflag) {
11022: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
11023: # modify command to delete the role
11024:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
11025:                 "$udom:$uname:$url".'_'."$mrole";
11026: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
11027: # set start and finish to negative values for userrolelog
11028:            $start=-1;
11029:            $end=-1;
11030:            $delflag = 1;
11031:         }
11032:     }
11033: # send command
11034:     my $answer=&reply($command,&homeserver($uname,$udom));
11035: # log new user role if status is ok
11036:     if ($answer eq 'ok') {
11037: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
11038:         if (($role eq 'cc') || ($role eq 'in') ||
11039:             ($role eq 'ep') || ($role eq 'ad') ||
11040:             ($role eq 'ta') || ($role eq 'st') ||
11041:             ($role=~/^cr/) || ($role eq 'gr') ||
11042:             ($role eq 'co')) {
11043: # for course roles, perform group memberships changes triggered by role change.
11044:             unless ($role =~ /^gr/) {
11045:                 &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
11046:                                                  $origstart,$selfenroll,$context);
11047:             }
11048:             &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
11049:                            $selfenroll,$context,$othdomby,$requester);
11050:         } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
11051:                  ($role eq 'au') || ($role eq 'dc') || ($role eq 'dh') ||
11052:                  ($role eq 'da')) {
11053:             &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
11054:                            $context,$othdomby,$requester);
11055:         } elsif (($role eq 'ca') || ($role eq 'aa')) {
11056:             if ($rolelogcontext eq '') {
11057:                 $rolelogcontext = $context;
11058:             }
11059:             &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
11060:                              $rolelogcontext,$othdomby,$requester); 
11061:         }
11062:         if ($role eq 'cc') {
11063:             &autoupdate_coowners($url,$end,$start,$uname,$udom);
11064:         }
11065:     }
11066:     return $answer;
11067: }
11068: 
11069: sub autoupdate_coowners {
11070:     my ($url,$end,$start,$uname,$udom) = @_;
11071:     my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
11072:     if (($cdom ne '') && ($cnum ne '')) {
11073:         my $now = time;
11074:         my %domdesign = &Apache::loncommon::get_domainconf($cdom);
11075:         if ($domdesign{$cdom.'.autoassign.co-owners'}) {
11076:             my %coursehash = &coursedescription($cdom.'_'.$cnum);
11077:             my $instcode = $coursehash{'internal.coursecode'};
11078:             my $xlists = $coursehash{'internal.crosslistings'};
11079:             if ($instcode ne '') {
11080:                 if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
11081:                     unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
11082:                         my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
11083:                         my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
11084:                         unless ($result eq 'valid') {
11085:                             if ($xlists ne '') {
11086:                                 foreach my $xlist (split(',',$xlists)) {
11087:                                     my ($inst_crosslist,$lcsec) = split(':',$xlist);
11088:                                     $result =
11089:                                         &auto_validate_inst_crosslist($cnum,$cdom,$instcode,
11090:                                                                       $inst_crosslist,$uname.':'.$udom);
11091:                                     last if ($result eq 'valid');
11092:                                 }
11093:                             }
11094:                         }
11095:                         if ($result eq 'valid') {
11096:                             if ($coursehash{'internal.co-owners'}) {
11097:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
11098:                                     push(@newcoowners,$coowner);
11099:                                 }
11100:                                 unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
11101:                                     push(@newcoowners,$uname.':'.$udom);
11102:                                 }
11103:                                 @newcoowners = sort(@newcoowners);
11104:                             } else {
11105:                                 push(@newcoowners,$uname.':'.$udom);
11106:                             }
11107:                         } elsif ($coursehash{'internal.co-owners'}) {
11108:                             foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
11109:                                 unless ($coowner eq $uname.':'.$udom) {
11110:                                     push(@newcoowners,$coowner);
11111:                                 }
11112:                             }
11113:                             unless (@newcoowners > 0) {
11114:                                 $delcoowners = 1;
11115:                                 $coowners = '';
11116:                             }
11117:                         }
11118:                         if (@newcoowners || $delcoowners) {
11119:                             &store_coowners($cdom,$cnum,$coursehash{'home'},
11120:                                             $delcoowners,@newcoowners);
11121:                         }
11122:                     }
11123:                 }
11124:             }
11125:         }
11126:     }
11127: }
11128: 
11129: sub store_coowners {
11130:     my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
11131:     my $cid = $cdom.'_'.$cnum;
11132:     my ($coowners,$delresult,$putresult);
11133:     if (@newcoowners) {
11134:         $coowners = join(',',@newcoowners);
11135:         my %coownershash = (
11136:                             'internal.co-owners' => $coowners,
11137:                            );
11138:         $putresult = &put('environment',\%coownershash,$cdom,$cnum);
11139:         if ($putresult eq 'ok') {
11140:             if ($env{'course.'.$cid.'.num'} eq $cnum) {
11141:                 &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
11142:             }
11143:         }
11144:     }
11145:     if ($delcoowners) {
11146:         $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
11147:         if ($delresult eq 'ok') {
11148:             if ($env{'course.'.$cid.'.internal.co-owners'}) {
11149:                 &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
11150:             }
11151:         }
11152:     }
11153:     if (($putresult eq 'ok') || ($delresult eq 'ok')) {
11154:         my %crsinfo =
11155:             &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
11156:         if (ref($crsinfo{$cid}) eq 'HASH') {
11157:             $crsinfo{$cid}{'co-owners'} = \@newcoowners;
11158:             my $cidput = &courseidput($cdom,\%crsinfo,$chome,'notime');
11159:         }
11160:     }
11161: }
11162: 
11163: # -------------------------------------------------- Modify user authentication
11164: # Overrides without validation
11165: 
11166: sub modifyuserauth {
11167:     my ($udom,$uname,$umode,$upass)=@_;
11168:     my $uhome=&homeserver($uname,$udom);
11169:     my $allowed;
11170:     if (&allowed('mau',$udom)) {
11171:         $allowed = 1;
11172:     } elsif (($umode eq 'internal') && ($udom eq $env{'user.domain'}) &&
11173:              ($env{'request.course.id'}) && (&allowed('mip',$env{'request.course.id'})) &&
11174:              (!$env{'course.'.$env{'request.course.id'}.'.internal.nopasswdchg'})) {
11175:         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
11176:         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
11177:         if (($cdom ne '') && ($cnum ne '')) {
11178:             my $is_owner = &is_course_owner($cdom,$cnum);
11179:             if ($is_owner) {
11180:                 $allowed = 1;
11181:             }
11182:         }
11183:     }
11184:     unless ($allowed) { return 'refused'; }
11185:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
11186:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
11187:              ' in domain '.$env{'request.role.domain'});  
11188:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
11189: 		     &escape($upass),$uhome);
11190:     my $ip = &get_requestor_ip();
11191:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
11192:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
11193:          '(Remote '.$ip.'): '.$reply);
11194:     &log($udom,,$uname,$uhome,
11195:         'Authentication changed by '.$env{'user.domain'}.', '.
11196:                                      $env{'user.name'}.', '.$umode.
11197:          '(Remote '.$ip.'): '.$reply);
11198:     unless ($reply eq 'ok') {
11199:         &logthis('Authentication mode error: '.$reply);
11200: 	return 'error: '.$reply;
11201:     }   
11202:     return 'ok';
11203: }
11204: 
11205: # --------------------------------------------------------------- Modify a user
11206: 
11207: sub modifyuser {
11208:     my ($udom,    $uname, $uid,
11209:         $umode,   $upass, $first,
11210:         $middle,  $last,  $gene,
11211:         $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
11212:     $udom= &LONCAPA::clean_domain($udom);
11213:     $uname=&LONCAPA::clean_username($uname);
11214:     my $showcandelete = 'none';
11215:     if (ref($candelete) eq 'ARRAY') {
11216:         if (@{$candelete} > 0) {
11217:             $showcandelete = join(', ',@{$candelete});
11218:         }
11219:     }
11220:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
11221:              $umode.', '.$first.', '.$middle.', '.
11222: 	     $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
11223:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
11224:                                      ' desiredhome not specified'). 
11225:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
11226:              ' in domain '.$env{'request.role.domain'});
11227:     my $uhome=&homeserver($uname,$udom,'true');
11228:     my $newuser;
11229:     if ($uhome eq 'no_host') {
11230:         $newuser = 1;
11231:         unless (($umode && ($upass ne '')) || ($umode eq 'localauth') ||
11232:                 ($umode eq 'lti')) {
11233:             return 'error: more information needed to create new user';
11234:         }
11235:     }
11236: # ----------------------------------------------------------------- Create User
11237:     if (($uhome eq 'no_host') && 
11238: 	(($umode && $upass) || ($umode eq 'localauth') || ($umode eq 'lti'))) {
11239:         my $unhome='';
11240:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
11241:             $unhome = $desiredhome;
11242: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
11243: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
11244:         } else { # load balancing routine for determining $unhome
11245:             my $loadm=10000000;
11246: 	    my %servers = &get_servers($udom,'library');
11247: 	    foreach my $tryserver (keys(%servers)) {
11248: 		my $answer=reply('load',$tryserver);
11249: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
11250: 		    $loadm=$answer;
11251: 		    $unhome=$tryserver;
11252: 		}
11253: 	    }
11254:         }
11255:         if (($unhome eq '') || ($unhome eq 'no_host')) {
11256: 	    return 'error: unable to find a home server for '.$uname.
11257:                    ' in domain '.$udom;
11258:         }
11259:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
11260:                          &escape($upass),$unhome);
11261: 	unless ($reply eq 'ok') {
11262:             return 'error: '.$reply;
11263:         }   
11264:         $uhome=&homeserver($uname,$udom,'true');
11265:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
11266: 	    return 'error: unable verify users home machine.';
11267:         }
11268:     }   # End of creation of new user
11269: # ---------------------------------------------------------------------- Add ID
11270:     if ($uid) {
11271:        $uid=~tr/A-Z/a-z/;
11272:        my %uidhash=&idrget($udom,$uname);
11273:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
11274:          && (!$forceid)) {
11275: 	  unless ($uid eq $uidhash{$uname}) {
11276: 	      return 'error: user id "'.$uid.'" does not match '.
11277:                   'current user id "'.$uidhash{$uname}.'".';
11278:           }
11279:        } else {
11280: 	  &idput($udom,{$uname => $uid},$uhome,'ids');
11281:        }
11282:     }
11283: # -------------------------------------------------------------- Add names, etc
11284:     my @tmp=&get('environment',
11285: 		   ['firstname','middlename','lastname','generation','id',
11286:                     'permanentemail','inststatus'],
11287: 		   $udom,$uname);
11288:     my (%names,%oldnames);
11289:     if ($tmp[0] =~ m/^error:.*/) { 
11290:         %names=(); 
11291:     } else {
11292:         %names = @tmp;
11293:         %oldnames = %names;
11294:     }
11295: #
11296: # If name, email and/or uid are blank (e.g., because an uploaded file
11297: # of users did not contain them), do not overwrite existing values
11298: # unless field is in $candelete array ref.  
11299: #
11300: 
11301:     my @fields = ('firstname','middlename','lastname','generation',
11302:                   'permanentemail','id');
11303:     my %newvalues;
11304:     if (ref($candelete) eq 'ARRAY') {
11305:         foreach my $field (@fields) {
11306:             if (grep(/^\Q$field\E$/,@{$candelete})) {
11307:                 if ($field eq 'firstname') {
11308:                     $names{$field} = $first;
11309:                 } elsif ($field eq 'middlename') {
11310:                     $names{$field} = $middle;
11311:                 } elsif ($field eq 'lastname') {
11312:                     $names{$field} = $last;
11313:                 } elsif ($field eq 'generation') { 
11314:                     $names{$field} = $gene;
11315:                 } elsif ($field eq 'permanentemail') {
11316:                     $names{$field} = $email;
11317:                 } elsif ($field eq 'id') {
11318:                     $names{$field}  = $uid;
11319:                 }
11320:             }
11321:         }
11322:     }
11323:     if ($first)  { $names{'firstname'}  = $first; }
11324:     if (defined($middle)) { $names{'middlename'} = $middle; }
11325:     if ($last)   { $names{'lastname'}   = $last; }
11326:     if (defined($gene))   { $names{'generation'} = $gene; }
11327:     if ($email) {
11328:        $email=~s/[^\w\@\.\-\,]//gs;
11329:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
11330:     }
11331:     if ($uid) { $names{'id'}  = $uid; }
11332:     if (defined($inststatus)) {
11333:         $names{'inststatus'} = '';
11334:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
11335:         if (ref($usertypes) eq 'HASH') {
11336:             my @okstatuses; 
11337:             foreach my $item (split(/:/,$inststatus)) {
11338:                 if (defined($usertypes->{$item})) {
11339:                     push(@okstatuses,$item);  
11340:                 }
11341:             }
11342:             if (@okstatuses) {
11343:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
11344:             }
11345:         }
11346:     }
11347:     my $logmsg = $udom.', '.$uname.', '.$uid.', '.
11348:                  $umode.', '.$first.', '.$middle.', '.
11349:                  $last.', '.$gene.', '.$email.', '.$inststatus;
11350:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
11351:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
11352:     } else {
11353:         $logmsg .= ' during self creation';
11354:     }
11355:     my $changed;
11356:     if ($newuser) {
11357:         $changed = 1;
11358:     } else {
11359:         foreach my $field (@fields) {
11360:             if ($names{$field} ne $oldnames{$field}) {
11361:                 $changed = 1;
11362:                 last;
11363:             }
11364:         }
11365:     }
11366:     unless ($changed) {
11367:         $logmsg = 'No changes in user information needed for: '.$logmsg;
11368:         &logthis($logmsg);
11369:         return 'ok';
11370:     }
11371:     my $reply = &put('environment', \%names, $udom,$uname);
11372:     if ($reply ne 'ok') { 
11373:         return 'error: '.$reply;
11374:     }
11375:     if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
11376:         &devalidate_cache_new('emailscache',$uname.':'.$udom);
11377:     }
11378:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
11379:     &devalidate_cache_new('namescache',$uname.':'.$udom);
11380:     $logmsg = 'Success modifying user '.$logmsg;
11381:     &logthis($logmsg);
11382:     return 'ok';
11383: }
11384: 
11385: # -------------------------------------------------------------- Modify student
11386: 
11387: sub modifystudent {
11388:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
11389:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
11390:         $selfenroll,$context,$inststatus,$credits,$instsec)=@_;
11391:     if (!$cid) {
11392: 	unless ($cid=$env{'request.course.id'}) {
11393: 	    return 'not_in_class';
11394: 	}
11395:     }
11396: # --------------------------------------------------------------- Make the user
11397:     my $reply=&modifyuser
11398: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
11399:          $desiredhome,$email,$inststatus);
11400:     unless ($reply eq 'ok') { return $reply; }
11401:     # This will cause &modify_student_enrollment to get the uid from the
11402:     # student's environment
11403:     $uid = undef if (!$forceid);
11404:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
11405:                                         $gene,$usec,$end,$start,$type,$locktype,
11406:                                         $cid,$selfenroll,$context,$credits,$instsec);
11407:     return $reply;
11408: }
11409: 
11410: sub modify_student_enrollment {
11411:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,
11412:         $locktype,$cid,$selfenroll,$context,$credits,$instsec,$othdomby,$requester) = @_;
11413:     my ($cdom,$cnum,$chome);
11414:     if (!$cid) {
11415: 	unless ($cid=$env{'request.course.id'}) {
11416: 	    return 'not_in_class';
11417: 	}
11418: 	$cdom=$env{'course.'.$cid.'.domain'};
11419: 	$cnum=$env{'course.'.$cid.'.num'};
11420:     } else {
11421: 	($cdom,$cnum)=split(/_/,$cid);
11422:     }
11423:     $chome=$env{'course.'.$cid.'.home'};
11424:     if (!$chome) {
11425: 	$chome=&homeserver($cnum,$cdom);
11426:     }
11427:     if (!$chome) { return 'unknown_course'; }
11428:     # Make sure the user exists
11429:     my $uhome=&homeserver($uname,$udom);
11430:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
11431: 	return 'error: no such user';
11432:     }
11433:     # Get student data if we were not given enough information
11434:     if (!defined($first)  || $first  eq '' || 
11435:         !defined($last)   || $last   eq '' || 
11436:         !defined($uid)    || $uid    eq '' || 
11437:         !defined($middle) || $middle eq '' || 
11438:         !defined($gene)   || $gene   eq '') {
11439:         # They did not supply us with enough data to enroll the student, so
11440:         # we need to pick up more information.
11441:         my %tmp = &get('environment',
11442:                        ['firstname','middlename','lastname', 'generation','id']
11443:                        ,$udom,$uname);
11444: 
11445:         #foreach my $key (keys(%tmp)) {
11446:         #    &logthis("key $key = ".$tmp{$key});
11447:         #}
11448:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
11449:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
11450:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
11451:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
11452:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
11453:     }
11454:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
11455:     my $user = "$uname:$udom";
11456:     my %old_entry = &get('classlist',[$user],$cdom,$cnum);
11457:     my $reply=cput('classlist',
11458: 		   {$user => 
11459: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits,$instsec) },
11460: 		   $cdom,$cnum);
11461:     if (($reply eq 'ok') || ($reply eq 'delayed')) {
11462:         &devalidate_getsection_cache($udom,$uname,$cid);
11463:     } else { 
11464: 	return 'error: '.$reply;
11465:     }
11466:     # Add student role to user
11467:     my $uurl='/'.$cid;
11468:     $uurl=~s/\_/\//g;
11469:     if ($usec) {
11470: 	$uurl.='/'.$usec;
11471:     }
11472:     my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
11473:                              $selfenroll,$context,$othdomby,$requester);
11474:     if ($result ne 'ok') {
11475:         if ($old_entry{$user} ne '') {
11476:             $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
11477:         } else {
11478:             $reply = &del('classlist',[$user],$cdom,$cnum);
11479:         }
11480:     }
11481:     return $result; 
11482: }
11483: 
11484: sub format_name {
11485:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
11486:     my $name;
11487:     if ($first ne 'lastname') {
11488: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
11489:     } else {
11490: 	if ($lastname=~/\S/) {
11491: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
11492: 	    $name=~s/\s+,/,/;
11493: 	} else {
11494: 	    $name.= $firstname.' '.$middlename.' '.$generation;
11495: 	}
11496:     }
11497:     $name=~s/^\s+//;
11498:     $name=~s/\s+$//;
11499:     $name=~s/\s+/ /g;
11500:     return $name;
11501: }
11502: 
11503: # ------------------------------------------------- Write to course preferences
11504: 
11505: sub writecoursepref {
11506:     my ($courseid,%prefs)=@_;
11507:     $courseid=~s/^\///;
11508:     $courseid=~s/\_/\//g;
11509:     my ($cdomain,$cnum)=split(/\//,$courseid);
11510:     my $chome=homeserver($cnum,$cdomain);
11511:     if (($chome eq '') || ($chome eq 'no_host')) { 
11512: 	return 'error: no such course';
11513:     }
11514:     my $cstring='';
11515:     foreach my $pref (keys(%prefs)) {
11516: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
11517:     }
11518:     $cstring=~s/\&$//;
11519:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
11520: }
11521: 
11522: # ---------------------------------------------------------- Make/modify course
11523: 
11524: sub createcourse {
11525:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
11526:         $course_owner,$crstype,$cnum,$context,$category,$callercontext)=@_;
11527:     $url=&declutter($url);
11528:     my $cid='';
11529:     if ($context eq 'requestcourses') {
11530:         my $can_create = 0;
11531:         my ($ownername,$ownerdom) = split(':',$course_owner);
11532:         if ($udom eq $ownerdom) {
11533:             my $reload;
11534:             if (($callercontext eq 'auto') &&
11535:                ($ownerdom eq $env{'user.domain'}) && ($ownername eq $env{'user.name'})) {
11536:                 $reload = 'reload';
11537:             }
11538:             if (&usertools_access($ownername,$ownerdom,$category,$reload,
11539:                                   $context)) {
11540:                 $can_create = 1;
11541:             }
11542:         } else {
11543:             my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
11544:                                            $category);
11545:             if ($userenv{'reqcrsotherdom.'.$category} ne '') {
11546:                 my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
11547:                 if (@curr > 0) {
11548:                     my @options = qw(approval validate autolimit);
11549:                     my $optregex = join('|',@options);
11550:                     if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
11551:                         $can_create = 1;
11552:                     }
11553:                 }
11554:             }
11555:         }
11556:         if ($can_create) {
11557:             unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
11558:                 unless (&allowed('ccc',$udom)) {
11559:                     return 'refused'; 
11560:                 }
11561:             }
11562:         } else {
11563:             return 'refused';
11564:         }
11565:     } elsif (!&allowed('ccc',$udom)) {
11566:         return 'refused';
11567:     }
11568: # --------------------------------------------------------------- Get Unique ID
11569:     my $uname;
11570:     if ($cnum =~ /^$match_courseid$/) {
11571:         my $chome=&homeserver($cnum,$udom,'true');
11572:         if (($chome eq '') || ($chome eq 'no_host')) {
11573:             $uname = $cnum;
11574:         } else {
11575:             $uname = &generate_coursenum($udom,$crstype);
11576:         }
11577:     } else {
11578:         $uname = &generate_coursenum($udom,$crstype);
11579:     }
11580:     return $uname if ($uname =~ /^error/);
11581: # -------------------------------------------------- Check supplied server name
11582:     if (!defined($course_server)) {
11583:         if (defined(&domain($udom,'primary'))) {
11584:             $course_server = &domain($udom,'primary');
11585:         } else {
11586:             $course_server = $env{'user.home'}; 
11587:         }
11588:     }
11589:     my %host_servers =
11590:         &get_servers($udom,'library');
11591:     unless ($host_servers{$course_server}) {
11592:         return 'error: invalid home server for course: '.$course_server;
11593:     }
11594: # ------------------------------------------------------------- Make the course
11595:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
11596:                       $course_server);
11597:     unless ($reply eq 'ok') { return 'error: '.$reply; }
11598:     my $uhome=&homeserver($uname,$udom,'true');
11599:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
11600: 	return 'error: no such course';
11601:     }
11602: # ----------------------------------------------------------------- Course made
11603: # log existence
11604:     my $now = time;
11605:     my $newcourse = {
11606:                     $udom.'_'.$uname => {
11607:                                      description => $description,
11608:                                      inst_code   => $inst_code,
11609:                                      owner       => $course_owner,
11610:                                      type        => $crstype,
11611:                                      creator     => $env{'user.name'}.':'.
11612:                                                     $env{'user.domain'},
11613:                                      created     => $now,
11614:                                      context     => $context,
11615:                                                 },
11616:                     };
11617:     &courseidput($udom,$newcourse,$uhome,'notime');
11618: # set toplevel url
11619:     my $topurl=$url;
11620:     unless ($nonstandard) {
11621: # ------------------------------------------ For standard courses, make top url
11622:         my $mapurl=&clutter($url);
11623:         if ($mapurl eq '/res/') { $mapurl=''; }
11624:         $env{'form.initmap'}=(<<ENDINITMAP);
11625: <map>
11626: <resource id="1" type="start"></resource>
11627: <resource id="2" src="$mapurl"></resource>
11628: <resource id="3" type="finish"></resource>
11629: <link index="1" from="1" to="2"></link>
11630: <link index="2" from="2" to="3"></link>
11631: </map>
11632: ENDINITMAP
11633:         $topurl=&declutter(
11634:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
11635:                           );
11636:     }
11637: # ----------------------------------------------------------- Write preferences
11638:     &writecoursepref($udom.'_'.$uname,
11639:                      ('description'              => $description,
11640:                       'url'                      => $topurl,
11641:                       'internal.creator'         => $env{'user.name'}.':'.
11642:                                                     $env{'user.domain'},
11643:                       'internal.created'         => $now,
11644:                       'internal.creationcontext' => $context)
11645:                     );
11646:     return '/'.$udom.'/'.$uname;
11647: }
11648: 
11649: # ------------------------------------------------------------------- Create ID
11650: sub generate_coursenum {
11651:     my ($udom,$crstype) = @_;
11652:     my $domdesc = &domain($udom);
11653:     return 'error: invalid domain' if ($domdesc eq '');
11654:     my $first;
11655:     if ($crstype eq 'Community') {
11656:         $first = '0';
11657:     } else {
11658:         $first = int(1+rand(9)); 
11659:     } 
11660:     my $uname=$first.
11661:         ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
11662:         substr($$.time,0,5).unpack("H8",pack("I32",time)).
11663:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
11664: # ----------------------------------------------- Make sure that does not exist
11665:     my $uhome=&homeserver($uname,$udom,'true');
11666:     unless (($uhome eq '') || ($uhome eq 'no_host')) {
11667:         if ($crstype eq 'Community') {
11668:             $first = '0';
11669:         } else {
11670:             $first = int(1+rand(9));
11671:         }
11672:         $uname=$first.
11673:                ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
11674:                substr($$.time,0,5).unpack("H8",pack("I32",time)).
11675:                unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
11676:         $uhome=&homeserver($uname,$udom,'true');
11677:         unless (($uhome eq '') || ($uhome eq 'no_host')) {
11678:             return 'error: unable to generate unique course-ID';
11679:         }
11680:     }
11681:     return $uname;
11682: }
11683: 
11684: sub is_course {
11685:     my ($cdom, $cnum) = scalar(@_) == 1 ? 
11686:          ($_[0] =~ /^($match_domain)_($match_courseid)$/)  :  @_;
11687: 
11688:     return unless (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/));
11689:     my $uhome=&homeserver($cnum,$cdom);
11690:     my $iscourse;
11691:     if (grep { $_ eq $uhome } current_machine_ids()) {
11692:         $iscourse = &LONCAPA::Lond::is_course($cdom,$cnum);
11693:     } else {
11694:         my $hashid = $cdom.':'.$cnum;
11695:         ($iscourse,my $cached) = &is_cached_new('iscourse',$hashid);
11696:         unless (defined($cached)) {
11697:             my %courses = &courseiddump($cdom, '.', 1, '.', '.',
11698:                                         $cnum,undef,undef,'.');
11699:             $iscourse = 0;
11700:             if (exists($courses{$cdom.'_'.$cnum})) {
11701:                 $iscourse = 1;
11702:             }
11703:             &do_cache_new('iscourse',$hashid,$iscourse,3600);
11704:         }
11705:     }
11706:     return unless ($iscourse);
11707:     return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
11708: }
11709: 
11710: sub store_userdata {
11711:     my ($storehash,$datakey,$namespace,$udom,$uname,$ip) = @_;
11712:     my $result;
11713:     if ($datakey ne '') {
11714:         if (ref($storehash) eq 'HASH') {
11715:             if ($udom eq '' || $uname eq '') {
11716:                 $udom = $env{'user.domain'};
11717:                 $uname = $env{'user.name'};
11718:             }
11719:             my $uhome=&homeserver($uname,$udom);
11720:             if (($uhome eq '') || ($uhome eq 'no_host')) {
11721:                 $result = 'error: no_host';
11722:             } else {
11723:                 if ($ip ne '') {
11724:                     $storehash->{'ip'} = $ip;
11725:                 } else {
11726:                     $storehash->{'ip'} = &get_requestor_ip();
11727:                 }
11728:                 $storehash->{'host'} = $perlvar{'lonHostID'};
11729: 
11730:                 my $namevalue='';
11731:                 foreach my $key (keys(%{$storehash})) {
11732:                     $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
11733:                 }
11734:                 $namevalue=~s/\&$//;
11735:                 unless ($namespace eq 'courserequests') {
11736:                     $datakey = &escape($datakey);
11737:                 }
11738:                 $result =  &reply("store:$udom:$uname:$namespace:$datakey:".
11739:                                   $namevalue,$uhome);
11740:             }
11741:         } else {
11742:             $result = 'error: data to store was not a hash reference'; 
11743:         }
11744:     } else {
11745:         $result= 'error: invalid requestkey'; 
11746:     }
11747:     return $result;
11748: }
11749: 
11750: # ---------------------------------------------------------- Assign Custom Role
11751: 
11752: sub assigncustomrole {
11753:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,
11754:         $selfenroll,$context,$othdomby,$requester)=@_;
11755:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
11756:                        $end,$start,$deleteflag,$selfenroll,$context,$othdomby,
11757:                        $requester);
11758: }
11759: 
11760: # ----------------------------------------------------------------- Revoke Role
11761: 
11762: sub revokerole {
11763:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
11764:     my $now=time;
11765:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
11766: }
11767: 
11768: # ---------------------------------------------------------- Revoke Custom Role
11769: 
11770: sub revokecustomrole {
11771:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
11772:     my $now=time;
11773:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
11774:            $deleteflag,$selfenroll,$context);
11775: }
11776: 
11777: # ------------------------------------------------------------ Disk usage
11778: sub diskusage {
11779:     my ($udom,$uname,$directorypath,$getpropath)=@_;
11780:     $directorypath =~ s/\/$//;
11781:     my $listing=&reply('du2:'.&escape($directorypath).':'
11782:                        .&escape($getpropath).':'.&escape($uname).':'
11783:                        .&escape($udom),homeserver($uname,$udom));
11784:     if ($listing eq 'unknown_cmd') {
11785:         if ($getpropath) {
11786:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
11787:         }
11788:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
11789:     }
11790:     return $listing;
11791: }
11792: 
11793: sub is_locked {
11794:     my ($file_name, $domain, $user, $which) = @_;
11795:     my @check;
11796:     my $is_locked;
11797:     push (@check,$file_name);
11798:     my %locked = &get('file_permissions',\@check,
11799: 		      $env{'user.domain'},$env{'user.name'});
11800:     my ($tmp)=keys(%locked);
11801:     if ($tmp=~/^error:/) { undef(%locked); }
11802:     
11803:     if (ref($locked{$file_name}) eq 'ARRAY') {
11804:         $is_locked = 'false';
11805:         foreach my $entry (@{$locked{$file_name}}) {
11806:            if (ref($entry) eq 'ARRAY') {
11807:                $is_locked = 'true';
11808:                if (ref($which) eq 'ARRAY') {
11809:                    push(@{$which},$entry);
11810:                } else {
11811:                    last;
11812:                }
11813:            }
11814:        }
11815:     } else {
11816:         $is_locked = 'false';
11817:     }
11818:     return $is_locked;
11819: }
11820: 
11821: sub declutter_portfile {
11822:     my ($file) = @_;
11823:     $file =~ s{^(/portfolio/|portfolio/)}{/};
11824:     return $file;
11825: }
11826: 
11827: # ------------------------------------------------------------- Mark as Read Only
11828: 
11829: sub mark_as_readonly {
11830:     my ($domain,$user,$files,$what) = @_;
11831:     my %current_permissions = &dump('file_permissions',$domain,$user);
11832:     my ($tmp)=keys(%current_permissions);
11833:     if ($tmp=~/^error:/) { undef(%current_permissions); }
11834:     foreach my $file (@{$files}) {
11835: 	$file = &declutter_portfile($file);
11836:         push(@{$current_permissions{$file}},$what);
11837:     }
11838:     &put('file_permissions',\%current_permissions,$domain,$user);
11839:     return;
11840: }
11841: 
11842: # ------------------------------------------------------------Save Selected Files
11843: 
11844: sub save_selected_files {
11845:     my ($user, $path, @files) = @_;
11846:     my $filename = $user."savedfiles";
11847:     my @other_files = &files_not_in_path($user, $path);
11848:     open (OUT,'>',LONCAPA::tempdir().$filename);
11849:     foreach my $file (@files) {
11850:         print (OUT $env{'form.currentpath'}.$file."\n");
11851:     }
11852:     foreach my $file (@other_files) {
11853:         print (OUT $file."\n");
11854:     }
11855:     close (OUT);
11856:     return 'ok';
11857: }
11858: 
11859: sub clear_selected_files {
11860:     my ($user) = @_;
11861:     my $filename = $user."savedfiles";
11862:     open (OUT,'>',LONCAPA::tempdir().$filename);
11863:     print (OUT undef);
11864:     close (OUT);
11865:     return ("ok");    
11866: }
11867: 
11868: sub files_in_path {
11869:     my ($user, $path) = @_;
11870:     my $filename = $user."savedfiles";
11871:     my %return_files;
11872:     open (IN,'<',LONCAPA::tempdir().$filename);
11873:     while (my $line_in = <IN>) {
11874:         chomp ($line_in);
11875:         my @paths_and_file = split (m!/!, $line_in);
11876:         my $file_part = pop (@paths_and_file);
11877:         my $path_part = join ('/', @paths_and_file);
11878:         $path_part.='/';
11879:         my $path_and_file = $path_part.$file_part;
11880:         if ($path_part eq $path) {
11881:             $return_files{$file_part}= 'selected';
11882:         }
11883:     }
11884:     close (IN);
11885:     return (\%return_files);
11886: }
11887: 
11888: # called in portfolio select mode, to show files selected NOT in current directory
11889: sub files_not_in_path {
11890:     my ($user, $path) = @_;
11891:     my $filename = $user."savedfiles";
11892:     my @return_files;
11893:     my $path_part;
11894:     open(IN, '<',LONCAPA::tempdir().$filename);
11895:     while (my $line = <IN>) {
11896:         #ok, I know it's clunky, but I want it to work
11897:         my @paths_and_file = split(m|/|, $line);
11898:         my $file_part = pop(@paths_and_file);
11899:         chomp($file_part);
11900:         my $path_part = join('/', @paths_and_file);
11901:         $path_part .= '/';
11902:         my $path_and_file = $path_part.$file_part;
11903:         if ($path_part ne $path) {
11904:             push(@return_files, ($path_and_file));
11905:         }
11906:     }
11907:     close(OUT);
11908:     return (@return_files);
11909: }
11910: 
11911: #------------------------------Submitted/Handedback Portfolio Files Versioning
11912:  
11913: sub portfiles_versioning {
11914:     my ($symb,$domain,$stu_name,$portfiles,$versioned_portfiles) = @_;
11915:     my $portfolio_root = '/userfiles/portfolio';
11916:     return unless ((ref($portfiles) eq 'ARRAY') && (ref($versioned_portfiles) eq 'ARRAY'));
11917:     foreach my $file (@{$portfiles}) {
11918:         &unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
11919:         my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
11920:         my ($answer_name,$answer_ver,$answer_ext) = &file_name_version_ext($answer_file);
11921:         my $getpropath = 1;
11922:         my ($dir_list,$listerror) = &dirlist($portfolio_root.$directory,$domain,
11923:                                              $stu_name,$getpropath);
11924:         my $version = &get_next_version($answer_name,$answer_ext,$dir_list);
11925:         my $new_answer = 
11926:             &version_selected_portfile($domain,$stu_name,$directory,$answer_file,$version);
11927:         if ($new_answer ne 'problem getting file') {
11928:             push(@{$versioned_portfiles}, $directory.$new_answer);
11929:             &mark_as_readonly($domain,$stu_name,[$directory.$new_answer],
11930:                               [$symb,$env{'request.course.id'},'graded']);
11931:         }
11932:     }
11933: }
11934: 
11935: sub get_next_version {
11936:     my ($answer_name, $answer_ext, $dir_list) = @_;
11937:     my $version;
11938:     if (ref($dir_list) eq 'ARRAY') {
11939:         foreach my $row (@{$dir_list}) {
11940:             my ($file) = split(/\&/,$row,2);
11941:             my ($file_name,$file_version,$file_ext) =
11942:                 &file_name_version_ext($file);
11943:             if (($file_name eq $answer_name) &&
11944:                 ($file_ext eq $answer_ext)) {
11945:                      # gets here if filename and extension match,
11946:                      # regardless of version
11947:                 if ($file_version ne '') {
11948:                     # a versioned file is found  so save it for later
11949:                     if ($file_version > $version) {
11950:                         $version = $file_version;
11951:                     }
11952:                 }
11953:             }
11954:         }
11955:     }
11956:     $version ++;
11957:     return($version);
11958: }
11959: 
11960: sub version_selected_portfile {
11961:     my ($domain,$stu_name,$directory,$file_name,$version) = @_;
11962:     my ($answer_name,$answer_ver,$answer_ext) =
11963:         &file_name_version_ext($file_name);
11964:     my $new_answer;
11965:     $env{'form.copy'} =
11966:         &getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
11967:     if($env{'form.copy'} eq '-1') {
11968:         $new_answer = 'problem getting file';
11969:     } else {
11970:         $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
11971:         my $copy_result = 
11972:             &finishuserfileupload($stu_name,$domain,'copy',
11973:                                   '/portfolio'.$directory.$new_answer);
11974:     }
11975:     undef($env{'form.copy'});
11976:     return ($new_answer);
11977: }
11978: 
11979: sub file_name_version_ext {
11980:     my ($file)=@_;
11981:     my @file_parts = split(/\./, $file);
11982:     my ($name,$version,$ext);
11983:     if (@file_parts > 1) {
11984:         $ext=pop(@file_parts);
11985:         if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
11986:             $version=pop(@file_parts);
11987:         }
11988:         $name=join('.',@file_parts);
11989:     } else {
11990:         $name=join('.',@file_parts);
11991:     }
11992:     return($name,$version,$ext);
11993: }
11994: 
11995: #----------------------------------------------Get portfolio file permissions
11996: 
11997: sub get_portfile_permissions {
11998:     my ($domain,$user) = @_;
11999:     my %current_permissions = &dump('file_permissions',$domain,$user);
12000:     my ($tmp)=keys(%current_permissions);
12001:     if ($tmp=~/^error:/) { undef(%current_permissions); }
12002:     return \%current_permissions;
12003: }
12004: 
12005: #---------------------------------------------Get portfolio file access controls
12006: 
12007: sub get_access_controls {
12008:     my ($current_permissions,$group,$file) = @_;
12009:     my %access;
12010:     my $real_file = $file;
12011:     $file =~ s/\.meta$//;
12012:     if (defined($file)) {
12013:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
12014:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
12015:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
12016:             }
12017:         }
12018:     } else {
12019:         foreach my $key (keys(%{$current_permissions})) {
12020:             if ($key =~ /\0accesscontrol$/) {
12021:                 if (defined($group)) {
12022:                     if ($key !~ m-^\Q$group\E/-) {
12023:                         next;
12024:                     }
12025:                 }
12026:                 my ($fullpath) = split(/\0/,$key);
12027:                 if (ref($$current_permissions{$key}) eq 'HASH') {
12028:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
12029:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
12030:                     }
12031:                 }
12032:             }
12033:         }
12034:     }
12035:     return %access;
12036: }
12037: 
12038: sub modify_access_controls {
12039:     my ($file_name,$changes,$domain,$user)=@_;
12040:     my ($outcome,$deloutcome);
12041:     my %store_permissions;
12042:     my %new_values;
12043:     my %new_control;
12044:     my %translation;
12045:     my @deletions = ();
12046:     my $now = time;
12047:     if (exists($$changes{'activate'})) {
12048:         if (ref($$changes{'activate'}) eq 'HASH') {
12049:             my @newitems = sort(keys(%{$$changes{'activate'}}));
12050:             my $numnew = scalar(@newitems);
12051:             for (my $i=0; $i<$numnew; $i++) {
12052:                 my $newkey = $newitems[$i];
12053:                 my $newid = &Apache::loncommon::get_cgi_id();
12054:                 if ($newkey =~ /^\d+:/) { 
12055:                     $newkey =~ s/^(\d+)/$newid/;
12056:                     $translation{$1} = $newid;
12057:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
12058:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
12059:                     $translation{$1} = $newid;
12060:                 }
12061:                 $new_values{$file_name."\0".$newkey} = 
12062:                                           $$changes{'activate'}{$newitems[$i]};
12063:                 $new_control{$newkey} = $now;
12064:             }
12065:         }
12066:     }
12067:     my %todelete;
12068:     my %changed_items;
12069:     foreach my $action ('delete','update') {
12070:         if (exists($$changes{$action})) {
12071:             if (ref($$changes{$action}) eq 'HASH') {
12072:                 foreach my $key (keys(%{$$changes{$action}})) {
12073:                     my ($itemnum) = ($key =~ /^([^:]+):/);
12074:                     if ($action eq 'delete') { 
12075:                         $todelete{$itemnum} = 1;
12076:                     } else {
12077:                         $changed_items{$itemnum} = $key;
12078:                     }
12079:                 }
12080:             }
12081:         }
12082:     }
12083:     # get lock on access controls for file.
12084:     my $lockhash = {
12085:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
12086:                                                        ':'.$env{'user.domain'},
12087:                    }; 
12088:     my $tries = 0;
12089:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
12090:    
12091:     while (($gotlock ne 'ok') && $tries < 10) {
12092:         $tries ++;
12093:         sleep(0.1);
12094:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
12095:     }
12096:     if ($gotlock eq 'ok') {
12097:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
12098:         my ($tmp)=keys(%curr_permissions);
12099:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
12100:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
12101:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
12102:             if (ref($curr_controls) eq 'HASH') {
12103:                 foreach my $control_item (keys(%{$curr_controls})) {
12104:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
12105:                     if (defined($todelete{$itemnum})) {
12106:                         push(@deletions,$file_name."\0".$control_item);
12107:                     } else {
12108:                         if (defined($changed_items{$itemnum})) {
12109:                             $new_control{$changed_items{$itemnum}} = $now;
12110:                             push(@deletions,$file_name."\0".$control_item);
12111:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
12112:                         } else {
12113:                             $new_control{$control_item} = $$curr_controls{$control_item};
12114:                         }
12115:                     }
12116:                 }
12117:             }
12118:         }
12119:         my ($group);
12120:         if (&is_course($domain,$user)) {
12121:             ($group,my $file) = split(/\//,$file_name,2);
12122:         }
12123:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
12124:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
12125:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
12126:         #  remove lock
12127:         my @del_lock = ($file_name."\0".'locked_access_records');
12128:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
12129:         my $sqlresult =
12130:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
12131:                                     $group);
12132:     } else {
12133:         $outcome = "error: could not obtain lockfile\n";  
12134:     }
12135:     return ($outcome,$deloutcome,\%new_values,\%translation);
12136: }
12137: 
12138: sub make_public_indefinitely {
12139:     my (@requrl) = @_;
12140:     return &automated_portfile_access('public',\@requrl);
12141: }
12142: 
12143: sub automated_portfile_access {
12144:     my ($accesstype,$addsref,$delsref,$info) = @_;
12145:     unless (($accesstype eq 'public') || ($accesstype eq 'ip')) {
12146:         return 'invalid';
12147:     }
12148:     my %urls;
12149:     if (ref($addsref) eq 'ARRAY') {
12150:         foreach my $requrl (@{$addsref}) {
12151:             if (&is_portfolio_url($requrl)) {
12152:                 unless (exists($urls{$requrl})) {
12153:                     $urls{$requrl} = 'add';
12154:                 }
12155:             }
12156:         }
12157:     }
12158:     if (ref($delsref) eq 'ARRAY') {
12159:         foreach my $requrl (@{$delsref}) { 
12160:             if (&is_portfolio_url($requrl)) {
12161:                 unless (exists($urls{$requrl})) {
12162:                     $urls{$requrl} = 'delete'; 
12163:                 }
12164:             }
12165:         }
12166:     }
12167:     unless (keys(%urls)) {
12168:         return 'invalid';
12169:     }
12170:     my $ip;
12171:     if ($accesstype eq 'ip') {
12172:         if (ref($info) eq 'HASH') {
12173:             if ($info->{'ip'} ne '') {
12174:                 $ip = $info->{'ip'};
12175:             }
12176:         }
12177:         if ($ip eq '') {
12178:             return 'invalid';
12179:         }
12180:     }
12181:     my $errors;
12182:     my $now = time;
12183:     my %current_perms;
12184:     foreach my $requrl (sort(keys(%urls))) {
12185:         my $action;
12186:         if ($urls{$requrl} eq 'add') {
12187:             $action = 'activate';
12188:         } else {
12189:             $action = 'none';
12190:         }
12191:         my $aclnum = 0;
12192:         my (undef,$udom,$unum,$file_name,$group) =
12193:             &parse_portfolio_url($requrl);
12194:         unless (exists($current_perms{$unum.':'.$udom})) {
12195:             $current_perms{$unum.':'.$udom} = &get_portfile_permissions($udom,$unum);
12196:         }
12197:         my %access_controls = &get_access_controls($current_perms{$unum.':'.$udom},
12198:                                                    $group,$file_name);
12199:         foreach my $key (keys(%{$access_controls{$file_name}})) {
12200:             my ($num,$scope,$end,$start) = 
12201:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
12202:             if ($scope eq $accesstype) {
12203:                 if (($start <= $now) && ($end == 0)) {
12204:                     if ($accesstype eq 'ip') {
12205:                         if (ref($access_controls{$file_name}{$key}) eq 'HASH') {
12206:                             if (ref($access_controls{$file_name}{$key}{'ip'}) eq 'ARRAY') {
12207:                                 if (grep(/^\Q$ip\E$/,@{$access_controls{$file_name}{$key}{'ip'}})) {
12208:                                     if ($urls{$requrl} eq 'add') {
12209:                                         $action = 'none';
12210:                                         last;
12211:                                     } else {
12212:                                         $action = 'delete';
12213:                                         $aclnum = $num;
12214:                                         last;
12215:                                     }
12216:                                 }
12217:                             }
12218:                         }
12219:                     } elsif ($accesstype eq 'public') {
12220:                         if ($urls{$requrl} eq 'add') {
12221:                             $action = 'none';
12222:                             last;
12223:                         } else {
12224:                             $action = 'delete';
12225:                             $aclnum = $num;
12226:                             last;
12227:                         }
12228:                     }
12229:                 } elsif ($accesstype eq 'public') {
12230:                     $action = 'update';
12231:                     $aclnum = $num;
12232:                     last;
12233:                 }
12234:             }
12235:         }
12236:         if ($action eq 'none') {
12237:             next;
12238:         } else {
12239:             my %changes;
12240:             my $newend = 0;
12241:             my $newstart = $now;
12242:             my $newkey = $aclnum.':'.$accesstype.'_'.$newend.'_'.$newstart;
12243:             $changes{$action}{$newkey} = {
12244:                 type => $accesstype,
12245:                 time => {
12246:                     start => $newstart,
12247:                     end   => $newend,
12248:                 },
12249:             };
12250:             if ($accesstype eq 'ip') {
12251:                 $changes{$action}{$newkey}{'ip'} = [$ip];
12252:             }
12253:             my ($outcome,$deloutcome,$new_values,$translation) =
12254:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
12255:             unless ($outcome eq 'ok') {
12256:                 $errors .= $outcome.' ';
12257:             }
12258:         }
12259:     }
12260:     if ($errors) {
12261:         $errors =~ s/\s$//;
12262:         return $errors;
12263:     } else {
12264:         return 'ok';
12265:     }
12266: }
12267: 
12268: #------------------------------------------------------Get Marked as Read Only
12269: 
12270: sub get_marked_as_readonly {
12271:     my ($domain,$user,$what,$group) = @_;
12272:     my $current_permissions = &get_portfile_permissions($domain,$user);
12273:     my @readonly_files;
12274:     my $cmp1=$what;
12275:     if (ref($what)) { $cmp1=join('',@{$what}) };
12276:     while (my ($file_name,$value) = each(%{$current_permissions})) {
12277:         if (defined($group)) {
12278:             if ($file_name !~ m-^\Q$group\E/-) {
12279:                 next;
12280:             }
12281:         }
12282:         if (ref($value) eq "ARRAY"){
12283:             foreach my $stored_what (@{$value}) {
12284:                 my $cmp2=$stored_what;
12285:                 if (ref($stored_what) eq 'ARRAY') {
12286:                     $cmp2=join('',@{$stored_what});
12287:                 }
12288:                 if ($cmp1 eq $cmp2) {
12289:                     push(@readonly_files, $file_name);
12290:                     last;
12291:                 } elsif (!defined($what)) {
12292:                     push(@readonly_files, $file_name);
12293:                     last;
12294:                 }
12295:             }
12296:         }
12297:     }
12298:     return @readonly_files;
12299: }
12300: #-----------------------------------------------------------Get Marked as Read Only Hash
12301: 
12302: sub get_marked_as_readonly_hash {
12303:     my ($current_permissions,$group,$what) = @_;
12304:     my %readonly_files;
12305:     while (my ($file_name,$value) = each(%{$current_permissions})) {
12306:         if (defined($group)) {
12307:             if ($file_name !~ m-^\Q$group\E/-) {
12308:                 next;
12309:             }
12310:         }
12311:         if (ref($value) eq "ARRAY"){
12312:             foreach my $stored_what (@{$value}) {
12313:                 if (ref($stored_what) eq 'ARRAY') {
12314:                     foreach my $lock_descriptor(@{$stored_what}) {
12315:                         if ($lock_descriptor eq 'graded') {
12316:                             $readonly_files{$file_name} = 'graded';
12317:                         } elsif ($lock_descriptor eq 'handback') {
12318:                             $readonly_files{$file_name} = 'handback';
12319:                         } else {
12320:                             if (!exists($readonly_files{$file_name})) {
12321:                                 $readonly_files{$file_name} = 'locked';
12322:                             }
12323:                         }
12324:                     }
12325:                 } 
12326:             }
12327:         } 
12328:     }
12329:     return %readonly_files;
12330: }
12331: # ------------------------------------------------------------ Unmark as Read Only
12332: 
12333: sub unmark_as_readonly {
12334:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
12335:     # for portfolio submissions, $what contains [$symb,$crsid] 
12336:     my ($domain,$user,$what,$file_name,$group) = @_;
12337:     $file_name = &declutter_portfile($file_name);
12338:     my $symb_crs = $what;
12339:     if (ref($what)) { $symb_crs=join('',@$what); }
12340:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
12341:     my ($tmp)=keys(%current_permissions);
12342:     if ($tmp=~/^error:/) { undef(%current_permissions); }
12343:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
12344:     foreach my $file (@readonly_files) {
12345: 	my $clean_file = &declutter_portfile($file);
12346: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
12347: 	my $current_locks = $current_permissions{$file};
12348:         my @new_locks;
12349:         my @del_keys;
12350:         if (ref($current_locks) eq "ARRAY"){
12351:             foreach my $locker (@{$current_locks}) {
12352:                 my $compare=$locker;
12353:                 if (ref($locker) eq 'ARRAY') {
12354:                     $compare=join('',@{$locker});
12355:                     if ($compare ne $symb_crs) {
12356:                         push(@new_locks, $locker);
12357:                     }
12358:                 }
12359:             }
12360:             if (scalar(@new_locks) > 0) {
12361:                 $current_permissions{$file} = \@new_locks;
12362:             } else {
12363:                 push(@del_keys, $file);
12364:                 &del('file_permissions',\@del_keys, $domain, $user);
12365:                 delete($current_permissions{$file});
12366:             }
12367:         }
12368:     }
12369:     &put('file_permissions',\%current_permissions,$domain,$user);
12370:     return;
12371: }
12372: 
12373: # ------------------------------------------------------------ Directory lister
12374: 
12375: sub dirlist {
12376:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
12377:     $uri=~s/^\///;
12378:     $uri=~s/\/$//;
12379:     my ($udom, $uname);
12380:     if ($getuserdir) {
12381:         $udom = $userdomain;
12382:         $uname = $username;
12383:     } else {
12384:         (undef,$udom,$uname)=split(/\//,$uri);
12385:         if(defined($userdomain)) {
12386:             $udom = $userdomain;
12387:         }
12388:         if(defined($username)) {
12389:             $uname = $username;
12390:         }
12391:     }
12392:     my ($dirRoot,$listing,@listing_results);
12393: 
12394:     $dirRoot = $perlvar{'lonDocRoot'};
12395:     if (defined($getpropath)) {
12396:         $dirRoot = &propath($udom,$uname);
12397:         $dirRoot =~ s/\/$//;
12398:     } elsif (defined($getuserdir)) {
12399:         my $subdir=$uname.'__';
12400:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
12401:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
12402:                    ."/$udom/$subdir/$uname";
12403:     } elsif (defined($alternateRoot)) {
12404:         $dirRoot = $alternateRoot;
12405:     }
12406: 
12407:     if($udom) {
12408:         if($uname) {
12409:             my $uhome = &homeserver($uname,$udom);
12410:             if ($uhome eq 'no_host') {
12411:                 return ([],'no_host');
12412:             }
12413:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
12414:                               .$getuserdir.':'.&escape($dirRoot)
12415:                               .':'.&escape($uname).':'.&escape($udom),$uhome);
12416:             if ($listing eq 'unknown_cmd') {
12417:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
12418:             } else {
12419:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
12420:             }
12421:             if ($listing eq 'unknown_cmd') {
12422:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
12423:                 @listing_results = split(/:/,$listing);
12424:             } else {
12425:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
12426:             }
12427:             if (($listing eq 'no_such_host') || ($listing eq 'con_lost') || 
12428:                 ($listing eq 'rejected') || ($listing eq 'refused') ||
12429:                 ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
12430:                 return ([],$listing);
12431:             } else {
12432:                 return (\@listing_results);
12433:             }
12434:         } elsif(!$alternateRoot) {
12435:             my (%allusers,%listerror);
12436: 	    my %servers = &get_servers($udom,'library');
12437:  	    foreach my $tryserver (keys(%servers)) {
12438:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
12439:                                   &escape($udom),$tryserver);
12440:                 if ($listing eq 'unknown_cmd') {
12441: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
12442: 				      $udom, $tryserver);
12443:                 } else {
12444:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
12445:                 }
12446: 		if ($listing eq 'unknown_cmd') {
12447: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
12448: 				      $udom, $tryserver);
12449: 		    @listing_results = split(/:/,$listing);
12450: 		} else {
12451: 		    @listing_results =
12452: 			map { &unescape($_); } split(/:/,$listing);
12453: 		}
12454:                 if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
12455:                     ($listing eq 'rejected') || ($listing eq 'refused') ||
12456:                     ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
12457:                     $listerror{$tryserver} = $listing;
12458:                 } else {
12459: 		    foreach my $line (@listing_results) {
12460: 			my ($entry) = split(/&/,$line,2);
12461: 			$allusers{$entry} = 1;
12462: 		    }
12463: 		}
12464:             }
12465:             my @alluserslist=();
12466:             foreach my $user (sort(keys(%allusers))) {
12467:                 push(@alluserslist,$user.'&user');
12468:             }
12469: 
12470:             if (!%listerror) {
12471:                 # no errors
12472:                 return (\@alluserslist);
12473:             } elsif (scalar(keys(%servers)) == 1) {
12474:                 # one library server, one error 
12475:                 my ($key) = keys(%listerror);
12476:                 return (\@alluserslist, $listerror{$key});
12477:             } elsif ( grep { $_ eq 'con_lost' } values(%listerror) ) {
12478:                 # con_lost indicates that we might miss data from at least one
12479:                 # library server
12480:                 return (\@alluserslist, 'con_lost');
12481:             } else {
12482:                 # multiple library servers and no con_lost -> data should be
12483:                 # complete. 
12484:                 return (\@alluserslist);
12485:             }
12486: 
12487:         } else {
12488:             return ([],'missing username');
12489:         }
12490:     } elsif(!defined($getpropath)) {
12491:         my $path = $perlvar{'lonDocRoot'}.'/res/'; 
12492:         my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
12493:         return (\@all_domains);
12494:     } else {
12495:         return ([],'missing domain');
12496:     }
12497: }
12498: 
12499: # --------------------------------------------- GetFileTimestamp
12500: # This function utilizes dirlist and returns the date stamp for
12501: # when it was last modified.  It will also return an error of -1
12502: # if an error occurs
12503: 
12504: sub GetFileTimestamp {
12505:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
12506:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
12507:     $studentName   = &LONCAPA::clean_username($studentName);
12508:     my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
12509:                                     undef,$getuserdir);
12510:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
12511:         return -1;
12512:     }
12513:     if (ref($fileref) eq 'ARRAY') {
12514:         my @stats = split('&',$fileref->[0]);
12515:         # @stats contains first the filename, then the stat output
12516:         return $stats[10]; # so this is 10 instead of 9.
12517:     } else {
12518:         return -1;
12519:     }
12520: }
12521: 
12522: sub stat_file {
12523:     my ($uri) = @_;
12524:     $uri = &clutter_with_no_wrapper($uri);
12525: 
12526:     my ($udom,$uname,$file);
12527:     if ($uri =~ m-^/(uploaded|editupload)/-) {
12528: 	($udom,$uname,$file) =
12529: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
12530: 	$file = 'userfiles/'.$file;
12531:     }
12532:     if ($uri =~ m-^/res/-) {
12533: 	($udom,$uname) = 
12534: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
12535: 	$file = $uri;
12536:     }
12537: 
12538:     if (!$udom || !$uname || !$file) {
12539: 	# unable to handle the uri
12540: 	return ();
12541:     }
12542:     my $getpropath;
12543:     if ($file =~ /^userfiles\//) {
12544:         $getpropath = 1;
12545:     }
12546:     my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
12547:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
12548:         return ();
12549:     } else {
12550:         if (ref($listref) eq 'ARRAY') {
12551:             my @stats = split('&',$listref->[0]);
12552: 	    shift(@stats); #filename is first
12553: 	    return @stats;
12554:         }
12555:     }
12556:     return ();
12557: }
12558: 
12559: # --------------------------------------------------------- recursedirs
12560: # Recursive function to traverse either a specific user's Authoring Space
12561: # or corresponding Published Resource Space, and populate the hash ref:
12562: # $dirhashref with URLs of all directories, and if $filehashref hash
12563: # ref arg is provided, the URLs of any files, excluding versioned, .meta,
12564: # or .rights files in resource space, and .meta, .save, .log, .bak and
12565: # .rights files in Authoring Space.
12566: #
12567: # Inputs:
12568: #
12569: # $is_home - true if current server is home server for user's space
12570: # $recurse - if true will also traverse subdirectories recursively
12571: # $include - reference to hash containing allowed file extensions.  If provided,
12572: #             files which do not have a matching extension will be ignored.
12573: # $exclude - reference to hash containing excluded file extensions.  If provided,
12574: #             files which have a matching extension will be ignored.
12575: # $nonemptydir - if true, will only populate $fileshashref hash entry for a particular
12576: #             directory with first file found (with acceptable extension).
12577: # $addtopdir - if true, set $dirhashref->{'/'} = 1 
12578: # $toppath - Top level directory (i.e., /res/$dom/$uname or /priv/$dom/$uname
12579: # $relpath - Current path (relative to top level).
12580: # $dirhashref - reference to hash to populate with URLs of directories (Required)
12581: # $filehashref - reference to hash to populate with URLs of files (Optional)
12582: # $getlastmod - if true, will set value for each key in innerhash in $filehashref
12583: #               to last modification time of file; value set to 1 otherwise.
12584: #
12585: # Returns: nothing
12586: #
12587: # Side Effects: populates $dirhashref, and $filehashref (if provided).
12588: #
12589: # Currently used by interface/londocs.pm to create linked select boxes for
12590: # directory and filename to import a Course "Author" resource into a course, and
12591: # also to create linked select boxes for Authoring Space and Directory to choose
12592: # save location for creation of a new "standard" problem from the Course Editor.
12593: #
12594: 
12595: sub recursedirs {
12596:     my ($is_home,$recurse,$include,$exclude,$nonemptydir,$addtopdir,$toppath,
12597:         $relpath,$dirhashref,$filehashref,$getlastmod) = @_;
12598:     return unless (ref($dirhashref) eq 'HASH');
12599:     my $docroot = $perlvar{'lonDocRoot'};
12600:     my $currpath = $docroot.$toppath;
12601:     if ($relpath ne '') {
12602:         $currpath .= "/$relpath";
12603:     }
12604:     my ($savefile,$checkinc,$checkexc);
12605:     if (ref($filehashref) eq 'HASH') {
12606:         $savefile = 1;
12607:     }
12608:     if (ref($include) eq 'HASH') {
12609:         $checkinc = 1;
12610:     }
12611:     if (ref($exclude) eq 'HASH') {
12612:         $checkexc = 1;
12613:     }
12614:     if ($is_home) {
12615:         if ((-e $currpath) && (opendir(my $dirh,$currpath))) {
12616:             my $filecount = 0;
12617:             foreach my $item (sort { lc($a) cmp lc($b) } grep(!/^\.+$/,readdir($dirh))) {
12618:                 next if ($item eq '');
12619:                 if (-d "$currpath/$item") {
12620:                     my $newpath;
12621:                     if ($relpath ne '') {
12622:                         $newpath = "$relpath/$item";
12623:                     } else {
12624:                         $newpath = $item;
12625:                     }
12626:                     $dirhashref->{&Apache::lonlocal::js_escape($newpath)} = 1;
12627:                     if ($recurse) {
12628:                         &recursedirs($is_home,$recurse,$include,$exclude,$nonemptydir,$addtopdir,
12629:                                      $toppath,$newpath,$dirhashref,$filehashref,$getlastmod);
12630:                     }
12631:                 } elsif (($savefile) || ($relpath eq '')) {
12632:                     next if ($nonemptydir && $filecount);
12633:                     if ($checkinc || $checkexc) {
12634:                         my ($extension) = ($item =~ /\.(\w+)$/);
12635:                         if ($checkinc) {
12636:                             next unless ($extension && $include->{$extension});
12637:                         }
12638:                         if ($checkexc) {
12639:                             next if ($extension && $exclude->{$extension});
12640:                         }
12641:                     }
12642:                     if (($relpath eq '') && (!exists($dirhashref->{'/'}))) {
12643:                         $dirhashref->{'/'} = 1;
12644:                     }
12645:                     if ($savefile) {
12646:                         my $value;
12647:                         if ($getlastmod) {
12648:                             ($value) = (stat("$currpath/$item"))[9];
12649:                         } else {
12650:                             $value = 1;
12651:                         }
12652:                         if ($relpath eq '') {
12653:                             $filehashref->{'/'}{$item} = $value
12654:                         } else {
12655:                             $filehashref->{&Apache::lonlocal::js_escape($relpath)}{$item} = $value;
12656:                         }
12657:                     }
12658:                     $filecount ++;
12659:                 }
12660:             }
12661:             closedir($dirh);
12662:         }
12663:     } else {
12664:         my $url = $toppath;
12665:         if ($relpath ne '') {
12666:             $url = $toppath.'/'.$relpath;
12667:         }
12668:         my ($dirlistref,$listerror) = &dirlist($url);
12669:         my @dir_lines;
12670:         my $dirptr=16384;
12671:         if (ref($dirlistref) eq 'ARRAY') {
12672:             my $filecount = 0;
12673:             foreach my $dir_line (sort
12674:                               {
12675:                                   my ($afile)=split('&',$a,2);
12676:                                   my ($bfile)=split('&',$b,2);
12677:                                   return (lc($afile) cmp lc($bfile));
12678:                               } (@{$dirlistref})) {
12679:                 my ($item,$dom,undef,$testdir,undef,undef,undef,undef,$size,undef,$mtime,undef,undef,undef,$obs,undef) =
12680:                     split(/\&/,$dir_line,16);
12681:                 $item =~ s/\s+$//;
12682:                 next if (($item =~ /^\.\.?$/) || ($obs));
12683:                 if ($dirptr&$testdir) {
12684:                     my $newpath;
12685:                     if ($relpath) {
12686:                         $newpath = "$relpath/$item";
12687:                     } else {
12688:                         $newpath = $item;
12689:                     }
12690:                     $dirhashref->{&Apache::lonlocal::js_escape($newpath)} = 1;
12691:                     if ($recurse) {
12692:                         &recursedirs($is_home,$recurse,$include,$exclude,$nonemptydir,$addtopdir,
12693:                                      $toppath,$newpath,$dirhashref,$filehashref,$getlastmod);
12694:                     }
12695:                 } elsif (($savefile) || ($relpath eq '')) {
12696:                     next if ($nonemptydir && $filecount);
12697:                     if ($checkinc || $checkexc) {
12698:                         my ($extension) = ($item =~ /\.(\w+)$/);
12699:                         if ($checkinc) {
12700:                             next unless ($extension && $include->{$extension});
12701:                         }
12702:                         if ($checkexc) {
12703:                             next if ($extension && $exclude->{$extension});
12704:                         }
12705:                     }
12706:                     if (($relpath eq '') && (!exists($dirhashref->{'/'}))) {
12707:                         $dirhashref->{'/'} = 1;
12708:                     }
12709:                     if ($savefile) {
12710:                         my $value;
12711:                         if ($getlastmod) {
12712:                             $value = $mtime;
12713:                         } else {
12714:                             $value = 1;
12715:                         }
12716:                         if ($relpath eq '') {
12717:                             $filehashref->{'/'}{$item} = $value;
12718:                         } else {
12719:                             $filehashref->{&Apache::lonlocal::js_escape($relpath)}{$item} = $value;
12720:                         }
12721:                     }
12722:                     $filecount ++; 
12723:                 }
12724:             }
12725:         }
12726:     }
12727:     if ($addtopdir) {
12728:         if (($relpath eq '') && (!exists($dirhashref->{'/'}))) {
12729:             $dirhashref->{'/'} = 1;
12730:         }
12731:     }
12732:     return;
12733: }
12734: 
12735: sub priv_exclude {
12736:     return {
12737:              meta => 1,
12738:              save => 1,
12739:              log => 1,
12740:              bak => 1,
12741:              rights => 1,
12742:              DS_Store => 1,
12743:            };
12744: }
12745: 
12746: sub res_exclude {
12747:     return {
12748:              meta => 1,
12749:              subscription => 1,
12750:              rights => 1,
12751:            };
12752: }
12753: 
12754: # -------------------------------------------------------- Value of a Condition
12755: 
12756: # gets the value of a specific preevaluated condition
12757: #    stored in the string  $env{user.state.<cid>}
12758: # or looks up a condition reference in the bighash and if if hasn't
12759: # already been evaluated recurses into docondval to get the value of
12760: # the condition, then memoizing it to 
12761: #   $env{user.state.<cid>.<condition>}
12762: sub directcondval {
12763:     my $number=shift;
12764:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
12765: 	&Apache::lonuserstate::evalstate();
12766:     }
12767:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
12768: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
12769:     } elsif ($number =~ /^_/) {
12770: 	my $sub_condition;
12771: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
12772: 		&GDBM_READER(),0640)) {
12773: 	    $sub_condition=$bighash{'conditions'.$number};
12774: 	    untie(%bighash);
12775: 	}
12776: 	my $value = &docondval($sub_condition);
12777: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
12778: 	return $value;
12779:     }
12780:     if ($env{'user.state.'.$env{'request.course.id'}}) {
12781:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
12782:     } else {
12783:        return 2;
12784:     }
12785: }
12786: 
12787: # get the collection of conditions for this resource
12788: sub condval {
12789:     my $condidx=shift;
12790:     my $allpathcond='';
12791:     foreach my $cond (split(/\|/,$condidx)) {
12792: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
12793: 	    $allpathcond.=
12794: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
12795: 	}
12796:     }
12797:     $allpathcond=~s/\|$//;
12798:     return &docondval($allpathcond);
12799: }
12800: 
12801: #evaluates an expression of conditions
12802: sub docondval {
12803:     my ($allpathcond) = @_;
12804:     my $result=0;
12805:     if ($env{'request.course.id'}
12806: 	&& defined($allpathcond)) {
12807: 	my $operand='|';
12808: 	my @stack;
12809: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
12810: 	    if ($chunk eq '(') {
12811: 		push @stack,($operand,$result);
12812: 	    } elsif ($chunk eq ')') {
12813: 		my $before=pop @stack;
12814: 		if (pop @stack eq '&') {
12815: 		    $result=$result>$before?$before:$result;
12816: 		} else {
12817: 		    $result=$result>$before?$result:$before;
12818: 		}
12819: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
12820: 		$operand=$chunk;
12821: 	    } else {
12822: 		my $new=directcondval($chunk);
12823: 		if ($operand eq '&') {
12824: 		    $result=$result>$new?$new:$result;
12825: 		} else {
12826: 		    $result=$result>$new?$result:$new;
12827: 		}
12828: 	    }
12829: 	}
12830:     }
12831:     return $result;
12832: }
12833: 
12834: # ---------------------------------------------------- Devalidate courseresdata
12835: 
12836: sub devalidatecourseresdata {
12837:     my ($coursenum,$coursedomain)=@_;
12838:     my $hashid=$coursenum.':'.$coursedomain;
12839:     &devalidate_cache_new('courseres',$hashid);
12840: }
12841: 
12842: 
12843: # --------------------------------------------------- Course Resourcedata Query
12844: #
12845: #  Parameters:
12846: #      $coursenum    - Number of the course.
12847: #      $coursedomain - Domain at which the course was created.
12848: #  Returns:
12849: #     A hash of the course parameters along (I think) with timestamps
12850: #     and version info.
12851: 
12852: sub get_courseresdata {
12853:     my ($coursenum,$coursedomain)=@_;
12854:     my $coursehom=&homeserver($coursenum,$coursedomain);
12855:     my $hashid=$coursenum.':'.$coursedomain;
12856:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
12857:     my %dumpreply;
12858:     unless (defined($cached)) {
12859: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
12860: 	$result=\%dumpreply;
12861: 	my ($tmp) = keys(%dumpreply);
12862: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
12863: 	    &do_cache_new('courseres',$hashid,$result,600);
12864: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
12865: 	    return $tmp;
12866: 	} elsif ($tmp =~ /^(error)/) {
12867: 	    $result=undef;
12868: 	    &do_cache_new('courseres',$hashid,$result,600);
12869: 	}
12870:     }
12871:     return $result;
12872: }
12873: 
12874: sub devalidateuserresdata {
12875:     my ($uname,$udom)=@_;
12876:     my $hashid="$udom:$uname";
12877:     &devalidate_cache_new('userres',$hashid);
12878: }
12879: 
12880: sub get_userresdata {
12881:     my ($uname,$udom)=@_;
12882:     #most student don\'t have any data set, check if there is some data
12883:     if (&EXT_cache_status($udom,$uname)) { return undef; }
12884: 
12885:     my $hashid="$udom:$uname";
12886:     my ($result,$cached)=&is_cached_new('userres',$hashid);
12887:     if (!defined($cached)) {
12888: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
12889: 	$result=\%resourcedata;
12890: 	&do_cache_new('userres',$hashid,$result,600);
12891:     }
12892:     my ($tmp)=keys(%$result);
12893:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
12894: 	return $result;
12895:     }
12896:     #error 2 occurs when the .db doesn't exist
12897:     if ($tmp!~/error: 2 /) {
12898:         if ((!defined($cached)) || ($tmp ne 'con_lost')) {
12899: 	    &logthis("<font color=\"blue\">WARNING:".
12900: 		     " Trying to get resource data for ".
12901: 		     $uname." at ".$udom.": ".
12902: 		     $tmp."</font>");
12903:         }
12904:     } elsif ($tmp=~/error: 2 /) {
12905: 	#&EXT_cache_set($udom,$uname);
12906: 	&do_cache_new('userres',$hashid,undef,600);
12907: 	undef($tmp); # not really an error so don't send it back
12908:     }
12909:     return $tmp;
12910: }
12911: #----------------------------------------------- resdata - return resource data
12912: #  Purpose:
12913: #    Return resource data for either users or for a course.
12914: #  Parameters:
12915: #     $name      - Course/user name.
12916: #     $domain    - Name of the domain the user/course is registered on.
12917: #     $type      - Type of thing $name is (must be 'course' or 'user')
12918: #     $mapp      - decluttered URL of enclosing map  
12919: #     $recursed  - Ref to scalar -- set to 1, if nested maps have been recursed.
12920: #     $recurseup - Ref to array of map URLs, starting with map containing
12921: #                  $mapp up through hierarchy of nested maps to top level map.  
12922: #     $courseid  - CourseID (first part of param identifier).
12923: #     $modifier  - Middle part of param identifier.
12924: #     $what      - Last part of param identifier.
12925: #     @which     - Array of names of resources desired.
12926: #  Returns:
12927: #     The value of the first reasource in @which that is found in the
12928: #     resource hash.
12929: #  Exceptional Conditions:
12930: #     If the $type passed in is not valid (not the string 'course' or 
12931: #     'user', an undefined  reference is returned.
12932: #     If none of the resources are found, an undef is returned
12933: sub resdata {
12934:     my ($name,$domain,$type,$mapp,$recursed,$recurseup,$courseid,
12935:         $modifier,$what,@which)=@_;
12936:     my $result;
12937:     if ($type eq 'course') {
12938: 	$result=&get_courseresdata($name,$domain);
12939:     } elsif ($type eq 'user') {
12940: 	$result=&get_userresdata($name,$domain);
12941:     }
12942:     if (!ref($result)) { return $result; }    
12943:     foreach my $item (@which) {
12944:         if ($item->[1] eq 'course') {
12945:             if ((ref($recurseup) eq 'ARRAY') && (ref($recursed) eq 'SCALAR')) {
12946:                 unless ($$recursed) {
12947:                     @{$recurseup} = &get_map_hierarchy($mapp,$courseid);
12948:                     $$recursed = 1;
12949:                 }
12950:                 foreach my $item (@${recurseup}) {
12951:                     my $norecursechk=$courseid.$modifier.$item.'___(all).'.$what;
12952:                     last if (defined($result->{$norecursechk}));
12953:                     my $recursechk=$courseid.$modifier.$item.'___(rec).'.$what;
12954:                     if (defined($result->{$recursechk})) { return [$result->{$recursechk},'map']; }
12955:                 }
12956:             }
12957:         }
12958:         if (defined($result->{$item->[0]})) {
12959: 	    return [$result->{$item->[0]},$item->[1]];
12960: 	}
12961:     }
12962:     return undef;
12963: }
12964: 
12965: sub get_domain_lti {
12966:     my ($cdom,$context) = @_;
12967:     my ($name,$cachename,%lti);
12968:     if ($context eq 'consumer') {
12969:         $name = 'ltitools';
12970:     } elsif ($context eq 'provider') {
12971:         $name = 'lti';
12972:     } elsif ($context eq 'linkprot') {
12973:         $name = 'ltisec';
12974:     } else {
12975:         return %lti;
12976:     }
12977:     if ($context eq 'linkprot') {
12978:         $cachename = $context;
12979:     } else {
12980:         $cachename = $name;
12981:     }
12982:     my ($result,$cached)=&is_cached_new($cachename,$cdom);
12983:     if (defined($cached)) {
12984:         if (ref($result) eq 'HASH') {
12985:             %lti = %{$result};
12986:         }
12987:     } else {
12988:         my %domconfig = &get_dom('configuration',[$name],$cdom);
12989:         if (ref($domconfig{$name}) eq 'HASH') {
12990:             if ($context eq 'linkprot') {
12991:                 if (ref($domconfig{$name}{'linkprot'}) eq 'HASH') {
12992:                     %lti = %{$domconfig{$name}{'linkprot'}};
12993:                 }
12994:             } else {
12995:                 %lti = %{$domconfig{$name}};
12996:             }
12997:         }
12998:         my $cachetime = 24*60*60;
12999:         &do_cache_new($cachename,$cdom,\%lti,$cachetime);
13000:     }
13001:     return %lti;
13002: }
13003: 
13004: sub get_course_lti {
13005:     my ($cnum,$cdom,$context) = @_;
13006:     my ($name,$cachename,%lti);
13007:     if ($context eq 'consumer') {
13008:         $name = 'ltitools';
13009:         $cachename = 'courseltitools';
13010:     } elsif ($context eq 'provider') {
13011:         $name = 'lti';
13012:         $cachename = 'courselti';
13013:     } else {
13014:         return %lti;
13015:     }
13016:     my $hashid=$cdom.'_'.$cnum;
13017:     my ($result,$cached)=&is_cached_new($cachename,$hashid);
13018:     if (defined($cached)) {
13019:         if (ref($result) eq 'HASH') {
13020:             %lti = %{$result};
13021:         }
13022:     } else {
13023:         %lti = &dump($name,$cdom,$cnum,undef,undef,undef,1);
13024:         my $cachetime = 24*60*60;
13025:         &do_cache_new($cachename,$hashid,\%lti,$cachetime);
13026:     }
13027:     return %lti;
13028: }
13029: 
13030: sub courselti_itemid {
13031:     my ($cnum,$cdom,$url,$method,$params,$context) = @_;
13032:     my ($chome,$itemid);
13033:     $chome = &homeserver($cnum,$cdom);
13034:     return if ($chome eq 'no_host');
13035:     if (ref($params) eq 'HASH') {
13036:         my $rep;
13037:         if (grep { $_ eq $chome } current_machine_ids()) {
13038:             $rep = LONCAPA::Lond::crslti_itemid($cdom,$cnum,$url,$method,$params,$perlvar{'lonVersion'});
13039:         } else {
13040:             my $escurl = &escape($url);
13041:             my $escmethod = &escape($method);
13042:             my $items = &freeze_escape($params);
13043:             $rep = &reply("encrypt:lti:$cdom:$cnum:$context:$escurl:$escmethod:$items",$chome);
13044:         }
13045:         unless (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
13046:                 ($rep eq 'unknown_cmd')) {
13047:             $itemid = $rep;
13048:         }
13049:     }
13050:     return $itemid;
13051: }
13052: 
13053: sub domainlti_itemid {
13054:     my ($cdom,$url,$method,$params,$context) = @_;
13055:     my ($primary_id,$itemid);
13056:     $primary_id = &domain($cdom,'primary');
13057:     return if ($primary_id eq '');
13058:     if (ref($params) eq 'HASH') {
13059:         my $rep;
13060:         if (grep { $_ eq $primary_id } current_machine_ids()) {
13061:             $rep = LONCAPA::Lond::domlti_itemid($cdom,$context,$url,$method,$params,$perlvar{'lonVersion'});
13062:         } else {
13063:             my $cnum = '';
13064:             my $escurl = &escape($url);
13065:             my $escmethod = &escape($method);
13066:             my $items = &freeze_escape($params);
13067:             $rep = &reply("encrypt:lti:$cdom:$cnum:$context:$escurl:$escmethod:$items",$primary_id);
13068:         }
13069:         unless (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
13070:                 ($rep eq 'unknown_cmd')) {
13071:             $itemid = $rep;
13072:         }
13073:     }
13074:     return $itemid;
13075: }
13076: 
13077: sub get_ltitools_id {
13078:     my ($context,$cdom,$cnum,$title) = @_;
13079:     my ($lockhash,$tries,$gotlock,$id,$error);
13080: 
13081:     # get lock on ltitools db
13082:     $lockhash = {
13083:                    lock => $env{'user.name'}.
13084:                            ':'.$env{'user.domain'},
13085:                 };
13086:     $tries = 0;
13087:     if ($context eq 'domain') {
13088:         $gotlock = &newput_dom('ltitools',$lockhash,$cdom);
13089:     } else {
13090:         $gotlock = &newput('ltitools',$lockhash,$cdom,$cnum);
13091:     }
13092:     while (($gotlock ne 'ok') && ($tries<10)) {
13093:         $tries ++;
13094:         sleep (0.1);
13095:         if ($context eq 'domain') {
13096:             $gotlock = &newput_dom('ltitools',$lockhash,$cdom);
13097:         } else {
13098:             $gotlock = &newput('ltitools',$lockhash,$cdom,$cnum);
13099:         }
13100:     }
13101:     if ($gotlock eq 'ok') {
13102:         my %currids;
13103:         if ($context eq 'domain') {
13104:             %currids = &dump_dom('ltitools',$cdom);
13105:         } else {
13106:             %currids = &dump('ltitools',$cdom,$cnum);
13107:         }
13108:         if ($currids{'lock'}) {
13109:             delete($currids{'lock'});
13110:             if (keys(%currids)) {
13111:                 my @curr = sort { $a <=> $b } keys(%currids);
13112:                 if ($curr[-1] =~ /^\d+$/) {
13113:                     $id = 1 + $curr[-1];
13114:                 }
13115:             } else {
13116:                 $id = 1;
13117:             }
13118:             if ($id) {
13119:                 if ($context eq 'domain') {
13120:                     unless (&newput_dom('ltitools',{ $id => $title },$cdom) eq 'ok') {
13121:                         $error = 'nostore';
13122:                     }
13123:                 } else {
13124:                     unless (&newput('ltitools',{ $id => $title },$cdom,$cnum) eq 'ok') {
13125:                         $error = 'nostore';
13126:                     }
13127:                 }
13128:             } else {
13129:                 $error = 'nonumber';
13130:             }
13131:         }
13132:         my $dellockoutcome;
13133:         if ($context eq 'domain') {
13134:             $dellockoutcome = &del_dom('ltitools',['lock'],$cdom);
13135:         } else {
13136:             $dellockoutcome = &del('ltitools',['lock'],$cdom,$cnum);
13137:         }
13138:     } else {
13139:         $error = 'nolock';
13140:     }
13141:     return ($id,$error);
13142: }
13143: 
13144: sub count_supptools {
13145:     my ($cnum,$cdom,$ignorecache,$reload)=@_;
13146:     my $hashid=$cnum.':'.$cdom;
13147:     my ($numexttools,$cached);
13148:     unless ($ignorecache) {
13149:         ($numexttools,$cached) = &is_cached_new('supptools',$hashid);
13150:     }
13151:     unless (defined($cached)) {
13152:         my $chome=&homeserver($cnum,$cdom);
13153:         $numexttools = 0;
13154:         unless ($chome eq 'no_host') {
13155:             my ($supplemental) = &Apache::loncommon::get_supplemental($cnum,$cdom,$reload);
13156:             if (ref($supplemental) eq 'HASH') {
13157:                 if ((ref($supplemental->{'ids'}) eq 'HASH') && (ref($supplemental->{'hidden'}) eq 'HASH')) {
13158:                     foreach my $key (keys(%{$supplemental->{'ids'}})) {
13159:                         if ($key =~ m{^/adm/$cdom/$cnum/\d+/ext\.tool$}) {
13160:                             $numexttools ++;
13161:                         }
13162:                     }
13163:                 }
13164:             }
13165:         }
13166:         &do_cache_new('supptools',$hashid,$numexttools,600);
13167:     }
13168:     return $numexttools;
13169: }
13170: 
13171: sub has_unhidden_suppfiles {
13172:     my ($cnum,$cdom,$ignorecache,$possdel)=@_;
13173:     my $hashid=$cnum.':'.$cdom;
13174:     my ($showsupp,$cached);
13175:     unless ($ignorecache) {
13176:         ($showsupp,$cached) = &is_cached_new('showsupp',$hashid);
13177:     }
13178:     unless (defined($cached)) {
13179:         my $chome=&homeserver($cnum,$cdom);
13180:         unless ($chome eq 'no_host') {
13181:             my ($supplemental) = &Apache::loncommon::get_supplemental($cnum,$cdom,$ignorecache,$possdel);
13182:             if (ref($supplemental) eq 'HASH') {
13183:                 if ((ref($supplemental->{'ids'}) eq 'HASH') && (ref($supplemental->{'hidden'}) eq 'HASH')) {
13184:                     foreach my $key (keys(%{$supplemental->{'ids'}})) {
13185:                         next if ($key =~ /\.sequence$/);
13186:                         if (ref($supplemental->{'ids'}->{$key}) eq 'ARRAY') {
13187:                             foreach my $id (@{$supplemental->{'ids'}->{$key}}) {
13188:                                 unless ($supplemental->{'hidden'}->{$id}) {
13189:                                     $showsupp = 1;
13190:                                     last;
13191:                                 }
13192:                             }
13193:                         }
13194:                         last if ($showsupp);
13195:                     }
13196:                 }
13197:             }
13198:         }
13199:         &do_cache_new('showsupp',$hashid,$showsupp,600);
13200:     }
13201:     return $showsupp;
13202: }
13203: 
13204: #
13205: # EXT resource caching routines
13206: #
13207: 
13208: {
13209: # Cache (5 seconds) of map hierarchy for speedup of navmaps display
13210: #
13211: # The course for which we cache
13212: my $cachedmapkey='';
13213: # The cached recursive maps for this course
13214: my %cachedmaps=();
13215: # When this was last done
13216: my $cachedmaptime='';
13217: 
13218: sub clear_EXT_cache_status {
13219:     &delenv('cache.EXT.');
13220: }
13221: 
13222: sub EXT_cache_status {
13223:     my ($target_domain,$target_user) = @_;
13224:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
13225:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
13226:         # We know already the user has no data
13227:         return 1;
13228:     } else {
13229:         return 0;
13230:     }
13231: }
13232: 
13233: sub EXT_cache_set {
13234:     my ($target_domain,$target_user) = @_;
13235:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
13236:     #&appenv({$cachename => time});
13237: }
13238: 
13239: # --------------------------------------------------------- Value of a Variable
13240: sub EXT {
13241: 
13242:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse,$cid,$recurseupref)=@_;
13243:     unless ($varname) { return ''; }
13244:     #get real user name/domain, courseid and symb
13245:     my $courseid;
13246:     my $publicuser;
13247:     if ($symbparm) {
13248: 	$symbparm=&get_symb_from_alias($symbparm);
13249:     }
13250:     if (!($uname && $udom)) {
13251:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
13252:       if (!$symbparm) {	$symbparm=$cursymb; }
13253:     } else {
13254: 	$courseid=$env{'request.course.id'};
13255:     }
13256:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
13257:     my $rest;
13258:     if (defined($therest[0])) {
13259:        $rest=join('.',@therest);
13260:     } else {
13261:        $rest='';
13262:     }
13263: 
13264:     my $qualifierrest=$qualifier;
13265:     if ($rest) { $qualifierrest.='.'.$rest; }
13266:     my $spacequalifierrest=$space;
13267:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
13268:     if ($realm eq 'user') {
13269: # --------------------------------------------------------------- user.resource
13270: 	if ($space eq 'resource') {
13271: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
13272: 		  || defined($Apache::lonhomework::parsing_a_task))
13273: 		 &&
13274: 		 ($symbparm eq &symbread()) ) {
13275: 		# if we are in the middle of processing the resource the
13276: 		# get the value we are planning on committing
13277:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
13278:                     return $Apache::lonhomework::results{$qualifierrest};
13279:                 } else {
13280:                     return $Apache::lonhomework::history{$qualifierrest};
13281:                 }
13282: 	    } else {
13283: 		my %restored;
13284: 		if ($publicuser || $env{'request.state'} eq 'construct') {
13285: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
13286: 		} else {
13287: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
13288: 		}
13289: 		return $restored{$qualifierrest};
13290: 	    }
13291: # ----------------------------------------------------------------- user.access
13292:         } elsif ($space eq 'access') {
13293: 	    # FIXME - not supporting calls for a specific user
13294:             return &allowed($qualifier,$rest);
13295: # ------------------------------------------ user.preferences, user.environment
13296:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
13297: 	    if (($uname eq $env{'user.name'}) &&
13298: 		($udom eq $env{'user.domain'})) {
13299: 		return $env{join('.',('environment',$qualifierrest))};
13300: 	    } else {
13301: 		my %returnhash;
13302: 		if (!$publicuser) {
13303: 		    %returnhash=&userenvironment($udom,$uname,
13304: 						 $qualifierrest);
13305: 		}
13306: 		return $returnhash{$qualifierrest};
13307: 	    }
13308: # ----------------------------------------------------------------- user.course
13309:         } elsif ($space eq 'course') {
13310: 	    # FIXME - not supporting calls for a specific user
13311:             return $env{join('.',('request.course',$qualifier))};
13312: # ------------------------------------------------------------------- user.role
13313:         } elsif ($space eq 'role') {
13314: 	    # FIXME - not supporting calls for a specific user
13315:             my ($role,$where)=split(/\./,$env{'request.role'});
13316:             if ($qualifier eq 'value') {
13317: 		return $role;
13318:             } elsif ($qualifier eq 'extent') {
13319:                 return $where;
13320:             }
13321: # ----------------------------------------------------------------- user.domain
13322:         } elsif ($space eq 'domain') {
13323:             return $udom;
13324: # ------------------------------------------------------------------- user.name
13325:         } elsif ($space eq 'name') {
13326:             return $uname;
13327: # ---------------------------------------------------- Any other user namespace
13328:         } else {
13329: 	    my %reply;
13330: 	    if (!$publicuser) {
13331: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
13332: 	    }
13333: 	    return $reply{$qualifierrest};
13334:         }
13335:     } elsif ($realm eq 'query') {
13336: # ---------------------------------------------- pull stuff out of query string
13337:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
13338: 						[$spacequalifierrest]);
13339: 	return $env{'form.'.$spacequalifierrest}; 
13340:    } elsif ($realm eq 'request') {
13341: # ------------------------------------------------------------- request.browser
13342:         if ($space eq 'browser') {
13343:             return $env{'browser.'.$qualifier};
13344: # ------------------------------------------------------------ request.filename
13345:         } else {
13346:             return $env{'request.'.$spacequalifierrest};
13347:         }
13348:     } elsif ($realm eq 'course') {
13349: # ---------------------------------------------------------- course.description
13350:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
13351:     } elsif ($realm eq 'resource') {
13352: 
13353: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
13354: 	    if (!$symbparm) { $symbparm=&symbread(); }
13355: 	}
13356: 
13357:         if ($qualifier eq '') {
13358: 	    if ($space eq 'title') {
13359: 	        if (!$symbparm) { $symbparm = $env{'request.filename'}; }
13360: 	        return &gettitle($symbparm);
13361: 	    }
13362: 	
13363: 	    if ($space eq 'map') {
13364: 	        my ($map) = &decode_symb($symbparm);
13365: 	        return &symbread($map);
13366: 	    }
13367:             if ($space eq 'maptitle') {
13368:                 my ($map) = &decode_symb($symbparm);
13369:                 return &gettitle($map);
13370:             }
13371: 	    if ($space eq 'filename') {
13372: 	        if ($symbparm) {
13373: 		    return &clutter((&decode_symb($symbparm))[2]);
13374: 	        }
13375: 	        return &hreflocation('',$env{'request.filename'});
13376: 	    }
13377: 
13378:             if ((defined($courseid)) && ($courseid eq $env{'request.course.id'}) && $symbparm) {
13379:                 if ($space eq 'visibleparts') {
13380:                     my $navmap = Apache::lonnavmaps::navmap->new();
13381:                     my $item;
13382:                     if (ref($navmap)) {
13383:                         my $res = $navmap->getBySymb($symbparm);
13384:                         my $parts = $res->parts();
13385:                         if (ref($parts) eq 'ARRAY') {
13386:                             $item = join(',',@{$parts});
13387:                         }
13388:                         undef($navmap);
13389:                     }
13390:                     return $item;
13391:                 }
13392:             }
13393:         }
13394: 
13395: 	my ($section, $group, @groups, @recurseup, $recursed);
13396:         if (ref($recurseupref) eq 'ARRAY') {
13397:             @recurseup = @{$recurseupref};
13398:             $recursed = 1;
13399:         }
13400: 	my ($courselevelm,$courseleveli,$courselevel,$mapp);
13401:         if (($courseid eq '') && ($cid)) {
13402:             $courseid = $cid;
13403:         }
13404: 	if (($symbparm && $courseid) && 
13405: 	    (($courseid eq $env{'request.course.id'}) || ($courseid eq $cid)))  {
13406: 
13407: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
13408: 
13409: # ----------------------------------------------------- Cascading lookup scheme
13410: 	    my $symbp=$symbparm;
13411: 	    $mapp=&deversion((&decode_symb($symbp))[0]);
13412: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
13413:             my $recurseparm=$mapp.'___(rec).'.$spacequalifierrest;
13414: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
13415: 	    if (($env{'user.name'} eq $uname) &&
13416: 		($env{'user.domain'} eq $udom)) {
13417: 		$section=$env{'request.course.sec'};
13418:                 @groups = split(/:/,$env{'request.course.groups'});  
13419:                 @groups=&sort_course_groups($courseid,@groups); 
13420: 	    } else {
13421: 		if (! defined($usection)) {
13422: 		    $section=&getsection($udom,$uname,$courseid);
13423: 		} else {
13424: 		    $section = $usection;
13425: 		}
13426:                 @groups = &get_users_groups($udom,$uname,$courseid);
13427: 	    }
13428: 
13429: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
13430: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
13431:             my $secleveli=$courseid.'.['.$section.'].'.$recurseparm;
13432: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
13433: 
13434: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
13435: 	    my $courselevelr=$courseid.'.'.$symbparm;
13436:             $courseleveli=$courseid.'.'.$recurseparm;
13437: 	    $courselevelm=$courseid.'.'.$mapparm;
13438: 
13439: # ----------------------------------------------------------- first, check user
13440: 
13441: 	    my $userreply=&resdata($uname,$udom,'user',$mapp,\$recursed,
13442:                                    \@recurseup,$courseid,'.',$spacequalifierrest, 
13443: 				       ([$courselevelr,'resource'],
13444: 					[$courselevelm,'map'     ],
13445:                                         [$courseleveli,'map'     ],
13446: 					[$courselevel, 'course'  ]));
13447: 	    if (defined($userreply)) { return &get_reply($userreply); }
13448: 
13449: # ------------------------------------------------ second, check some of course
13450:             my $coursereply;
13451:             if (@groups > 0) {
13452:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
13453:                                        $recurseparm,$mapparm,$spacequalifierrest,
13454:                                        $mapp,\$recursed,\@recurseup);
13455:                 if (defined($coursereply)) { return &get_reply($coursereply); } 
13456:             }
13457: 
13458: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
13459: 				  $env{'course.'.$courseid.'.domain'},
13460: 				  'course',$mapp,\$recursed,\@recurseup,
13461:                                   $courseid,'.['.$section.'].',$spacequalifierrest,
13462: 				  ([$seclevelr,   'resource'],
13463: 				   [$seclevelm,   'map'     ],
13464:                                    [$secleveli,   'map'     ],
13465: 				   [$seclevel,    'course'  ],
13466: 				   [$courselevelr,'resource']));
13467: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
13468: 
13469: # ------------------------------------------------------ third, check map parms
13470: 	    my %parmhash=();
13471: 	    my $thisparm='';
13472: 	    if (tie(%parmhash,'GDBM_File',
13473: 		    $env{'request.course.fn'}.'_parms.db',
13474: 		    &GDBM_READER(),0640)) {
13475: 		$thisparm=$parmhash{$symbparm};
13476: 		untie(%parmhash);
13477: 	    }
13478: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
13479: 	}
13480: # ------------------------------------------ fourth, look in resource metadata
13481:  
13482:         my $what = $spacequalifierrest;
13483: 	$what=~s/\./\_/;
13484: 	my $filename;
13485: 	if (!$symbparm) { $symbparm=&symbread(); }
13486: 	if ($symbparm) {
13487: 	    $filename=(&decode_symb($symbparm))[2];
13488: 	} else {
13489: 	    $filename=$env{'request.filename'};
13490: 	}
13491:         my $toolsymb;
13492:         if (($filename =~ /ext\.tool$/) && ($what ne '0_gradable')) {
13493:             $toolsymb = $symbparm;
13494:         }
13495: 	my $metadata=&metadata($filename,$what,$toolsymb);
13496: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
13497: 	$metadata=&metadata($filename,'parameter_'.$what,$toolsymb);
13498: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
13499: 
13500: # ----------------------------------------------- fifth, look in rest of course
13501: 	if ($symbparm && defined($courseid) && 
13502: 	    $courseid eq $env{'request.course.id'}) {
13503: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
13504: 				     $env{'course.'.$courseid.'.domain'},
13505: 				     'course',$mapp,\$recursed,\@recurseup,
13506:                                      $courseid,'.',$spacequalifierrest,
13507: 				     ([$courselevelm,'map'   ],
13508:                                       [$courseleveli,'map'   ],
13509: 				      [$courselevel, 'course']));
13510: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
13511: 	}
13512: # ------------------------------------------------------------------ Cascade up
13513: 	unless ($space eq '0') {
13514: 	    my @parts=split(/_/,$space);
13515: 	    my $id=pop(@parts);
13516: 	    my $part=join('_',@parts);
13517: 	    if ($part eq '') { $part='0'; }
13518: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
13519: 				 $symbparm,$udom,$uname,$section,1);
13520: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
13521: 	}
13522: 	if ($recurse) { return undef; }
13523: 	my $pack_def=&packages_tab_default($filename,$varname,$toolsymb);
13524: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
13525: # ---------------------------------------------------- Any other user namespace
13526:     } elsif ($realm eq 'environment') {
13527: # ----------------------------------------------------------------- environment
13528: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
13529: 	    return $env{'environment.'.$spacequalifierrest};
13530: 	} else {
13531: 	    if ($uname eq 'anonymous' && $udom eq '') {
13532: 		return '';
13533: 	    }
13534: 	    my %returnhash=&userenvironment($udom,$uname,
13535: 					    $spacequalifierrest);
13536: 	    return $returnhash{$spacequalifierrest};
13537: 	}
13538:     } elsif ($realm eq 'system') {
13539: # ----------------------------------------------------------------- system.time
13540: 	if ($space eq 'time') {
13541: 	    return time;
13542:         }
13543:     } elsif ($realm eq 'server') {
13544: # ----------------------------------------------------------------- system.time
13545: 	if ($space eq 'name') {
13546: 	    return $ENV{'SERVER_NAME'};
13547:         }
13548:     } elsif ($realm eq 'client') {
13549:         if ($space eq 'remote_addr') {
13550:             return &get_requestor_ip();
13551:         }
13552:     }
13553:     return '';
13554: }
13555: 
13556: sub get_reply {
13557:     my ($reply_value) = @_;
13558:     if (ref($reply_value) eq 'ARRAY') {
13559:         if (wantarray) {
13560: 	    return @$reply_value;
13561:         }
13562:         return $reply_value->[0];
13563:     } else {
13564:         return $reply_value;
13565:     }
13566: }
13567: 
13568: sub check_group_parms {
13569:     my ($courseid,$groups,$symbparm,$recurseparm,$mapparm,$what,$mapp,
13570:         $recursed,$recurseupref) = @_;
13571:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$recurseparm,'map'],
13572:                   [$what,'course']);
13573:     my $coursereply;
13574:     foreach my $group (@{$groups}) {
13575:         my @groupitems = ();
13576:         foreach my $level (@levels) {
13577:              my $item = $courseid.'.['.$group.'].'.$level->[0];
13578:              push(@groupitems,[$item,$level->[1]]);
13579:         }
13580:         my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
13581:                                    $env{'course.'.$courseid.'.domain'},
13582:                                    'course',$mapp,$recursed,$recurseupref,
13583:                                    $courseid,'.['.$group.'].',$what,
13584:                                    @groupitems);
13585:         last if (defined($coursereply));
13586:     }
13587:     return $coursereply;
13588: }
13589: 
13590: sub get_map_hierarchy {
13591:     my ($mapname,$courseid) = @_;
13592:     my @recurseup = ();
13593:     if ($mapname) {
13594:         if (($cachedmapkey eq $courseid) &&
13595:             (abs($cachedmaptime-time)<5)) {
13596:             if (ref($cachedmaps{$mapname}) eq 'ARRAY') {
13597:                 return @{$cachedmaps{$mapname}};
13598:             }
13599:         }
13600:         my $navmap = Apache::lonnavmaps::navmap->new();
13601:         if (ref($navmap)) {
13602:             @recurseup = $navmap->recurseup_maps($mapname);
13603:             undef($navmap);
13604:             $cachedmaps{$mapname} = \@recurseup;
13605:             $cachedmaptime=time;
13606:             $cachedmapkey=$courseid;
13607:         }
13608:     }
13609:     return @recurseup;
13610: }
13611: 
13612: }
13613: 
13614: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
13615:     my ($courseid,@groups) = @_;
13616:     @groups = sort(@groups);
13617:     return @groups;
13618: }
13619: 
13620: sub packages_tab_default {
13621:     my ($uri,$varname,$toolsymb)=@_;
13622:     my (undef,$part,$name)=split(/\./,$varname);
13623: 
13624:     my (@extension,@specifics,$do_default);
13625:     foreach my $package (split(/,/,&metadata($uri,'packages',$toolsymb))) {
13626: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
13627: 	if ($pack_type eq 'default') {
13628: 	    $do_default=1;
13629: 	} elsif ($pack_type eq 'extension') {
13630: 	    push(@extension,[$package,$pack_type,$pack_part]);
13631: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
13632: 	    # only look at packages defaults for packages that this id is
13633: 	    push(@specifics,[$package,$pack_type,$pack_part]);
13634: 	}
13635:     }
13636:     # first look for a package that matches the requested part id
13637:     foreach my $package (@specifics) {
13638: 	my (undef,$pack_type,$pack_part)=@{$package};
13639: 	next if ($pack_part ne $part);
13640: 	if (defined($packagetab{"$pack_type&$name&default"})) {
13641: 	    return $packagetab{"$pack_type&$name&default"};
13642: 	}
13643:     }
13644:     # look for any possible matching non extension_ package
13645:     foreach my $package (@specifics) {
13646: 	my (undef,$pack_type,$pack_part)=@{$package};
13647: 	if (defined($packagetab{"$pack_type&$name&default"})) {
13648: 	    return $packagetab{"$pack_type&$name&default"};
13649: 	}
13650: 	if ($pack_type eq 'part') { $pack_part='0'; }
13651: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
13652: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
13653: 	}
13654:     }
13655:     # look for any posible extension_ match
13656:     foreach my $package (@extension) {
13657: 	my ($package,$pack_type)=@{$package};
13658: 	if (defined($packagetab{"$pack_type&$name&default"})) {
13659: 	    return $packagetab{"$pack_type&$name&default"};
13660: 	}
13661: 	if (defined($packagetab{$package."&$name&default"})) {
13662: 	    return $packagetab{$package."&$name&default"};
13663: 	}
13664:     }
13665:     # look for a global default setting
13666:     if ($do_default && defined($packagetab{"default&$name&default"})) {
13667: 	return $packagetab{"default&$name&default"};
13668:     }
13669:     return undef;
13670: }
13671: 
13672: sub add_prefix_and_part {
13673:     my ($prefix,$part)=@_;
13674:     my $keyroot;
13675:     if (defined($prefix) && $prefix !~ /^__/) {
13676: 	# prefix that has a part already
13677: 	$keyroot=$prefix;
13678:     } elsif (defined($prefix)) {
13679: 	# prefix that is missing a part
13680: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
13681:     } else {
13682: 	# no prefix at all
13683: 	if (defined($part)) { $keyroot='_'.$part; }
13684:     }
13685:     return $keyroot;
13686: }
13687: 
13688: # ---------------------------------------------------------------- Get metadata
13689: 
13690: my %metaentry;
13691: my %importedpartids;
13692: my %importedrespids;
13693: sub metadata {
13694:     my ($uri,$what,$toolsymb,$liburi,$prefix,$depthcount)=@_;
13695:     $uri=&declutter($uri);
13696:     # if it is a non metadata possible uri return quickly
13697:     if (($uri eq '') || 
13698: 	(($uri =~ m|^/*adm/|) && 
13699: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard|ext\.tool)$})) ||
13700:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
13701: 	return undef;
13702:     }
13703:     if (($uri =~ /^priv/ || $uri=~m{^home/httpd/html/priv}) 
13704: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
13705: 	return undef;
13706:     }
13707:     my $filename=$uri;
13708:     $uri=~s/\.meta$//;
13709: #
13710: # Is the metadata already cached?
13711: # Look at timestamp of caching
13712: # Everything is cached by the main uri, libraries are never directly cached
13713: #
13714:     if (!defined($liburi)) {
13715: 	my ($result,$cached)=&is_cached_new('meta',$uri);
13716: 	if (defined($cached)) { return $result->{':'.$what}; }
13717:     }
13718: 
13719: #
13720: # If the uri is for an external tool the file from
13721: # which metadata should be retrieved depends on whether
13722: # the tool had been configured to be gradable (set in the Course
13723: # Editor or Resource Editor).
13724: #
13725: # If a valid symb has been included as the third arg in the call
13726: # to &metadata() that can be used to retrieve the value of
13727: # parameter_0_gradable set for the resource, and included in the
13728: # uploaded map containing the tool. The value is retrieved via
13729: # &EXT(), if a valid symb is available.  Otherwise the value of
13730: # gradable in the exttool_$marker.db file for the tool instance
13731: # is retrieved via &get().
13732: #
13733: # When lonuserstate::traceroute() calls lonnet::EXT() for 
13734: # hiddenresource and encrypturl (during course initialization)
13735: # the map-level parameter for resource.0.gradable included in the 
13736: # uploaded map containing the tool will not yet have been stored
13737: # in the user_course_parms.db file for the user's session, so in 
13738: # this case fall back to retrieving gradable status from the
13739: # exttool_$marker.db file.
13740: #
13741: # In order to avoid an infinite loop, &metadata() will return
13742: # before a call to &EXT(), if the uri is for an external tool
13743: # and the $what for which metadata is being requested is
13744: # parameter_0_gradable or 0_gradable.
13745: #
13746: 
13747:     if ($uri =~ /ext\.tool$/) {
13748:         if (($what eq 'parameter_0_gradable') || ($what eq '0_gradable')) {
13749:             return;
13750:         } else {
13751:             my ($checked,$use_passback);
13752:             if ($toolsymb ne '') {
13753:                 (undef,undef,my $tooluri) = &decode_symb($toolsymb);
13754:                 if (($tooluri eq $uri) && (&EXT('resource.0.gradable',$toolsymb))) {
13755:                     $checked = 1;
13756:                     if (&EXT('resource.0.gradable',$toolsymb) =~ /^yes$/i) {
13757:                         $use_passback = 1;
13758:                     }
13759:                 }
13760:             }
13761:             unless ($checked) {
13762:                 my ($ignore,$cdom,$cnum,$marker) = split(m{/},$uri);
13763:                 $marker=~s/\D//g;
13764:                 if ($marker) {
13765:                     my %toolsettings=&get('exttool_'.$marker,['gradable'],$cdom,$cnum);
13766:                     $use_passback = $toolsettings{'gradable'};
13767:                 }
13768:             }
13769:             if ($use_passback) {
13770:                 $filename = '/home/httpd/html/res/lib/templates/LTIpassback.tool';
13771:             } else {
13772:                 $filename = '/home/httpd/html/res/lib/templates/LTIstandard.tool';
13773:             }
13774:         }
13775:     }
13776: 
13777:     {
13778: # Imported parts would go here
13779:         my @origfiletagids=();
13780:         my $importedparts=0;
13781: 
13782: # Imported responseids would go here
13783:         my $importedresponses=0;
13784: #
13785: # Is this a recursive call for a library?
13786: #
13787: #	if (! exists($metacache{$uri})) {
13788: #	    $metacache{$uri}={};
13789: #	}
13790: 	my $cachetime = 60*60;
13791:         if ($liburi) {
13792: 	    $liburi=&declutter($liburi);
13793:             $filename=$liburi;
13794:         } else {
13795: 	    &devalidate_cache_new('meta',$uri);
13796: 	    undef(%metaentry);
13797: 	}
13798:         my %metathesekeys=();
13799:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
13800: 	my $metastring;
13801: 	if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
13802: 	    my $which = &hreflocation('','/'.($liburi || $uri));
13803: 	    $metastring = 
13804: 		&Apache::lonnet::ssi_body($which,
13805: 					  ('grade_target' => 'meta'));
13806: 	    $cachetime = 1; # only want this cached in the child not long term
13807: 	} elsif (($uri !~ m -^(editupload)/-) && 
13808:                  ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
13809: 	    my $file=&filelocation('',&clutter($filename));
13810: 	    #push(@{$metaentry{$uri.'.file'}},$file);
13811: 	    $metastring=&getfile($file);
13812: 	}
13813:         my $parser=HTML::LCParser->new(\$metastring);
13814:         my $token;
13815:         undef %metathesekeys;
13816:         while ($token=$parser->get_token) {
13817: 	    if ($token->[0] eq 'S') {
13818: 		if (defined($token->[2]->{'package'})) {
13819: #
13820: # This is a package - get package info
13821: #
13822: 		    my $package=$token->[2]->{'package'};
13823: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
13824: 		    if (defined($token->[2]->{'id'})) { 
13825: 			$keyroot.='_'.$token->[2]->{'id'}; 
13826: 		    }
13827: 		    if ($metaentry{':packages'}) {
13828: 			$metaentry{':packages'}.=','.$package.$keyroot;
13829: 		    } else {
13830: 			$metaentry{':packages'}=$package.$keyroot;
13831: 		    }
13832: 		    foreach my $pack_entry (keys(%packagetab)) {
13833: 			my $part=$keyroot;
13834: 			$part=~s/^\_//;
13835: 			if ($pack_entry=~/^\Q$package\E\&/ || 
13836: 			    $pack_entry=~/^\Q$package\E_0\&/) {
13837: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
13838: 			    # ignore package.tab specified default values
13839:                             # here &package_tab_default() will fetch those
13840: 			    if ($subp eq 'default') { next; }
13841: 			    my $value=$packagetab{$pack_entry};
13842: 			    my $unikey;
13843: 			    if ($pack =~ /_0$/) {
13844: 				$unikey='parameter_0_'.$name;
13845: 				$part=0;
13846: 			    } else {
13847: 				$unikey='parameter'.$keyroot.'_'.$name;
13848: 			    }
13849: 			    if ($subp eq 'display') {
13850: 				$value.=' [Part: '.$part.']';
13851: 			    }
13852: 			    $metaentry{':'.$unikey.'.part'}=$part;
13853: 			    $metathesekeys{$unikey}=1;
13854: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
13855: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
13856: 			    }
13857: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
13858: 				$metaentry{':'.$unikey}=
13859: 				    $metaentry{':'.$unikey.'.default'};
13860: 			    }
13861: 			}
13862: 		    }
13863: 		} else {
13864: #
13865: # This is not a package - some other kind of start tag
13866: #
13867: 		    my $entry=$token->[1];
13868: 		    my $unikey='';
13869: 
13870: 		    if ($entry eq 'import') {
13871: #
13872: # Importing a library here
13873: #
13874:                         my $location=$parser->get_text('/import');
13875:                         my $dir=$filename;
13876:                         $dir=~s|[^/]*$||;
13877:                         $location=&filelocation($dir,$location);
13878: 
13879:                         my $importid=$token->[2]->{'id'};
13880:                         my $importmode=$token->[2]->{'importmode'};
13881: #
13882: # Check metadata for imported file to
13883: # see if it contained response items
13884: #
13885:                         my ($origfile,@libfilekeys);
13886:                         my %currmetaentry = %metaentry;
13887:                         @libfilekeys = split(/,/,&metadata($location,'keys',undef,undef,undef,
13888:                                                            $depthcount+1));
13889:                         if (grep(/^responseorder$/,@libfilekeys)) {
13890:                             my $libresponseorder = &metadata($location,'responseorder',undef,undef,
13891:                                                              undef,$depthcount+1);
13892:                             if ($libresponseorder ne '') {
13893:                                 if ($#origfiletagids<0) {
13894:                                     undef(%importedrespids);
13895:                                     undef(%importedpartids);
13896:                                 }
13897:                                 my @respids = split(/\s*,\s*/,$libresponseorder);
13898:                                 if (@respids) {
13899:                                     $importedrespids{$importid} = join(',',map { $importid.'_'.$_ } @respids);
13900:                                 }
13901:                                 if ($importedrespids{$importid} ne '') {
13902:                                     $importedresponses = 1;
13903: # We need to get the original file and the imported file to get the response order correct
13904: # Load and inspect original file
13905:                                     if ($#origfiletagids<0) {
13906:                                         my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
13907:                                         $origfile=&getfile($origfilelocation);
13908:                                         @origfiletagids=($origfile=~/<((?:\w+)response|import|part)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
13909:                                     }
13910:                                 }
13911:                             }
13912:                         }
13913: # Do not overwrite contents of %metaentry hash for resource itself with 
13914: # hash populated for imported library file
13915:                         %metaentry = %currmetaentry;
13916:                         undef(%currmetaentry);
13917:                         if ($importmode eq 'part') {
13918: # Import as part(s)
13919:                            $importedparts=1;
13920: # We need to get the original file and the imported file to get the part order correct
13921: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
13922: # Load and inspect original file if we didn't do that already
13923:                            if ($#origfiletagids<0) {
13924:                                undef(%importedrespids);
13925:                                undef(%importedpartids);
13926:                                if ($origfile eq '') {
13927:                                    my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
13928:                                    $origfile=&getfile($origfilelocation);
13929:                                    @origfiletagids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
13930:                                }
13931:                            }
13932:                            my @impfilepartids;
13933: # If <partorder> tag is included in metadata for the imported file
13934: # get the parts in the imported file from that.
13935:                            if (grep(/^partorder$/,@libfilekeys)) {
13936:                                %currmetaentry = %metaentry;
13937:                                my $libpartorder = &metadata($location,'partorder',undef,undef,undef,
13938:                                                             $depthcount+1);
13939:                                %metaentry = %currmetaentry;
13940:                                undef(%currmetaentry);
13941:                                if ($libpartorder ne '') {
13942:                                    @impfilepartids=split(/\s*,\s*/,$libpartorder);
13943:                                }
13944:                            } else {
13945: # If no <partorder> tag available, load and inspect imported file
13946:                                my $impfile=&getfile($location);
13947:                                @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
13948:                            }
13949:                            if ($#impfilepartids>=0) {
13950: # This problem had parts
13951:                                $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
13952:                            } else {
13953: # Importing by turning a single problem into a problem part
13954: # It gets the import-tags ID as part-ID
13955:                                $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
13956:                                $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
13957:                            }
13958:                         } else {
13959: # Import as problem or as normal import
13960:                             $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
13961:                             unless ($importmode eq 'problem') {
13962: # Normal import
13963:                                 if (defined($token->[2]->{'id'})) {
13964:                                     $unikey.='_'.$token->[2]->{'id'};
13965:                                 }
13966:                             }
13967: # Check metadata for imported file to
13968: # see if it contained parts
13969:                             if (grep(/^partorder$/,@libfilekeys)) {
13970:                                 %currmetaentry = %metaentry;
13971:                                 my $libpartorder = &metadata($location,'partorder',undef,undef,undef,
13972:                                                              $depthcount+1);
13973:                                 %metaentry = %currmetaentry;
13974:                                 undef(%currmetaentry);
13975:                                 if ($libpartorder ne '') {
13976:                                     $importedparts = 1;
13977:                                     $importedpartids{$token->[2]->{'id'}}=$libpartorder;
13978:                                 }
13979:                             }
13980:                         }
13981: 			if ($depthcount<20) {
13982: 			    my $metadata = 
13983: 				&metadata($uri,'keys',$toolsymb,$location,$unikey,
13984: 					  $depthcount+1);
13985: 			    foreach my $meta (split(',',$metadata)) {
13986: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
13987: 				$metathesekeys{$meta}=1;
13988: 			    }
13989:                         }
13990: 		    } else {
13991: #
13992: # Not importing, some other kind of non-package, non-library start tag
13993: # 
13994:                         $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
13995:                         if (defined($token->[2]->{'id'})) {
13996:                             $unikey.='_'.$token->[2]->{'id'};
13997:                         }
13998: 			if (defined($token->[2]->{'name'})) { 
13999: 			    $unikey.='_'.$token->[2]->{'name'}; 
14000: 			}
14001: 			$metathesekeys{$unikey}=1;
14002: 			foreach my $param (@{$token->[3]}) {
14003: 			    $metaentry{':'.$unikey.'.'.$param} =
14004: 				$token->[2]->{$param};
14005: 			}
14006: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
14007: 			my $default=$metaentry{':'.$unikey.'.default'};
14008: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
14009: 		 # only ws inside the tag, and not in default, so use default
14010: 		 # as value
14011: 			    $metaentry{':'.$unikey}=$default;
14012: 			} elsif ( $internaltext =~ /\S/ ) {
14013: 		  # something interesting inside the tag
14014: 			    $metaentry{':'.$unikey}=$internaltext;
14015: 			} else {
14016: 		  # no interesting values, don't set a default
14017: 			}
14018: # end of not-a-package not-a-library import
14019: 		    }
14020: # end of not-a-package start tag
14021: 		}
14022: # the next is the end of "start tag"
14023: 	    }
14024: 	}
14025: 	my ($extension) = ($uri =~ /\.(\w+)$/);
14026: 	$extension = lc($extension);
14027: 	if ($extension eq 'htm') { $extension='html'; }
14028: 
14029: 	foreach my $key (keys(%packagetab)) {
14030: 	    #no specific packages #how's our extension
14031: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
14032: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
14033: 					 \%metathesekeys);
14034: 	}
14035: 
14036: 	if (!exists($metaentry{':packages'})
14037: 	    || $packagetab{"import_defaults&extension_$extension"}) {
14038: 	    foreach my $key (keys(%packagetab)) {
14039: 		#no specific packages well let's get default then
14040: 		if ($key!~/^default&/) { next; }
14041: 		&metadata_create_package_def($uri,$key,'default',
14042: 					     \%metathesekeys);
14043: 	    }
14044: 	}
14045: # are there custom rights to evaluate
14046: 	if ($metaentry{':copyright'} eq 'custom') {
14047: 
14048:     #
14049:     # Importing a rights file here
14050:     #
14051: 	    unless ($depthcount) {
14052: 		my $location=$metaentry{':customdistributionfile'};
14053: 		my $dir=$filename;
14054: 		$dir=~s|[^/]*$||;
14055: 		$location=&filelocation($dir,$location);
14056: 		my $rights_metadata =
14057: 		    &metadata($uri,'keys',$toolsymb,$location,'_rights',
14058: 			      $depthcount+1);
14059: 		foreach my $rights (split(',',$rights_metadata)) {
14060: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
14061: 		    $metathesekeys{$rights}=1;
14062: 		}
14063: 	    }
14064: 	}
14065: 	# uniqifiy package listing
14066: 	my %seen;
14067: 	my @uniq_packages =
14068: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
14069: 	$metaentry{':packages'} = join(',',@uniq_packages);
14070: 
14071:         if (($importedresponses) || ($importedparts)) {
14072:             if ($importedparts) {
14073: # We had imported parts and need to rebuild partorder
14074:                 $metaentry{':partorder'}='';
14075:                 $metathesekeys{'partorder'}=1;
14076:             }
14077:             if ($importedresponses) {
14078: # We had imported responses and need to rebuil responseorder
14079:                 $metaentry{':responseorder'}='';
14080:                 $metathesekeys{'responseorder'}=1;
14081:             }
14082:             for (my $index=0;$index<$#origfiletagids;$index+=2) {
14083:                 my $origid = $origfiletagids[$index+1];
14084:                 if ($origfiletagids[$index] eq 'part') {
14085: # Original part, part of the problem
14086:                     if ($importedparts) {
14087:                         $metaentry{':partorder'}.=','.$origid;
14088:                     }
14089:                 } elsif ($origfiletagids[$index] eq 'import') {
14090:                     if ($importedparts) {
14091: # We have imported parts at this position
14092:                         if ($importedpartids{$origid} ne '') {
14093:                             $metaentry{':partorder'}.=','.$importedpartids{$origid};
14094:                         }
14095:                     }
14096:                     if ($importedresponses) {
14097: # We have imported responses at this position
14098:                         if ($importedrespids{$origid} ne '') {
14099:                             $metaentry{':responseorder'}.=','.$importedrespids{$origid};
14100:                         }
14101:                     }
14102:                 } else {
14103: # Original response item, part of the problem
14104:                     if ($importedresponses) {
14105:                         $metaentry{':responseorder'}.=','.$origid;
14106:                     }
14107:                 }
14108:             }
14109:             if ($importedparts) {
14110:                 $metaentry{':partorder'}=~s/^\,//;
14111:             }
14112:             if ($importedresponses) {
14113:                 $metaentry{':responseorder'}=~s/^\,//;
14114:             }
14115:         }
14116: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
14117: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
14118: 	$metaentry{':allpossiblekeys'}=join(',',keys(%metathesekeys));
14119:         unless ($liburi) {
14120: 	    &do_cache_new('meta',$uri,\%metaentry,$cachetime);
14121:         }
14122: # this is the end of "was not already recently cached
14123:     }
14124:     return $metaentry{':'.$what};
14125: }
14126: 
14127: sub metadata_create_package_def {
14128:     my ($uri,$key,$package,$metathesekeys)=@_;
14129:     my ($pack,$name,$subp)=split(/\&/,$key);
14130:     if ($subp eq 'default') { next; }
14131:     
14132:     if (defined($metaentry{':packages'})) {
14133: 	$metaentry{':packages'}.=','.$package;
14134:     } else {
14135: 	$metaentry{':packages'}=$package;
14136:     }
14137:     my $value=$packagetab{$key};
14138:     my $unikey;
14139:     $unikey='parameter_0_'.$name;
14140:     $metaentry{':'.$unikey.'.part'}=0;
14141:     $$metathesekeys{$unikey}=1;
14142:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
14143: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
14144:     }
14145:     if (defined($metaentry{':'.$unikey.'.default'})) {
14146: 	$metaentry{':'.$unikey}=
14147: 	    $metaentry{':'.$unikey.'.default'};
14148:     }
14149: }
14150: 
14151: sub metadata_generate_part0 {
14152:     my ($metadata,$metacache,$uri) = @_;
14153:     my %allnames;
14154:     foreach my $metakey (keys(%$metadata)) {
14155: 	if ($metakey=~/^parameter\_(.*)/) {
14156: 	  my $part=$$metacache{':'.$metakey.'.part'};
14157: 	  my $name=$$metacache{':'.$metakey.'.name'};
14158: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
14159: 	    $allnames{$name}=$part;
14160: 	  }
14161: 	}
14162:     }
14163:     foreach my $name (keys(%allnames)) {
14164:       $$metadata{"parameter_0_$name"}=1;
14165:       my $key=":parameter_0_$name";
14166:       $$metacache{"$key.part"}='0';
14167:       $$metacache{"$key.name"}=$name;
14168:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
14169: 					   $allnames{$name}.'_'.$name.
14170: 					   '.type'};
14171:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
14172: 			     '.display'};
14173:       my $expr='[Part: '.$allnames{$name}.']';
14174:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
14175:       $$metacache{"$key.display"}=$olddis;
14176:     }
14177: }
14178: 
14179: # ------------------------------------------------------ Devalidate title cache
14180: 
14181: sub devalidate_title_cache {
14182:     my ($url)=@_;
14183:     if (!$env{'request.course.id'}) { return; }
14184:     my $symb=&symbread($url);
14185:     if (!$symb) { return; }
14186:     my $key=$env{'request.course.id'}."\0".$symb;
14187:     &devalidate_cache_new('title',$key);
14188: }
14189: 
14190: # ------------------------------------------------- Get the title of a course
14191: 
14192: sub current_course_title {
14193:     return $env{ 'course.' . $env{'request.course.id'} . '.description' };
14194: }
14195: # ------------------------------------------------- Get the title of a resource
14196: 
14197: sub gettitle {
14198:     my $urlsymb=shift;
14199:     my $symb=&symbread($urlsymb);
14200:     if ($symb) {
14201: 	my $key=$env{'request.course.id'}."\0".$symb;
14202: 	my ($result,$cached)=&is_cached_new('title',$key);
14203: 	if (defined($cached)) { 
14204: 	    return $result;
14205: 	}
14206: 	my ($map,$resid,$url)=&decode_symb($symb);
14207: 	my $title='';
14208: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
14209: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
14210: 	} else {
14211: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
14212: 		    &GDBM_READER(),0640)) {
14213: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
14214: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
14215: 		untie(%bighash);
14216: 	    }
14217: 	}
14218: 	$title=~s/\&colon\;/\:/gs;
14219: 	if ($title) {
14220: # Remember both $symb and $title for dynamic metadata
14221:             $accesshash{$symb.'___crstitle'}=$title;
14222:             $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
14223: # Cache this title and then return it
14224: 	    return &do_cache_new('title',$key,$title,600);
14225: 	}
14226: 	$urlsymb=$url;
14227:     }
14228:     my $title=&metadata($urlsymb,'title');
14229:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
14230:     return $title;
14231: }
14232: 
14233: sub get_slot {
14234:     my ($which,$cnum,$cdom)=@_;
14235:     if (!$cnum || !$cdom) {
14236: 	(undef,my $courseid)=&whichuser();
14237: 	$cdom=$env{'course.'.$courseid.'.domain'};
14238: 	$cnum=$env{'course.'.$courseid.'.num'};
14239:     }
14240:     my $key=join("\0",'slots',$cdom,$cnum,$which);
14241:     my %slotinfo;
14242:     if (exists($remembered{$key})) {
14243: 	$slotinfo{$which} = $remembered{$key};
14244:     } else {
14245: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
14246: 	&Apache::lonhomework::showhash(%slotinfo);
14247: 	my ($tmp)=keys(%slotinfo);
14248: 	if ($tmp=~/^error:/) { return (); }
14249: 	$remembered{$key} = $slotinfo{$which};
14250:     }
14251:     if (ref($slotinfo{$which}) eq 'HASH') {
14252: 	return %{$slotinfo{$which}};
14253:     }
14254:     return $slotinfo{$which};
14255: }
14256: 
14257: sub get_reservable_slots {
14258:     my ($cnum,$cdom,$uname,$udom) = @_;
14259:     my $now = time;
14260:     my $reservable_info;
14261:     my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
14262:     if (exists($remembered{$key})) {
14263:         $reservable_info = $remembered{$key};
14264:     } else {
14265:         my %resv;
14266:         ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
14267:         &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
14268:         $reservable_info = \%resv;
14269:         $remembered{$key} = $reservable_info;
14270:     }
14271:     return $reservable_info;
14272: }
14273: 
14274: sub get_course_slots {
14275:     my ($cnum,$cdom) = @_;
14276:     my $hashid=$cnum.':'.$cdom;
14277:     my ($result,$cached) = &is_cached_new('allslots',$hashid);
14278:     if (defined($cached)) {
14279:         if (ref($result) eq 'HASH') {
14280:             return %{$result};
14281:         }
14282:     } else {
14283:         my %slots=&dump('slots',$cdom,$cnum);
14284:         my ($tmp) = keys(%slots);
14285:         if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
14286:             &do_cache_new('allslots',$hashid,\%slots,600);
14287:             return %slots;
14288:         }
14289:     }
14290:     return;
14291: }
14292: 
14293: sub devalidate_slots_cache {
14294:     my ($cnum,$cdom)=@_;
14295:     my $hashid=$cnum.':'.$cdom;
14296:     &devalidate_cache_new('allslots',$hashid);
14297: }
14298: 
14299: sub get_coursechange {
14300:     my ($cdom,$cnum) = @_;
14301:     if ($cdom eq '' || $cnum eq '') {
14302:         return unless ($env{'request.course.id'});
14303:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
14304:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
14305:     }
14306:     my $hashid=$cdom.'_'.$cnum;
14307:     my ($change,$cached)=&is_cached_new('crschange',$hashid);
14308:     if ((defined($cached)) && ($change ne '')) {
14309:         return $change;
14310:     } else {
14311:         my %crshash;
14312:         %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
14313:         if ($crshash{'internal.contentchange'} eq '') {
14314:             $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
14315:             if ($change eq '') {
14316:                 %crshash = &get('environment',['internal.created'],$cdom,$cnum);
14317:                 $change = $crshash{'internal.created'};
14318:             }
14319:         } else {
14320:             $change = $crshash{'internal.contentchange'};
14321:         }
14322:         my $cachetime = 600;
14323:         &do_cache_new('crschange',$hashid,$change,$cachetime);
14324:     }
14325:     return $change;
14326: }
14327: 
14328: sub devalidate_coursechange_cache {
14329:     my ($cdom,$cnum)=@_;
14330:     my $hashid=$cdom.'_'.$cnum;
14331:     &devalidate_cache_new('crschange',$hashid);
14332: }
14333: 
14334: sub get_suppchange {
14335:     my ($cdom,$cnum) = @_;
14336:     if ($cdom eq '' || $cnum eq '') {
14337:         return unless ($env{'request.course.id'});
14338:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
14339:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
14340:     }
14341:     my $hashid=$cdom.'_'.$cnum;
14342:     my ($change,$cached)=&is_cached_new('suppchange',$hashid);
14343:     if ((defined($cached)) && ($change ne '')) {
14344:         return $change;
14345:     } else {
14346:         my %crshash = &get('environment',['internal.supplementalchange'],$cdom,$cnum);
14347:         if ($crshash{'internal.supplementalchange'} eq '') {
14348:             $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
14349:             if ($change eq '') {
14350:                 %crshash = &get('environment',['internal.created'],$cdom,$cnum);
14351:                 $change = $crshash{'internal.created'};
14352:             }
14353:         } else {
14354:             $change = $crshash{'internal.supplementalchange'};
14355:         }
14356:         my $cachetime = 600;
14357:         &do_cache_new('suppchange',$hashid,$change,$cachetime);
14358:     }
14359:     return $change;
14360: }
14361: 
14362: sub devalidate_suppchange_cache {
14363:     my ($cdom,$cnum)=@_;
14364:     my $hashid=$cdom.'_'.$cnum;
14365:     &devalidate_cache_new('suppchange',$hashid);
14366: }
14367: 
14368: sub update_supp_caches {
14369:     my ($cdom,$cnum) = @_;
14370:     my %servers = &internet_dom_servers($cdom);
14371:     my @ids=&current_machine_ids();
14372:     foreach my $server (keys(%servers)) {
14373:         next if (grep(/^\Q$server\E$/,@ids));
14374:         my $hashid=$cnum.':'.$cdom;
14375:         my $cachekey = &escape('showsupp').':'.&escape($hashid);
14376:         &remote_devalidate_cache($server,[$cachekey]);
14377:     }
14378:     &has_unhidden_suppfiles($cnum,$cdom,1,1);
14379:     &count_supptools($cnum,$cdom,1);
14380:     my $now = time;
14381:     if ($env{'request.course.id'} eq $cdom.'_'.$cnum) {
14382:         &Apache::lonnet::appenv({'request.course.suppupdated' => $now});
14383:     }
14384:     &put('environment',{'internal.supplementalchange' => $now},
14385:          $cdom,$cnum);
14386:     &Apache::lonnet::appenv(
14387:         {'course.'.$cdom.'_'.$cnum.'.internal.supplementalchange' => $now});
14388:     &do_cache_new('suppchange',$cdom.'_'.$cnum,$now,600);
14389: }
14390: 
14391: # ------------------------------------------------- Update symbolic store links
14392: 
14393: sub symblist {
14394:     my ($mapname,%newhash)=@_;
14395:     $mapname=&deversion(&declutter($mapname));
14396:     my %hash;
14397:     if (($env{'request.course.fn'}) && (%newhash)) {
14398:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
14399:                       &GDBM_WRCREAT(),0640)) {
14400: 	    foreach my $url (keys(%newhash)) {
14401: 		next if ($url eq 'last_known'
14402: 			 && $env{'form.no_update_last_known'});
14403: 		$hash{declutter($url)}=&encode_symb($mapname,
14404: 						    $newhash{$url}->[1],
14405: 						    $newhash{$url}->[0]);
14406:             }
14407:             if (untie(%hash)) {
14408: 		return 'ok';
14409:             }
14410:         }
14411:     }
14412:     return 'error';
14413: }
14414: 
14415: # --------------------------------------------------------------- Verify a symb
14416: 
14417: sub symbverify {
14418:     my ($symb,$thisurl,$encstate)=@_;
14419:     my $thisfn=$thisurl;
14420:     $thisfn=&declutter($thisfn);
14421: # direct jump to resource in page or to a sequence - will construct own symbs
14422:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
14423: # check URL part
14424:     my ($map,$resid,$url)=&decode_symb($symb);
14425: 
14426:     unless ($url eq $thisfn) { return 0; }
14427: 
14428:     $symb=&symbclean($symb);
14429:     $thisurl=&deversion($thisurl);
14430:     $thisfn=&deversion($thisfn);
14431: 
14432:     my %bighash;
14433:     my $okay=0;
14434: 
14435:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
14436:                             &GDBM_READER(),0640)) {
14437:         if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
14438:             $thisurl =~ s/\?.+$//;
14439:             if ($map =~ m{^uploaded/.+\.page$}) {
14440:                 $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
14441:                 $thisurl =~ s{^\Qhttp://https://\E}{https://};
14442:             }
14443:         }
14444:         my $ids;
14445:         if ($map =~ m{^uploaded/.+\.page$}) {
14446:             $ids=$bighash{'ids_'.&clutter_with_no_wrapper($thisurl)};
14447:         } else {
14448:             $ids=$bighash{'ids_'.&clutter($thisurl)};
14449:         }
14450:         unless ($ids) {
14451:             my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;  
14452:             $ids=$bighash{$idkey};
14453:         }
14454:         if ($ids) {
14455: # ------------------------------------------------------------------- Has ID(s)
14456:             if ($thisfn =~ m{^/adm/wrapper/ext/}) {
14457:                 $symb =~ s/\?.+$//;
14458:             }
14459: 	    foreach my $id (split(/\,/,$ids)) {
14460: 	       my ($mapid,$resid)=split(/\./,$id);
14461:                if (
14462:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
14463:    eq $symb) {
14464:                    if (ref($encstate)) {
14465:                        $$encstate = $bighash{'encrypted_'.$id};
14466:                    }
14467: 		   if (($env{'request.role.adv'}) ||
14468: 		       ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
14469:                        ($thisurl eq '/adm/navmaps')) {
14470: 		       $okay=1;
14471:                        last;
14472: 		   }
14473: 	       }
14474: 	   }
14475:         }
14476: 	untie(%bighash);
14477:     }
14478:     return $okay;
14479: }
14480: 
14481: # --------------------------------------------------------------- Clean-up symb
14482: 
14483: sub symbclean {
14484:     my $symb=shift;
14485:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
14486: # remove version from map
14487:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
14488: 
14489: # remove version from URL
14490:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
14491: 
14492: # remove wrapper
14493: 
14494:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
14495:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
14496:     return $symb;
14497: }
14498: 
14499: # ---------------------------------------------- Split symb to find map and url
14500: 
14501: sub encode_symb {
14502:     my ($map,$resid,$url)=@_;
14503:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
14504: }
14505: 
14506: sub decode_symb {
14507:     my $symb=shift;
14508:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
14509:     my ($map,$resid,$url)=split(/___/,$symb);
14510:     return (&fixversion($map),$resid,&fixversion($url));
14511: }
14512: 
14513: sub fixversion {
14514:     my $fn=shift;
14515:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
14516:     my %bighash;
14517:     my $uri=&clutter($fn);
14518:     my $key=$env{'request.course.id'}.'_'.$uri;
14519: # is this cached?
14520:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
14521:     if (defined($cached)) { return $result; }
14522: # unfortunately not cached, or expired
14523:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
14524: 	    &GDBM_READER(),0640)) {
14525:  	if ($bighash{'version_'.$uri}) {
14526:  	    my $version=$bighash{'version_'.$uri};
14527:  	    unless (($version eq 'mostrecent') || 
14528: 		    ($version==&getversion($uri))) {
14529:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
14530:  	    }
14531:  	}
14532:  	untie %bighash;
14533:     }
14534:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
14535: }
14536: 
14537: sub deversion {
14538:     my $url=shift;
14539:     $url=~s/\.\d+\.(\w+)$/\.$1/;
14540:     return $url;
14541: }
14542: 
14543: # ------------------------------------------------------ Return symb list entry
14544: 
14545: sub symbread {
14546:     my ($thisfn,$donotrecurse,$ignorecachednull,$checkforblock,$possibles,
14547:         $ignoresymbdb,$noenccheck)=@_;
14548:     my $cache_str='request.symbread.cached.'.$thisfn;
14549:     if (defined($env{$cache_str})) {
14550:         unless (ref($possibles) eq 'HASH') {
14551:             if ($ignorecachednull) {
14552:                 return $env{$cache_str} unless ($env{$cache_str} eq '');
14553:             } else {
14554:                 return $env{$cache_str};
14555:             }
14556:         }
14557:     }
14558: # no filename provided? try from environment
14559:     unless ($thisfn) {
14560:         if ($env{'request.symb'}) {
14561:             return $env{$cache_str}=&symbclean($env{'request.symb'});
14562: 	}
14563: 	$thisfn=$env{'request.filename'};
14564:     }
14565:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
14566: # is that filename actually a symb? Verify, clean, and return
14567:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
14568: 	if (&symbverify($thisfn,$1)) {
14569: 	    return $env{$cache_str}=&symbclean($thisfn);
14570: 	}
14571:     }
14572:     $thisfn=declutter($thisfn);
14573:     my %hash;
14574:     my %bighash;
14575:     my $syval='';
14576:     if (($env{'request.course.fn'}) && ($thisfn)) {
14577:         unless ($ignoresymbdb) {
14578:             if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
14579:                           &GDBM_READER(),0640)) {
14580: 	        $syval=$hash{$thisfn};
14581:                 untie(%hash);
14582:             }
14583:             if ($syval && $checkforblock) {
14584:                 my @blockers = &has_comm_blocking('bre',$syval,$thisfn,$ignoresymbdb,$noenccheck);
14585:                 if (@blockers) {
14586:                     $syval='';
14587:                 }
14588:             }
14589:         }
14590: # ---------------------------------------------------------- There was an entry
14591:         if ($syval) {
14592: 	    #unless ($syval=~/\_\d+$/) {
14593: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
14594: 		    #&appenv({'request.ambiguous' => $thisfn});
14595: 		    #return $env{$cache_str}='';
14596: 		#}    
14597: 		#$syval.=$1;
14598: 	    #}
14599:         } else {
14600: # ------------------------------------------------------- Was not in symb table
14601:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
14602:                             &GDBM_READER(),0640)) {
14603: # ---------------------------------------------- Get ID(s) for current resource
14604:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
14605:               unless ($ids) { 
14606:                  $ids=$bighash{'ids_/'.$thisfn};
14607:               }
14608:               unless ($ids) {
14609: # alias?
14610: 		  $ids=$bighash{'mapalias_'.$thisfn};
14611:               }
14612:               if ($ids) {
14613: # ------------------------------------------------------------------- Has ID(s)
14614:                  my @possibilities=split(/\,/,$ids);
14615:                  if ($#possibilities==0) {
14616: # ----------------------------------------------- There is only one possibility
14617: 		     my ($mapid,$resid)=split(/\./,$ids);
14618: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
14619: 						    $resid,$thisfn);
14620:                      if (ref($possibles) eq 'HASH') {
14621:                          unless ($bighash{'randomout_'.$ids} || $env{'request.role.adv'}) {
14622:                              $possibles->{$syval} = 1;
14623:                          }
14624:                      }
14625:                      if ($checkforblock) {
14626:                          unless ($bighash{'randomout_'.$ids} || $env{'request.role.adv'}) {
14627:                              my @blockers = &has_comm_blocking('bre',$syval,$bighash{'src_'.$ids},'',$noenccheck);
14628:                              if (@blockers) {
14629:                                  $syval = '';
14630:                                  untie(%bighash);
14631:                                  return $env{$cache_str}='';
14632:                              }
14633:                          }
14634:                      }
14635:                  } elsif ((!$donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) { 
14636: # ------------------------------------------ There is more than one possibility
14637:                      my $realpossible=0;
14638:                      foreach my $id (@possibilities) {
14639: 			 my $file=$bighash{'src_'.$id};
14640:                          my $canaccess;
14641:                          if (($donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
14642:                              $canaccess = 1;
14643:                          } else { 
14644:                              $canaccess = &allowed('bre',$file);
14645:                          }
14646:                          if ($canaccess) {
14647:          		     my ($mapid,$resid)=split(/\./,$id);
14648:                              if ($bighash{'map_type_'.$mapid} ne 'page') {
14649:                                  my $poss_syval=&encode_symb($bighash{'map_id_'.$mapid},
14650: 						             $resid,$thisfn);
14651:                                  next if ($bighash{'randomout_'.$id} && !$env{'request.role.adv'});
14652:                                  next unless (($noenccheck) || ($bighash{'encrypted_'.$id} eq $env{'request.enc'}));
14653:                                  if ($checkforblock) {
14654:                                      my @blockers = &has_comm_blocking('bre',$poss_syval,$file,'',$noenccheck);
14655:                                      if (@blockers > 0) {
14656:                                          $syval = '';
14657:                                      } else {
14658:                                          $syval = $poss_syval;
14659:                                          $realpossible++;
14660:                                      }
14661:                                  } else {
14662:                                      $syval = $poss_syval;
14663:                                      $realpossible++;
14664:                                  }
14665:                                  if ($syval) {
14666:                                      if (ref($possibles) eq 'HASH') {
14667:                                          $possibles->{$syval} = 1;
14668:                                      }
14669:                                  }
14670:                              }
14671: 			 }
14672:                      }
14673: 		     if ($realpossible!=1) { $syval=''; }
14674:                  } else {
14675:                      $syval='';
14676:                  }
14677: 	      }
14678:               untie(%bighash);
14679:            }
14680:         }
14681:         if ($syval) {
14682: 	    return $env{$cache_str}=$syval;
14683:         }
14684:     }
14685:     &appenv({'request.ambiguous' => $thisfn});
14686:     return $env{$cache_str}='';
14687: }
14688: 
14689: # ---------------------------------------------------------- Return random seed
14690: 
14691: sub numval {
14692:     my $txt=shift;
14693:     $txt=~tr/A-J/0-9/;
14694:     $txt=~tr/a-j/0-9/;
14695:     $txt=~tr/K-T/0-9/;
14696:     $txt=~tr/k-t/0-9/;
14697:     $txt=~tr/U-Z/0-5/;
14698:     $txt=~tr/u-z/0-5/;
14699:     $txt=~s/\D//g;
14700:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
14701:     return int($txt);
14702: }
14703: 
14704: sub numval2 {
14705:     my $txt=shift;
14706:     $txt=~tr/A-J/0-9/;
14707:     $txt=~tr/a-j/0-9/;
14708:     $txt=~tr/K-T/0-9/;
14709:     $txt=~tr/k-t/0-9/;
14710:     $txt=~tr/U-Z/0-5/;
14711:     $txt=~tr/u-z/0-5/;
14712:     $txt=~s/\D//g;
14713:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
14714:     my $total;
14715:     foreach my $val (@txts) { $total+=$val; }
14716:     if ($_64bit) { if ($total > 2**32) { return -1; } }
14717:     return int($total);
14718: }
14719: 
14720: sub numval3 {
14721:     use integer;
14722:     my $txt=shift;
14723:     $txt=~tr/A-J/0-9/;
14724:     $txt=~tr/a-j/0-9/;
14725:     $txt=~tr/K-T/0-9/;
14726:     $txt=~tr/k-t/0-9/;
14727:     $txt=~tr/U-Z/0-5/;
14728:     $txt=~tr/u-z/0-5/;
14729:     $txt=~s/\D//g;
14730:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
14731:     my $total;
14732:     foreach my $val (@txts) { $total+=$val; }
14733:     if ($_64bit) { $total=(($total<<32)>>32); }
14734:     return $total;
14735: }
14736: 
14737: sub digest {
14738:     my ($data)=@_;
14739:     my $digest=&Digest::MD5::md5($data);
14740:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
14741:     my ($e,$f);
14742:     {
14743:         use integer;
14744:         $e=($a+$b);
14745:         $f=($c+$d);
14746:         if ($_64bit) {
14747:             $e=(($e<<32)>>32);
14748:             $f=(($f<<32)>>32);
14749:         }
14750:     }
14751:     if (wantarray) {
14752: 	return ($e,$f);
14753:     } else {
14754: 	my $g;
14755: 	{
14756: 	    use integer;
14757: 	    $g=($e+$f);
14758: 	    if ($_64bit) {
14759: 		$g=(($g<<32)>>32);
14760: 	    }
14761: 	}
14762: 	return $g;
14763:     }
14764: }
14765: 
14766: sub latest_rnd_algorithm_id {
14767:     return '64bit5';
14768: }
14769: 
14770: sub get_rand_alg {
14771:     my ($courseid)=@_;
14772:     if (!$courseid) { $courseid=(&whichuser())[1]; }
14773:     if ($courseid) {
14774: 	return $env{"course.$courseid.rndseed"};
14775:     }
14776:     return &latest_rnd_algorithm_id();
14777: }
14778: 
14779: sub validCODE {
14780:     my ($CODE)=@_;
14781:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
14782:     return 0;
14783: }
14784: 
14785: sub getCODE {
14786:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
14787:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
14788: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
14789: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
14790: 	return $Apache::lonhomework::history{'resource.CODE'};
14791:     }
14792:     return undef;
14793: }
14794: #
14795: #  Determines the random seed for a specific context:
14796: #
14797: # parameters:
14798: #   symb      - in course context the symb for the seed.
14799: #   course_id - The course id of the form domain_coursenum.
14800: #   domain    - Domain for the user.
14801: #   course    - Course for the user.
14802: #   cenv      - environment of the course.
14803: #
14804: # NOTE:
14805: #   All parameters are picked out of the environment if missing
14806: #   or not defined.
14807: #   If a symb cannot be determined the current time is used instead.
14808: #
14809: #  For a given well defined symb, courside, domain, username,
14810: #  and course environment, the seed is reproducible.
14811: #
14812: sub rndseed {
14813:     my ($symb,$courseid,$domain,$username, $cenv)=@_;
14814:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
14815:     if (!defined($symb)) {
14816: 	unless ($symb=$wsymb) { return time; }
14817:     }
14818:     if (!defined $courseid) { 
14819: 	$courseid=$wcourseid; 
14820:     }
14821:     if (!defined $domain) { $domain=$wdomain; }
14822:     if (!defined $username) { $username=$wusername }
14823: 
14824:     my $which;
14825:     if (defined($cenv->{'rndseed'})) {
14826: 	$which = $cenv->{'rndseed'};
14827:     } else {
14828: 	$which =&get_rand_alg($courseid);
14829:     }
14830:     if (defined(&getCODE())) {
14831: 
14832: 	if ($which eq '64bit5') {
14833: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
14834: 	} elsif ($which eq '64bit4') {
14835: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
14836: 	} else {
14837: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
14838: 	}
14839:     } elsif ($which eq '64bit5') {
14840: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
14841:     } elsif ($which eq '64bit4') {
14842: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
14843:     } elsif ($which eq '64bit3') {
14844: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
14845:     } elsif ($which eq '64bit2') {
14846: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
14847:     } elsif ($which eq '64bit') {
14848: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
14849:     }
14850:     return &rndseed_32bit($symb,$courseid,$domain,$username);
14851: }
14852: 
14853: sub rndseed_32bit {
14854:     my ($symb,$courseid,$domain,$username)=@_;
14855:     {
14856: 	use integer;
14857: 	my $symbchck=unpack("%32C*",$symb) << 27;
14858: 	my $symbseed=numval($symb) << 22;
14859: 	my $namechck=unpack("%32C*",$username) << 17;
14860: 	my $nameseed=numval($username) << 12;
14861: 	my $domainseed=unpack("%32C*",$domain) << 7;
14862: 	my $courseseed=unpack("%32C*",$courseid);
14863: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
14864: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
14865: 	#&logthis("rndseed :$num:$symb");
14866: 	if ($_64bit) { $num=(($num<<32)>>32); }
14867: 	return $num;
14868:     }
14869: }
14870: 
14871: sub rndseed_64bit {
14872:     my ($symb,$courseid,$domain,$username)=@_;
14873:     {
14874: 	use integer;
14875: 	my $symbchck=unpack("%32S*",$symb) << 21;
14876: 	my $symbseed=numval($symb) << 10;
14877: 	my $namechck=unpack("%32S*",$username);
14878: 	
14879: 	my $nameseed=numval($username) << 21;
14880: 	my $domainseed=unpack("%32S*",$domain) << 10;
14881: 	my $courseseed=unpack("%32S*",$courseid);
14882: 	
14883: 	my $num1=$symbchck+$symbseed+$namechck;
14884: 	my $num2=$nameseed+$domainseed+$courseseed;
14885: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
14886: 	#&logthis("rndseed :$num:$symb");
14887: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
14888: 	return "$num1,$num2";
14889:     }
14890: }
14891: 
14892: sub rndseed_64bit2 {
14893:     my ($symb,$courseid,$domain,$username)=@_;
14894:     {
14895: 	use integer;
14896: 	# strings need to be an even # of cahracters long, it it is odd the
14897:         # last characters gets thrown away
14898: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
14899: 	my $symbseed=numval($symb) << 10;
14900: 	my $namechck=unpack("%32S*",$username.' ');
14901: 	
14902: 	my $nameseed=numval($username) << 21;
14903: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
14904: 	my $courseseed=unpack("%32S*",$courseid.' ');
14905: 	
14906: 	my $num1=$symbchck+$symbseed+$namechck;
14907: 	my $num2=$nameseed+$domainseed+$courseseed;
14908: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
14909: 	#&logthis("rndseed :$num:$symb");
14910: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
14911: 	return "$num1,$num2";
14912:     }
14913: }
14914: 
14915: sub rndseed_64bit3 {
14916:     my ($symb,$courseid,$domain,$username)=@_;
14917:     {
14918: 	use integer;
14919: 	# strings need to be an even # of cahracters long, it it is odd the
14920:         # last characters gets thrown away
14921: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
14922: 	my $symbseed=numval2($symb) << 10;
14923: 	my $namechck=unpack("%32S*",$username.' ');
14924: 	
14925: 	my $nameseed=numval2($username) << 21;
14926: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
14927: 	my $courseseed=unpack("%32S*",$courseid.' ');
14928: 	
14929: 	my $num1=$symbchck+$symbseed+$namechck;
14930: 	my $num2=$nameseed+$domainseed+$courseseed;
14931: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
14932: 	#&logthis("rndseed :$num1:$num2:$_64bit");
14933: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
14934: 	
14935: 	return "$num1:$num2";
14936:     }
14937: }
14938: 
14939: sub rndseed_64bit4 {
14940:     my ($symb,$courseid,$domain,$username)=@_;
14941:     {
14942: 	use integer;
14943: 	# strings need to be an even # of cahracters long, it it is odd the
14944:         # last characters gets thrown away
14945: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
14946: 	my $symbseed=numval3($symb) << 10;
14947: 	my $namechck=unpack("%32S*",$username.' ');
14948: 	
14949: 	my $nameseed=numval3($username) << 21;
14950: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
14951: 	my $courseseed=unpack("%32S*",$courseid.' ');
14952: 	
14953: 	my $num1=$symbchck+$symbseed+$namechck;
14954: 	my $num2=$nameseed+$domainseed+$courseseed;
14955: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
14956: 	#&logthis("rndseed :$num1:$num2:$_64bit");
14957: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
14958: 	
14959: 	return "$num1:$num2";
14960:     }
14961: }
14962: 
14963: sub rndseed_64bit5 {
14964:     my ($symb,$courseid,$domain,$username)=@_;
14965:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
14966:     return "$num1:$num2";
14967: }
14968: 
14969: sub rndseed_CODE_64bit {
14970:     my ($symb,$courseid,$domain,$username)=@_;
14971:     {
14972: 	use integer;
14973: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
14974: 	my $symbseed=numval2($symb);
14975: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
14976: 	my $CODEseed=numval(&getCODE());
14977: 	my $courseseed=unpack("%32S*",$courseid.' ');
14978: 	my $num1=$symbseed+$CODEchck;
14979: 	my $num2=$CODEseed+$courseseed+$symbchck;
14980: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
14981: 	#&logthis("rndseed :$num1:$num2:$symb");
14982: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
14983: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
14984: 	return "$num1:$num2";
14985:     }
14986: }
14987: 
14988: sub rndseed_CODE_64bit4 {
14989:     my ($symb,$courseid,$domain,$username)=@_;
14990:     {
14991: 	use integer;
14992: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
14993: 	my $symbseed=numval3($symb);
14994: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
14995: 	my $CODEseed=numval3(&getCODE());
14996: 	my $courseseed=unpack("%32S*",$courseid.' ');
14997: 	my $num1=$symbseed+$CODEchck;
14998: 	my $num2=$CODEseed+$courseseed+$symbchck;
14999: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
15000: 	#&logthis("rndseed :$num1:$num2:$symb");
15001: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
15002: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
15003: 	return "$num1:$num2";
15004:     }
15005: }
15006: 
15007: sub rndseed_CODE_64bit5 {
15008:     my ($symb,$courseid,$domain,$username)=@_;
15009:     my $code = &getCODE();
15010:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
15011:     return "$num1:$num2";
15012: }
15013: 
15014: sub setup_random_from_rndseed {
15015:     my ($rndseed)=@_;
15016:     if ($rndseed =~/([,:])/) {
15017:         my ($num1,$num2) = map { abs($_); } (split(/[,:]/,$rndseed));
15018:         if ((!$num1) || (!$num2) || ($num1 > 2147483562) || ($num2 > 2147483398)) {
15019:             &Math::Random::random_set_seed_from_phrase($rndseed);
15020:         } else {
15021:             &Math::Random::random_set_seed($num1,$num2);
15022:         }
15023:     } else {
15024: 	&Math::Random::random_set_seed_from_phrase($rndseed);
15025:     }
15026: }
15027: 
15028: sub latest_receipt_algorithm_id {
15029:     return 'receipt3';
15030: }
15031: 
15032: sub recunique {
15033:     my $fucourseid=shift;
15034:     my $unique;
15035:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
15036: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
15037: 	$unique=$env{"course.$fucourseid.internal.encseed"};
15038:     } else {
15039: 	$unique=$perlvar{'lonReceipt'};
15040:     }
15041:     return unpack("%32C*",$unique);
15042: }
15043: 
15044: sub recprefix {
15045:     my $fucourseid=shift;
15046:     my $prefix;
15047:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
15048: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
15049: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
15050:     } else {
15051: 	$prefix=$perlvar{'lonHostID'};
15052:     }
15053:     return unpack("%32C*",$prefix);
15054: }
15055: 
15056: sub ireceipt {
15057:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
15058: 
15059:     my $return =&recprefix($fucourseid).'-';
15060: 
15061:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
15062: 	$env{'request.state'} eq 'construct') {
15063: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
15064: 	return $return;
15065:     }
15066: 
15067:     my $cuname=unpack("%32C*",$funame);
15068:     my $cudom=unpack("%32C*",$fudom);
15069:     my $cucourseid=unpack("%32C*",$fucourseid);
15070:     my $cusymb=unpack("%32C*",$fusymb);
15071:     my $cunique=&recunique($fucourseid);
15072:     my $cpart=unpack("%32S*",$part);
15073:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
15074: 
15075: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
15076: 			       
15077: 	$return.= ($cunique%$cuname+
15078: 		   $cunique%$cudom+
15079: 		   $cusymb%$cuname+
15080: 		   $cusymb%$cudom+
15081: 		   $cucourseid%$cuname+
15082: 		   $cucourseid%$cudom+
15083: 		   $cpart%$cuname+
15084: 		   $cpart%$cudom);
15085:     } else {
15086: 	$return.= ($cunique%$cuname+
15087: 		   $cunique%$cudom+
15088: 		   $cusymb%$cuname+
15089: 		   $cusymb%$cudom+
15090: 		   $cucourseid%$cuname+
15091: 		   $cucourseid%$cudom);
15092:     }
15093:     return $return;
15094: }
15095: 
15096: sub receipt {
15097:     my ($part)=@_;
15098:     my ($symb,$courseid,$domain,$name) = &whichuser();
15099:     return &ireceipt($name,$domain,$courseid,$symb,$part);
15100: }
15101: 
15102: sub whichuser {
15103:     my ($passedsymb)=@_;
15104:     my ($symb,$courseid,$domain,$name,$publicuser);
15105:     if (defined($env{'form.grade_symb'})) {
15106: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
15107: 	my $allowed=&allowed('vgr',$tmp_courseid);
15108: 	if (!$allowed &&
15109: 	    exists($env{'request.course.sec'}) &&
15110: 	    $env{'request.course.sec'} !~ /^\s*$/) {
15111: 	    $allowed=&allowed('vgr',$tmp_courseid.
15112: 			      '/'.$env{'request.course.sec'});
15113: 	}
15114: 	if ($allowed) {
15115: 	    ($symb)=&get_env_multiple('form.grade_symb');
15116: 	    $courseid=$tmp_courseid;
15117: 	    ($domain)=&get_env_multiple('form.grade_domain');
15118: 	    ($name)=&get_env_multiple('form.grade_username');
15119:             if ($name eq 'public' && $domain eq 'public') {
15120:                 $publicuser = 1;
15121:             }
15122: 	    return ($symb,$courseid,$domain,$name,$publicuser);
15123: 	}
15124:     }
15125:     if (!$passedsymb) {
15126: 	$symb=&symbread();
15127:     } else {
15128: 	$symb=$passedsymb;
15129:     }
15130:     $courseid=$env{'request.course.id'};
15131:     $domain=$env{'user.domain'};
15132:     $name=$env{'user.name'};
15133:     if ($name eq 'public' && $domain eq 'public') {
15134: 	if (!defined($env{'form.username'})) {
15135: 	    $env{'form.username'}.=time.rand(10000000);
15136: 	}
15137: 	$name.=$env{'form.username'};
15138:         $publicuser = 1;
15139:     }
15140:     return ($symb,$courseid,$domain,$name,$publicuser);
15141: 
15142: }
15143: 
15144: # ------------------------------------------------------------ Serves up a file
15145: # returns either the contents of the file or 
15146: # -1 if the file doesn't exist
15147: #
15148: # if the target is a file that was uploaded via DOCS, 
15149: # a check will be made to see if a current copy exists on the local server,
15150: # if it does this will be served, otherwise a copy will be retrieved from
15151: # the home server for the course and stored in /home/httpd/html/userfiles on
15152: # the local server.   
15153: 
15154: sub getfile {
15155:     my ($file) = @_;
15156:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
15157:     &repcopy($file);
15158:     return &readfile($file);
15159: }
15160: 
15161: sub repcopy_userfile {
15162:     my ($file)=@_;
15163:     my $londocroot = $perlvar{'lonDocRoot'};
15164:     if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
15165:     if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
15166:     my ($cdom,$cnum,$filename) = 
15167: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
15168:     my $uri="/uploaded/$cdom/$cnum/$filename";
15169:     if (-e "$file") {
15170: # we already have a local copy, check it out
15171: 	my @fileinfo = stat($file);
15172: 	my $rtncode;
15173: 	my $info;
15174: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
15175: 	if ($lwpresp ne 'ok') {
15176: # there is no such file anymore, even though we had a local copy
15177: 	    if ($rtncode eq '404') {
15178: 		unlink($file);
15179: 	    }
15180: 	    return -1;
15181: 	}
15182: 	if ($info < $fileinfo[9]) {
15183: # nice, the file we have is up-to-date, just say okay
15184: 	    return 'ok';
15185: 	} else {
15186: # the file is outdated, get rid of it
15187: 	    unlink($file);
15188: 	}
15189:     }
15190: # one way or the other, at this point, we don't have the file
15191: # construct the correct path for the file
15192:     my @parts = ($cdom,$cnum); 
15193:     if ($filename =~ m|^(.+)/[^/]+$|) {
15194: 	push @parts, split(/\//,$1);
15195:     }
15196:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
15197:     foreach my $part (@parts) {
15198: 	$path .= '/'.$part;
15199: 	if (!-e $path) {
15200: 	    mkdir($path,0770);
15201: 	}
15202:     }
15203: # now the path exists for sure
15204: # get a user agent
15205:     my $transferfile=$file.'.in.transfer';
15206: # FIXME: this should flock
15207:     if (-e $transferfile) { return 'ok'; }
15208:     my $request;
15209:     $uri=~s/^\///;
15210:     my $homeserver = &homeserver($cnum,$cdom);
15211:     my $hostname = &hostname($homeserver);
15212:     my $protocol = $protocol{$homeserver};
15213:     $protocol = 'http' if ($protocol ne 'https');
15214:     $request=new HTTP::Request('GET',$protocol.'://'.$hostname.'/raw/'.$uri);
15215:     my $response = &LONCAPA::LWPReq::makerequest($homeserver,$request,$transferfile,\%perlvar,'',0,1);
15216: # did it work?
15217:     if ($response->is_error()) {
15218: 	unlink($transferfile);
15219: 	&logthis("Userfile repcopy failed for $uri");
15220: 	return -1;
15221:     }
15222: # worked, rename the transfer file
15223:     rename($transferfile,$file);
15224:     return 'ok';
15225: }
15226: 
15227: sub repcopy_crsprivfile {
15228:     my ($src,$dest) = @_;
15229:     my $result;
15230:     if ($src =~ m{^/priv/($match_domain)/($match_courseid)/(.+)$}) {
15231:         my ($cdom,$cnum,$filepath) = ($1,$2,$3);
15232:         $filepath =~ s/\.{2,}//g;
15233:         my $chome = &homeserver($cnum,$cdom);
15234:         unless ($chome eq 'no_host') {
15235:             my @ids=&current_machine_ids();
15236:             unless (grep(/^\Q$chome\E$/,@ids)) {
15237:                 if (&is_course($cdom,$cnum)) {
15238:                     my $londocroot = $perlvar{'lonDocRoot'};
15239:                     if ($dest =~ m{^\Q$londocroot/priv/\E$match_domain/$match_username/.*\Q$filepath\E$}) {
15240:                         my $cmd = 'crsfilefrompriv:'.&escape($filepath).':'.&escape($cnum).':'.&escape($cdom);
15241:                         $result = &reply($cmd,$chome);
15242:                         unless (($result eq 'unknown_cmd') || ($result =~ /^error:/)) {
15243:                             my $url = &unescape($result);
15244:                             if ($url =~ m{^https?://[^/]+\Q/userfiles/$cdom/$cnum/priv/$filepath\E$}) {
15245:                                 my $request=new HTTP::Request('GET',$url);
15246:                                 my $response=&LONCAPA::LWPReq::makerequest($chome,$request,'',\%perlvar,1200,1);
15247:                                 if ($response->is_error()) {
15248:                                     $result = 'error: '.$response->status_line;
15249:                                 } else {
15250:                                     if (open(my $fh,'>',$dest)) {
15251:                                         print $fh $response->content;
15252:                                         close($fh);
15253:                                         $result = 'ok';
15254:                                     } else {
15255:                                         $result = 'error: nowrite';
15256:                                     }
15257:                                 }
15258:                             } else {
15259:                                 $result = 'error: invalidurl';
15260:                             }
15261:                         }
15262:                     }
15263:                 }
15264:             }
15265:         }
15266:     }
15267:     return $result;
15268: }
15269: 
15270: sub tokenwrapper {
15271:     my $uri=shift;
15272:     $uri=~s|^https?\://([^/]+)||;
15273:     $uri=~s|^/||;
15274:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
15275:     my $token=$1;
15276:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
15277:     if ($udom && $uname && $file) {
15278: 	$file=~s|(\?\.*)*$||;
15279:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
15280:         my $homeserver = &homeserver($uname,$udom);
15281:         my $hostname = &hostname($homeserver);
15282:         my $protocol = $protocol{$homeserver};
15283:         $protocol = 'http' if ($protocol ne 'https');
15284:         return $protocol.'://'.$hostname.'/'.$uri.
15285:                (($uri=~/\?/)?'&':'?').'token='.$token.
15286:                                '&tokenissued='.$perlvar{'lonHostID'};
15287:     } else {
15288:         return '/adm/notfound.html';
15289:     }
15290: }
15291: 
15292: # call with reqtype HEAD: get last modification time
15293: # call with reqtype GET: get the file contents
15294: # Do not call this with reqtype GET for large files! It loads everything into memory
15295: #
15296: sub getuploaded {
15297:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
15298:     $uri=~s/^\///;
15299:     my $homeserver = &homeserver($cnum,$cdom);
15300:     my $hostname = &hostname($homeserver);
15301:     my $protocol = $protocol{$homeserver};
15302:     $protocol = 'http' if ($protocol ne 'https');
15303:     $uri = $protocol.'://'.$hostname.'/raw/'.$uri;
15304:     my $request=new HTTP::Request($reqtype,$uri);
15305:     my $response=&LONCAPA::LWPReq::makerequest($homeserver,$request,'',\%perlvar,'',0,1);
15306:     $$rtncode = $response->code;
15307:     if (! $response->is_success()) {
15308: 	return 'failed';
15309:     }      
15310:     if ($reqtype eq 'HEAD') {
15311: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
15312:     } elsif ($reqtype eq 'GET') {
15313: 	$$info = $response->content;
15314:     }
15315:     return 'ok';
15316: }
15317: 
15318: sub readfile {
15319:     my $file = shift;
15320:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
15321:     my $fh;
15322:     open($fh,"<",$file);
15323:     my $a='';
15324:     while (my $line = <$fh>) { $a .= $line; }
15325:     return $a;
15326: }
15327: 
15328: sub filelocation {
15329:     my ($dir,$file) = @_;
15330:     my $location;
15331:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
15332: 
15333:     if ($file =~ m-^/adm/-) {
15334: 	$file=~s-^/adm/wrapper/-/-;
15335: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
15336:     }
15337: 
15338:     if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
15339:         $location = $file;
15340:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
15341:         my ($udom,$uname,$filename)=
15342:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
15343:         my $home=&homeserver($uname,$udom);
15344:         my $is_me=0;
15345:         my @ids=&current_machine_ids();
15346:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
15347:         if ($is_me) {
15348:   	    $location=propath($udom,$uname).'/userfiles/'.$filename;
15349:         } else {
15350:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
15351:   	      $udom.'/'.$uname.'/'.$filename;
15352:         }
15353:     } elsif ($file =~ m-^/adm/-) {
15354: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
15355:     } else {
15356:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
15357:         $file=~s:^/(res|priv)/:/:;
15358:         my $space=$1;
15359:         if ( !( $file =~ m:^/:) ) {
15360:             $location = $dir. '/'.$file;
15361:         } else {
15362:             $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
15363:         }
15364:     }
15365:     $location=~s://+:/:g; # remove duplicate /
15366:     while ($location=~m{/\.\./}) {
15367: 	if ($location =~ m{/[^/]+/\.\./}) {
15368: 	    $location=~ s{/[^/]+/\.\./}{/}g;
15369: 	} else {
15370: 	    $location=~ s{/\.\./}{/}g;
15371: 	}
15372:     } #remove dir/..
15373:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
15374:     return $location;
15375: }
15376: 
15377: sub hreflocation {
15378:     my ($dir,$file)=@_;
15379:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
15380: 	$file=filelocation($dir,$file);
15381:     } elsif ($file=~m-^/adm/-) {
15382: 	$file=~s-^/adm/wrapper/-/-;
15383: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
15384:     }
15385:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
15386: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
15387:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
15388: 	$file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
15389: 	        {/uploaded/$1/$2/}x;
15390:     }
15391:     if ($file=~ m{^/userfiles/}) {
15392: 	$file =~ s{^/userfiles/}{/uploaded/};
15393:     }
15394:     return $file;
15395: }
15396: 
15397: 
15398: 
15399: 
15400: 
15401: sub current_machine_domains {
15402:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
15403: }
15404: 
15405: sub machine_domains {
15406:     my ($hostname) = @_;
15407:     my @domains;
15408:     my %hostname = &all_hostnames();
15409:     while( my($id, $name) = each(%hostname)) {
15410: #	&logthis("-$id-$name-$hostname-");
15411: 	if ($hostname eq $name) {
15412: 	    push(@domains,&host_domain($id));
15413: 	}
15414:     }
15415:     return @domains;
15416: }
15417: 
15418: sub current_machine_ids {
15419:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
15420: }
15421: 
15422: sub machine_ids {
15423:     my ($hostname) = @_;
15424:     $hostname ||= &hostname($perlvar{'lonHostID'});
15425:     my @ids;
15426:     my %name_to_host = &all_names();
15427:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
15428: 	return @{ $name_to_host{$hostname} };
15429:     }
15430:     return;
15431: }
15432: 
15433: sub additional_machine_domains {
15434:     my @domains;
15435:     if (-e "$perlvar{'lonTabDir'}/expected_domains.tab") {
15436:         if (open(my $fh,"<","$perlvar{'lonTabDir'}/expected_domains.tab")) {
15437:             while (my $line = <$fh>) {
15438:                 chomp($line);           
15439:                 $line =~ s/\s//g;
15440:                 push(@domains,$line);
15441:             }
15442:             close($fh);
15443:         }
15444:     }
15445:     return @domains;
15446: }
15447: 
15448: sub default_login_domain {
15449:     my $domain = $perlvar{'lonDefDomain'};
15450:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
15451:     foreach my $posdom (&current_machine_domains(),
15452:                         &additional_machine_domains()) {
15453:         if (lc($posdom) eq lc($testdomain)) {
15454:             $domain=$posdom;
15455:             last;
15456:         }
15457:     }
15458:     return $domain;
15459: }
15460: 
15461: sub shared_institution {
15462:     my ($dom,$lonhost) = @_;
15463:     if ($lonhost eq '') {
15464:         $lonhost = $perlvar{'lonHostID'};
15465:     }
15466:     my $same_intdom;
15467:     my $hostintdom = &internet_dom($lonhost);
15468:     if ($hostintdom ne '') {
15469:         my %iphost = &get_iphost();
15470:         my $primary_id = &domain($dom,'primary');
15471:         my $primary_ip = &get_host_ip($primary_id);
15472:         if (ref($iphost{$primary_ip}) eq 'ARRAY') {
15473:             foreach my $id (@{$iphost{$primary_ip}}) {
15474:                 my $intdom = &internet_dom($id);
15475:                 if ($intdom eq $hostintdom) {
15476:                     $same_intdom = 1;
15477:                     last;
15478:                 }
15479:             }
15480:         }
15481:     }
15482:     return $same_intdom;
15483: }
15484: 
15485: sub uses_sts {
15486:     my ($ignore_cache) = @_;
15487:     my $lonhost = $perlvar{'lonHostID'};
15488:     my $hostname = &hostname($lonhost);
15489:     my $sts_on;
15490:     if ($protocol{$lonhost} eq 'https') {
15491:         my $cachetime = 12*3600;
15492:         if (!$ignore_cache) {
15493:             ($sts_on,my $cached)=&is_cached_new('stspolicy',$lonhost);
15494:             if (defined($cached)) {
15495:                 return $sts_on;
15496:             }
15497:         }
15498:         my $url = $protocol{$lonhost}.'://'.$hostname.'/index.html';
15499:         my $request=new HTTP::Request('HEAD',$url);
15500:         my $response=&LONCAPA::LWPReq::makerequest($lonhost,$request,'',\%perlvar,'','','',1);
15501:         if ($response->is_success) {
15502:             my $has_sts = $response->header('Strict-Transport-Security');
15503:             if ($has_sts eq '') {
15504:                 $sts_on = 0;
15505:             } else {
15506:                 if ($has_sts =~ /\Qmax-age=\E(\d+)/) {
15507:                     my $maxage = $1;
15508:                     if ($maxage) {
15509:                         $sts_on = 1;
15510:                     } else {
15511:                         $sts_on = 0;
15512:                     }
15513:                 } else {
15514:                     $sts_on = 0;
15515:                 }
15516:             }
15517:             return &do_cache_new('stspolicy',$lonhost,$sts_on,$cachetime);
15518:         }
15519:     }
15520:     return;
15521: }
15522: 
15523: sub waf_allssl {
15524:     my ($host_name) = @_;
15525:     my $alias = &get_proxy_alias();
15526:     if ($host_name eq '') {
15527:         $host_name = $ENV{'SERVER_NAME'};
15528:     }
15529:     if (($host_name ne '') && ($alias eq $host_name)) {
15530:         my $serverhomedom = &host_domain($perlvar{'lonHostID'});
15531:         my %defdomdefaults = &get_domain_defaults($serverhomedom);
15532:         if ($defdomdefaults{'waf_sslopt'}) {
15533:             return $defdomdefaults{'waf_sslopt'};
15534:         }
15535:     }
15536:     return;
15537: }
15538: 
15539: sub get_requestor_ip {
15540:     my ($r,$nolookup,$noproxy) = @_;
15541:     my $from_ip;
15542:     if (ref($r)) {
15543:         if ($r->can('useragent_ip')) {
15544:             if ($noproxy && $r->can('client_ip')) {
15545:                 $from_ip = $r->client_ip();
15546:             } else {
15547:                 $from_ip = $r->useragent_ip();
15548:             }
15549:         } elsif ($r->connection->can('remote_ip')) {
15550:             $from_ip = $r->connection->remote_ip();
15551:         } else {
15552:             $from_ip = $r->get_remote_host($nolookup);
15553:         }
15554:     } else {
15555:         $from_ip = $ENV{'REMOTE_ADDR'};
15556:     }
15557:     return $from_ip if ($noproxy); 
15558:     # Who controls proxy settings for server
15559:     my $dom_in_use = $Apache::lonnet::perlvar{'lonDefDomain'};
15560:     my $proxyinfo = &get_proxy_settings($dom_in_use);
15561:     if ((ref($proxyinfo) eq 'HASH') && ($from_ip)) {
15562:         if ($proxyinfo->{'vpnint'}) {
15563:             if (&ip_match($from_ip,$proxyinfo->{'vpnint'})) {
15564:                 return $from_ip;
15565:             }
15566:         }
15567:         if ($proxyinfo->{'trusted'}) {
15568:             if (&ip_match($from_ip,$proxyinfo->{'trusted'})) {
15569:                 my $ipheader = $proxyinfo->{'ipheader'};
15570:                 my ($ip,$xfor);
15571:                 if (ref($r)) {
15572:                     if ($ipheader) {
15573:                         $ip = $r->headers_in->{$ipheader};
15574:                     }
15575:                     $xfor = $r->headers_in->{'X-Forwarded-For'};
15576:                 } else {
15577:                     if ($ipheader) {
15578:                         $ip = $ENV{'HTTP_'.uc($ipheader)};
15579:                     }
15580:                     $xfor = $ENV{'HTTP_X_FORWARDED_FOR'};
15581:                 }
15582:                 if (($ip eq '') && ($xfor ne '')) {
15583:                     foreach my $poss_ip (reverse(split(/\s*,\s*/,$xfor))) {
15584:                         unless (&ip_match($poss_ip,$proxyinfo->{'trusted'})) {
15585:                             $ip = $poss_ip;
15586:                             last;
15587:                         }
15588:                     }
15589:                 }
15590:                 if ($ip ne '') {
15591:                     return $ip;
15592:                 }
15593:             }
15594:         }
15595:     }
15596:     return $from_ip;
15597: }
15598: 
15599: sub get_proxy_settings {
15600:     my ($dom_in_use) = @_;
15601:     my %domdefaults = &get_domain_defaults($dom_in_use);
15602:     my $proxyinfo = {
15603:                        ipheader => $domdefaults{'waf_ipheader'},
15604:                        trusted  => $domdefaults{'waf_trusted'},
15605:                        vpnint   => $domdefaults{'waf_vpnint'},
15606:                        vpnext   => $domdefaults{'waf_vpnext'},
15607:                        sslopt   => $domdefaults{'waf_sslopt'},
15608:                     };
15609:     return $proxyinfo;
15610: }
15611: 
15612: sub ip_match {
15613:     my ($ip,$pattern_str) = @_;
15614:     $ip=Net::CIDR::cidrvalidate($ip);
15615:     if ($ip) {
15616:         return Net::CIDR::cidrlookup($ip,split(/\s*,\s*/,$pattern_str));
15617:     }
15618:     return;
15619: }
15620: 
15621: sub get_proxy_alias {
15622:     my ($lonid) = @_;
15623:     if ($lonid eq '') {
15624:         $lonid = $perlvar{'lonHostID'};
15625:     }
15626:     if (!defined(&hostname($lonid))) {
15627:         return;
15628:     }
15629:     if ($lonid ne '') {
15630:         my ($alias,$cached) = &is_cached_new('proxyalias',$lonid);
15631:         if ($cached) {
15632:             return $alias;
15633:         }
15634:         my $dom = &host_domain($lonid);
15635:         if ($dom ne '') {
15636:             my $cachetime = 60*60*24;
15637:             my %domconfig =
15638:                 &get_dom('configuration',['wafproxy'],$dom);
15639:             if (ref($domconfig{'wafproxy'}) eq 'HASH') {
15640:                 if (ref($domconfig{'wafproxy'}{'alias'}) eq 'HASH') {
15641:                     $alias = $domconfig{'wafproxy'}{'alias'}{$lonid};
15642:                 }
15643:             }
15644:             return &do_cache_new('proxyalias',$lonid,$alias,$cachetime);
15645:         }
15646:     }
15647:     return;
15648: }
15649: 
15650: sub use_proxy_alias {
15651:     my ($r,$lonid) = @_;
15652:     my $alias = &get_proxy_alias($lonid);
15653:     if ($alias) {
15654:         my $dom = &host_domain($lonid);
15655:         if ($dom ne '') {
15656:             my $proxyinfo = &get_proxy_settings($dom);
15657:             my ($vpnint,$remote_ip);
15658:             if (ref($proxyinfo) eq 'HASH') {
15659:                 $vpnint = $proxyinfo->{'vpnint'};
15660:                 if ($vpnint) {
15661:                     $remote_ip = &get_requestor_ip($r,1,1);
15662:                 }
15663:             }
15664:             unless ($vpnint && &ip_match($remote_ip,$vpnint)) {
15665:                 return $alias;
15666:             }
15667:         }
15668:     }
15669:     return;
15670: }
15671: 
15672: sub alias_sso {
15673:     my ($lonid) = @_;
15674:     if ($lonid eq '') {
15675:         $lonid = $perlvar{'lonHostID'};
15676:     }
15677:     if (!defined(&hostname($lonid))) {
15678:         return;
15679:     }
15680:     if ($lonid ne '') {
15681:         my ($use_alias,$cached) = &is_cached_new('proxysaml',$lonid);
15682:         if ($cached) {
15683:             return $use_alias;
15684:         }
15685:         my $dom = &host_domain($lonid);
15686:         if ($dom ne '') {
15687:             my $cachetime = 60*60*24;
15688:             my %domconfig =
15689:                 &get_dom('configuration',['wafproxy'],$dom);
15690:             if (ref($domconfig{'wafproxy'}) eq 'HASH') {
15691:                 if (ref($domconfig{'wafproxy'}{'saml'}) eq 'HASH') {
15692:                     $use_alias = $domconfig{'wafproxy'}{'saml'}{$lonid};
15693:                 }
15694:             }
15695:             return &do_cache_new('proxysaml',$lonid,$use_alias,$cachetime);
15696:         }
15697:     }
15698:     return;
15699: }
15700: 
15701: sub get_saml_landing {
15702:     my ($lonid) = @_;
15703:     if ($lonid eq '') {
15704:         my $defdom = &default_login_domain();
15705:         my @hosts = &current_machine_ids();
15706:         if (@hosts > 1) {
15707:             foreach my $hostid (@hosts) {
15708:                 if (&host_domain($hostid) eq $defdom) {
15709:                     $lonid = $hostid;
15710:                     last;
15711:                 }
15712:             }
15713:         } else {
15714:             $lonid = $perlvar{'lonHostID'};
15715:         }
15716:         if ($lonid) {
15717:             unless (&host_domain($lonid) eq $defdom) {
15718:                 return;
15719:             }
15720:         } else {
15721:             return;
15722:         }
15723:     } elsif (!defined(&hostname($lonid))) {
15724:         return;
15725:     }
15726:     my ($landing,$cached) = &is_cached_new('samllanding',$lonid);
15727:     if ($cached) {
15728:         return $landing;
15729:     }
15730:     my $dom = &host_domain($lonid);
15731:     if ($dom ne '') {
15732:         my $cachetime = 60*60*24;
15733:         my %domconfig =
15734:             &get_dom('configuration',['login'],$dom);
15735:         if (ref($domconfig{'login'}) eq 'HASH') {
15736:             if (ref($domconfig{'login'}{'saml'}) eq 'HASH') {
15737:                 if (ref($domconfig{'login'}{'saml'}{$lonid}) eq 'HASH') {
15738:                     $landing = 1;
15739:                 }
15740:             }
15741:         }
15742:         return &do_cache_new('samllanding',$lonid,$landing,$cachetime);
15743:     }
15744:     return;
15745: }
15746: 
15747: # ------------------------------------------------------------- Declutters URLs
15748: 
15749: sub declutter {
15750:     my $thisfn=shift;
15751:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
15752:     unless ($thisfn=~m{^/home/httpd/html/priv/}) {
15753:         $thisfn=~s{^/home/httpd/html}{};
15754:     }
15755:     $thisfn=~s/^\///;
15756:     $thisfn=~s|^adm/wrapper/||;
15757:     $thisfn=~s|^adm/coursedocs/showdoc/||;
15758:     $thisfn=~s/^res\///;
15759:     $thisfn=~s/^priv\///;
15760:     unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
15761:         $thisfn=~s/\?.+$//;
15762:     }
15763:     return $thisfn;
15764: }
15765: 
15766: # ------------------------------------------------------------- Clutter up URLs
15767: 
15768: sub clutter {
15769:     my $thisfn='/'.&declutter(shift);
15770:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
15771: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
15772:        $thisfn='/res'.$thisfn; 
15773:     }
15774:     if ($thisfn !~m|^/adm|) {
15775: 	if ($thisfn =~ m|^/ext/|) {
15776: 	    $thisfn='/adm/wrapper'.$thisfn;
15777: 	} else {
15778: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
15779: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
15780: 	    if ($embstyle eq 'ssi'
15781: 		|| ($embstyle eq 'hdn')
15782: 		|| ($embstyle eq 'rat')
15783: 		|| ($embstyle eq 'prv')
15784: 		|| ($embstyle eq 'ign')) {
15785: 		#do nothing with these
15786: 	    } elsif (($embstyle eq 'img') 
15787: 		|| ($embstyle eq 'emb')
15788: 		|| ($embstyle eq 'wrp')) {
15789: 		$thisfn='/adm/wrapper'.$thisfn;
15790: 	    } elsif ($embstyle eq 'unk'
15791: 		     && $thisfn!~/\.(sequence|page)$/) {
15792: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
15793: 	    } else {
15794: #		&logthis("Got a blank emb style");
15795: 	    }
15796: 	}
15797:     } elsif ($thisfn =~ m{^/adm/$match_domain/$match_courseid/\d+/ext\.tool$}) {
15798:         $thisfn='/adm/wrapper'.$thisfn;
15799:     }
15800:     return $thisfn;
15801: }
15802: 
15803: sub clutter_with_no_wrapper {
15804:     my $uri = &clutter(shift);
15805:     if ($uri =~ m-^/adm/-) {
15806: 	$uri =~ s-^/adm/wrapper/-/-;
15807: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
15808:     }
15809:     return $uri;
15810: }
15811: 
15812: sub freeze_escape {
15813:     my ($value)=@_;
15814:     if (ref($value)) {
15815: 	$value=&nfreeze($value);
15816: 	return '__FROZEN__'.&escape($value);
15817:     }
15818:     return &escape($value);
15819: }
15820: 
15821: 
15822: sub thaw_unescape {
15823:     my ($value)=@_;
15824:     if ($value =~ /^__FROZEN__/) {
15825: 	substr($value,0,10,undef);
15826: 	$value=&unescape($value);
15827: 	return &thaw($value);
15828:     }
15829:     return &unescape($value);
15830: }
15831: 
15832: sub correct_line_ends {
15833:     my ($result)=@_;
15834:     $$result =~s/\r\n/\n/mg;
15835:     $$result =~s/\r/\n/mg;
15836: }
15837: # ================================================================ Main Program
15838: 
15839: sub goodbye {
15840:    &logthis("Starting Shut down");
15841: #not converted to using infrastruture and probably shouldn't be
15842:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
15843: #converted
15844: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
15845:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
15846: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
15847: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
15848: #1.1 only
15849: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
15850: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
15851: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
15852: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
15853:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
15854:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
15855:    &logthis(sprintf("%-20s is %s",'hits',$hits));
15856:    &flushcourselogs();
15857:    &logthis("Shutting down");
15858: }
15859: 
15860: sub get_dns {
15861:     my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
15862:     if (!$ignore_cache) {
15863: 	my ($content,$cached)=
15864: 	    &is_cached_new('dns',$url);
15865: 	if ($cached) {
15866: 	    &$func($content,$hashref);
15867: 	    return;
15868: 	}
15869:     }
15870: 
15871:     my %alldns;
15872:     if (open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab")) {
15873:         foreach my $dns (<$config>) {
15874: 	    next if ($dns !~ /^\^(\S*)/x);
15875:             my $line = $1;
15876:             my ($host,$protocol) = split(/:/,$line);
15877:             if ($protocol ne 'https') {
15878:                 $protocol = 'http';
15879:             }
15880: 	    $alldns{$host} = $protocol;
15881:         }
15882:         close($config);
15883:     }
15884:     while (%alldns) {
15885: 	my ($dns) = sort { $b cmp $a } keys(%alldns);
15886:         my ($contents,@content);
15887:         if ($dns eq Sys::Hostname::FQDN::fqdn()) {
15888:             my $command = (split('/',$url))[3];
15889:             my ($dir,$file) = &parse_getdns_url($command,$url);
15890:             delete($alldns{$dns});
15891:             next if (($dir eq '') || ($file eq ''));
15892:             if (open(my $config,'<',"$dir/$file")) {
15893:                 @content = <$config>;
15894:                 close($config);
15895:             }
15896:             if ($url eq '/adm/dns/loncapaCRL') {
15897:                 $contents = join('',@content);
15898:             }
15899:         } else {
15900: 	    my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
15901:             my $response = &LONCAPA::LWPReq::makerequest('',$request,'',\%perlvar,30,0);
15902:             delete($alldns{$dns});
15903: 	    next if ($response->is_error());
15904:             if ($url eq '/adm/dns/loncapaCRL') {
15905:                 $contents = $response->content;
15906:             } else {
15907:                 @content = split("\n",$response->content);
15908:             }
15909:         }
15910:         if ($url eq '/adm/dns/loncapaCRL') {
15911:             return &$func($contents);
15912:         } else {
15913: 	    unless ($nocache) {
15914: 	        &do_cache_new('dns',$url,\@content,30*24*60*60);
15915: 	    }
15916: 	    &$func(\@content,$hashref);
15917:             return;
15918:         }
15919:     }
15920:     my $which = (split('/',$url,4))[3];
15921:     if ($which eq 'loncapaCRL') {
15922:         my $diskfile = "$perlvar{'lonCertificateDirectory'}/$perlvar{'lonnetCertRevocationList'}";
15923:         if (-e $diskfile) {
15924:             &logthis("unable to contact DNS, on disk file $diskfile not updated");
15925:         } else {
15926:             &logthis("unable to contact DNS, no on disk file $diskfile available");
15927:         }
15928:     } else {
15929:         &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
15930:         if (open(my $config,"<","$perlvar{'lonTabDir'}/dns_$which.tab")) {
15931:             my @content = <$config>;
15932:             close($config);
15933:             &$func(\@content,$hashref);
15934:         }
15935:     }
15936:     return;
15937: }
15938: 
15939: # ------------------------------------------------------Get DNS checksums file
15940: sub parse_dns_checksums_tab {
15941:     my ($lines,$hashref) = @_;
15942:     my $lonhost = $perlvar{'lonHostID'};
15943:     my $machine_dom = &host_domain($lonhost);
15944:     my $loncaparev = &get_server_loncaparev($machine_dom);
15945:     my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
15946:     my $webconfdir = '/etc/httpd/conf';
15947:     if ($distro =~ /^(ubuntu|debian)(\d+)$/) {
15948:         $webconfdir = '/etc/apache2';
15949:     } elsif ($distro =~ /^sles(\d+)$/) {
15950:         if ($1 >= 10) {
15951:             $webconfdir = '/etc/apache2';
15952:         }
15953:     } elsif ($distro =~ /^suse(\d+\.\d+)$/) {
15954:         if ($1 >= 10.0) {
15955:             $webconfdir = '/etc/apache2';
15956:         }
15957:     }
15958:     my ($release,$timestamp) = split(/\-/,$loncaparev);
15959:     my (%chksum,%revnum);
15960:     if (ref($lines) eq 'ARRAY') {
15961:         chomp(@{$lines});
15962:         my $version = shift(@{$lines});
15963:         if ($version eq $release) {  
15964:             foreach my $line (@{$lines}) {
15965:                 my ($file,$version,$shasum) = split(/,/,$line);
15966:                 if ($file =~ m{^/etc/httpd/conf}) {
15967:                     if ($webconfdir eq '/etc/apache2') {
15968:                         $file =~ s{^\Q/etc/httpd/conf/\E}{$webconfdir/};
15969:                     }
15970:                 }
15971:                 $chksum{$file} = $shasum;
15972:                 $revnum{$file} = $version;
15973:             }
15974:             if (ref($hashref) eq 'HASH') {
15975:                 %{$hashref} = (
15976:                                 sums     => \%chksum,
15977:                                 versions => \%revnum,
15978:                               );
15979:             }
15980:         }
15981:     }
15982:     return;
15983: }
15984: 
15985: sub fetch_dns_checksums {
15986:     my %checksums;
15987:     my $machine_dom = &host_domain($perlvar{'lonHostID'});
15988:     my $loncaparev = &get_server_loncaparev($machine_dom,$perlvar{'lonHostID'});
15989:     my ($release,$timestamp) = split(/\-/,$loncaparev);
15990:     &get_dns("/adm/dns/checksums/$release",\&parse_dns_checksums_tab,1,1,
15991:              \%checksums);
15992:     return \%checksums;
15993: }
15994: 
15995: sub fetch_crl_pemfile {
15996:     return &get_dns("/adm/dns/loncapaCRL",\&save_crl_pem,1,1);
15997: }
15998: 
15999: sub save_crl_pem {
16000:     my ($content) = @_;
16001:     my ($msg,$hadchanges);
16002:     if ($content ne '') {
16003:         my $now = time;
16004:         my $lonca = $perlvar{'lonCertificateDirectory'}.'/'.$perlvar{'lonnetCertificateAuthority'};
16005:         my $tmpcrl = $tmpdir.'/'.$perlvar{'lonnetCertRevocationList'}.'_'.$now.'.'.$$.'.tmp';
16006:         if (open(my $fh,'>',"$tmpcrl")) {
16007:             print $fh $content;
16008:             close($fh);
16009:             if (-e $lonca) {
16010:                 if (open(PIPE,"openssl crl -in $tmpcrl -inform pem -CAfile $lonca -noout 2>&1 |")) {
16011:                     my $check = <PIPE>;
16012:                     close(PIPE);
16013:                     chomp($check);
16014:                     if ($check eq 'verify OK') {
16015:                         my $dest = "$perlvar{'lonCertificateDirectory'}/$perlvar{'lonnetCertRevocationList'}";
16016:                         my $backup;
16017:                         if (-e $dest) {
16018:                             if (&File::Copy::move($dest,"$dest.bak")) {
16019:                                 $backup = 'ok';
16020:                             }
16021:                         }
16022:                         if (&File::Copy::move($tmpcrl,$dest)) {
16023:                             $msg = 'ok';
16024:                             if ($backup) {
16025:                                 my (%oldnums,%newnums);
16026:                                 if (open(PIPE, "openssl crl -inform PEM -text -noout -in $dest.bak |grep 'Serial Number' |")) {
16027:                                     while (<PIPE>) {
16028:                                         $oldnums{(split(/:/))[1]} = 1;
16029:                                     }
16030:                                     close(PIPE);
16031:                                 }
16032:                                 if (open(PIPE, "openssl crl -inform PEM -text -noout -in $dest |grep 'Serial Number' |")) {
16033:                                     while(<PIPE>) {
16034:                                         $newnums{(split(/:/))[1]} = 1;
16035:                                     }
16036:                                     close(PIPE);
16037:                                 }
16038:                                 foreach my $key (sort {$b <=> $a } (keys(%newnums))) {
16039:                                     unless (exists($oldnums{$key})) {
16040:                                         $hadchanges = 1;
16041:                                         last;
16042:                                     }
16043:                                 }
16044:                                 unless ($hadchanges) {
16045:                                     foreach my $key (sort {$b <=> $a } (keys(%oldnums))) {
16046:                                         unless (exists($newnums{$key})) {
16047:                                             $hadchanges = 1;
16048:                                             last;
16049:                                         }
16050:                                     }
16051:                                 }
16052:                             }
16053:                         }
16054:                     } else {
16055:                         unlink($tmpcrl);
16056:                     }
16057:                 } else {
16058:                     unlink($tmpcrl);
16059:                 }
16060:             } else {
16061:                 unlink($tmpcrl);
16062:             }
16063:         }
16064:     }
16065:     return ($msg,$hadchanges);
16066: }
16067: 
16068: sub parse_getdns_url {
16069:     my ($command,$url) = @_;
16070:     my $dir = $perlvar{'lonTabDir'};
16071:     my $file;
16072:     if ($command eq 'hosts') {
16073:         $file = 'dns_hosts.tab';
16074:     } elsif ($command eq 'domain') {
16075:         $file = 'dns_domain.tab';
16076:     } elsif ($command eq 'checksums') {
16077:         my $version = (split('/',$url))[4];
16078:         $file = "dns_checksums/$version.tab",
16079:     } elsif ($command eq 'loncapaCRL') {
16080:         $dir = $perlvar{'lonCertificateDirectory'};
16081:         $file = $perlvar{'lonnetCertRevocationList'};
16082:     }
16083:     return ($dir,$file);
16084: }
16085: 
16086: # ------------------------------------------------------------ Read domain file
16087: {
16088:     my $loaded;
16089:     my %domain;
16090: 
16091:     sub parse_domain_tab {
16092: 	my ($lines) = @_;
16093: 	foreach my $line (@$lines) {
16094: 	    next if ($line =~ /^(\#|\s*$ )/x);
16095: 
16096: 	    chomp($line);
16097: 	    my ($name,@elements) = split(/:/,$line,9);
16098: 	    my %this_domain;
16099: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
16100: 			       'lang_def', 'city', 'longi', 'lati',
16101: 			       'primary') {
16102: 		$this_domain{$field} = shift(@elements);
16103: 	    }
16104: 	    $domain{$name} = \%this_domain;
16105: 	}
16106:     }
16107: 
16108:     sub reset_domain_info {
16109: 	undef($loaded);
16110: 	undef(%domain);
16111:     }
16112: 
16113:     sub load_domain_tab {
16114: 	my ($ignore_cache,$nocache) = @_;
16115: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache,$nocache);
16116: 	my $fh;
16117: 	if (open($fh,"<",$perlvar{'lonTabDir'}.'/domain.tab')) {
16118: 	    my @lines = <$fh>;
16119: 	    &parse_domain_tab(\@lines);
16120: 	}
16121: 	close($fh);
16122: 	$loaded = 1;
16123:     }
16124: 
16125:     sub domain {
16126: 	&load_domain_tab() if (!$loaded);
16127: 
16128: 	my ($name,$what) = @_;
16129: 	return if ( !exists($domain{$name}) );
16130: 
16131: 	if (!$what) {
16132: 	    return $domain{$name}{'description'};
16133: 	}
16134: 	return $domain{$name}{$what};
16135:     }
16136: 
16137:     sub domain_info {
16138:         &load_domain_tab() if (!$loaded);
16139:         return %domain;
16140:     }
16141: 
16142: }
16143: 
16144: 
16145: # ------------------------------------------------------------- Read hosts file
16146: {
16147:     my %hostname;
16148:     my %hostdom;
16149:     my %libserv;
16150:     my $loaded;
16151:     my %name_to_host;
16152:     my %internetdom;
16153:     my %LC_dns_serv;
16154: 
16155:     sub parse_hosts_tab {
16156: 	my ($file) = @_;
16157: 	foreach my $configline (@$file) {
16158: 	    next if ($configline =~ /^(\#|\s*$ )/x);
16159:             chomp($configline);
16160: 	    if ($configline =~ /^\^/) {
16161:                 if ($configline =~ /^\^([\w.\-]+)/) {
16162:                     $LC_dns_serv{$1} = 1;
16163:                 }
16164:                 next;
16165:             }
16166: 	    my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
16167: 	    $name=~s/\s//g;
16168: 	    if ($id && $domain && $role && $name) {
16169:                 if ((exists($hostname{$id})) && ($hostname{$id} ne '')) {
16170:                     my $curr = $hostname{$id};
16171:                     my $skip;
16172:                     if (ref($name_to_host{$curr}) eq 'ARRAY') {
16173:                         if (($curr eq $name) && (@{$name_to_host{$curr}} == 1)) {
16174:                             $skip = 1;
16175:                         } else {
16176:                             @{$name_to_host{$curr}} = grep { $_ ne $id } @{$name_to_host{$curr}};
16177:                         }
16178:                     }
16179:                     unless ($skip) {
16180:                         push(@{$name_to_host{$name}},$id);
16181:                     }
16182:                 } else {
16183:                     push(@{$name_to_host{$name}},$id);
16184:                 }
16185: 		$hostname{$id}=$name;
16186: 		$hostdom{$id}=$domain;
16187: 		if ($role eq 'library') { $libserv{$id}=$name; }
16188:                 if (defined($protocol)) {
16189:                     if ($protocol eq 'https') {
16190:                         $protocol{$id} = $protocol;
16191:                     } else {
16192:                         $protocol{$id} = 'http'; 
16193:                     }
16194:                 } else {
16195:                     $protocol{$id} = 'http';
16196:                 }
16197:                 if (defined($intdom)) {
16198:                     $internetdom{$id} = $intdom;
16199:                 }
16200: 	    }
16201: 	}
16202:     }
16203:     
16204:     sub reset_hosts_info {
16205: 	&purge_remembered();
16206: 	&reset_domain_info();
16207: 	&reset_hosts_ip_info();
16208:         undef(%internetdom);
16209: 	undef(%name_to_host);
16210: 	undef(%hostname);
16211: 	undef(%hostdom);
16212: 	undef(%libserv);
16213: 	undef($loaded);
16214:     }
16215: 
16216:     sub load_hosts_tab {
16217: 	my ($ignore_cache,$nocache) = @_;
16218: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache,$nocache);
16219: 	open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab");
16220: 	my @config = <$config>;
16221: 	&parse_hosts_tab(\@config);
16222: 	close($config);
16223: 	$loaded=1;
16224:     }
16225: 
16226:     sub hostname {
16227: 	&load_hosts_tab() if (!$loaded);
16228: 
16229: 	my ($lonid) = @_;
16230: 	return $hostname{$lonid};
16231:     }
16232: 
16233:     sub all_hostnames {
16234: 	&load_hosts_tab() if (!$loaded);
16235: 
16236: 	return %hostname;
16237:     }
16238: 
16239:     sub all_names {
16240:         my ($ignore_cache,$nocache) = @_;
16241: 	&load_hosts_tab($ignore_cache,$nocache) if (!$loaded);
16242: 
16243: 	return %name_to_host;
16244:     }
16245: 
16246:     sub all_host_domain {
16247:         &load_hosts_tab() if (!$loaded);
16248:         return %hostdom;
16249:     }
16250: 
16251:     sub all_host_intdom {
16252:         &load_hosts_tab() if (!$loaded);
16253:         return %internetdom;
16254:     }
16255: 
16256:     sub is_library {
16257: 	&load_hosts_tab() if (!$loaded);
16258: 
16259: 	return exists($libserv{$_[0]});
16260:     }
16261: 
16262:     sub all_library {
16263: 	&load_hosts_tab() if (!$loaded);
16264: 
16265: 	return %libserv;
16266:     }
16267: 
16268:     sub unique_library {
16269: 	#2x reverse removes all hostnames that appear more than once
16270:         my %unique = reverse &all_library();
16271:         return reverse %unique;
16272:     }
16273: 
16274:     sub get_servers {
16275: 	&load_hosts_tab() if (!$loaded);
16276: 
16277: 	my ($domain,$type) = @_;
16278: 	my %possible_hosts = ($type eq 'library') ? %libserv
16279: 	                                          : %hostname;
16280: 	my %result;
16281: 	if (ref($domain) eq 'ARRAY') {
16282: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
16283: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
16284: 		    $result{$host} = $hostname;
16285: 		}
16286: 	    }
16287: 	} else {
16288: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
16289: 		if ($hostdom{$host} eq $domain) {
16290: 		    $result{$host} = $hostname;
16291: 		}
16292: 	    }
16293: 	}
16294: 	return %result;
16295:     }
16296: 
16297:     sub get_unique_servers {
16298:         my %unique = reverse &get_servers(@_);
16299: 	return reverse %unique;
16300:     }
16301: 
16302:     sub host_domain {
16303: 	&load_hosts_tab() if (!$loaded);
16304: 
16305: 	my ($lonid) = @_;
16306: 	return $hostdom{$lonid};
16307:     }
16308: 
16309:     sub all_domains {
16310: 	&load_hosts_tab() if (!$loaded);
16311: 
16312: 	my %seen;
16313: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
16314: 	return @uniq;
16315:     }
16316: 
16317:     sub internet_dom {
16318:         &load_hosts_tab() if (!$loaded);
16319: 
16320:         my ($lonid) = @_;
16321:         return $internetdom{$lonid};
16322:     }
16323: 
16324:     sub is_LC_dns {
16325:         &load_hosts_tab() if (!$loaded);
16326: 
16327:         my ($hostname) = @_;
16328:         return exists($LC_dns_serv{$hostname});
16329:     }
16330: 
16331: }
16332: 
16333: { 
16334:     my %iphost;
16335:     my %name_to_ip;
16336:     my %lonid_to_ip;
16337: 
16338:     sub get_hosts_from_ip {
16339: 	my ($ip) = @_;
16340: 	my %iphosts = &get_iphost();
16341: 	if (ref($iphosts{$ip})) {
16342: 	    return @{$iphosts{$ip}};
16343: 	}
16344: 	return;
16345:     }
16346:     
16347:     sub reset_hosts_ip_info {
16348: 	undef(%iphost);
16349: 	undef(%name_to_ip);
16350: 	undef(%lonid_to_ip);
16351:     }
16352: 
16353:     sub get_host_ip {
16354: 	my ($lonid) = @_;
16355: 	if (exists($lonid_to_ip{$lonid})) {
16356: 	    return $lonid_to_ip{$lonid};
16357: 	}
16358: 	my $name=&hostname($lonid);
16359:    	my $ip = gethostbyname($name);
16360: 	return if (!$ip || length($ip) ne 4);
16361: 	$ip=inet_ntoa($ip);
16362: 	$name_to_ip{$name}   = $ip;
16363: 	$lonid_to_ip{$lonid} = $ip;
16364: 	return $ip;
16365:     }
16366:     
16367:     sub get_iphost {
16368: 	my ($ignore_cache,$nocache) = @_;
16369: 
16370: 	if (!$ignore_cache) {
16371: 	    if (%iphost) {
16372: 		return %iphost;
16373: 	    }
16374: 	    my ($ip_info,$cached)=
16375: 		&is_cached_new('iphost','iphost');
16376: 	    if ($cached) {
16377: 		%iphost      = %{$ip_info->[0]};
16378: 		%name_to_ip  = %{$ip_info->[1]};
16379: 		%lonid_to_ip = %{$ip_info->[2]};
16380: 		return %iphost;
16381: 	    }
16382: 	}
16383: 
16384: 	# get yesterday's info for fallback
16385: 	my %old_name_to_ip;
16386: 	my ($ip_info,$cached)=
16387: 	    &is_cached_new('iphost','iphost');
16388: 	if ($cached) {
16389: 	    %old_name_to_ip = %{$ip_info->[1]};
16390: 	}
16391: 
16392: 	my %name_to_host = &all_names($ignore_cache,$nocache);
16393: 	foreach my $name (keys(%name_to_host)) {
16394: 	    my $ip;
16395: 	    if (!exists($name_to_ip{$name})) {
16396: 		$ip = gethostbyname($name);
16397: 		if (!$ip || length($ip) ne 4) {
16398: 		    if (defined($old_name_to_ip{$name})) {
16399: 			$ip = $old_name_to_ip{$name};
16400: 			&logthis("Can't find $name defaulting to old $ip");
16401: 		    } else {
16402: 			&logthis("Name $name no IP found");
16403: 			next;
16404: 		    }
16405: 		} else {
16406: 		    $ip=inet_ntoa($ip);
16407: 		}
16408: 		$name_to_ip{$name} = $ip;
16409: 	    } else {
16410: 		$ip = $name_to_ip{$name};
16411: 	    }
16412: 	    foreach my $id (@{ $name_to_host{$name} }) {
16413: 		$lonid_to_ip{$id} = $ip;
16414: 	    }
16415: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
16416: 	}
16417:         unless ($nocache) {
16418: 	    &do_cache_new('iphost','iphost',
16419: 		          [\%iphost,\%name_to_ip,\%lonid_to_ip],
16420: 		          48*60*60);
16421:         }
16422: 
16423: 	return %iphost;
16424:     }
16425: 
16426:     #
16427:     #  Given a DNS returns the loncapa host name for that DNS 
16428:     # 
16429:     sub host_from_dns {
16430:         my ($dns) = @_;
16431:         my @hosts;
16432:         my $ip;
16433: 
16434:         if (exists($name_to_ip{$dns})) {
16435:             $ip = $name_to_ip{$dns};
16436:         }
16437:         if (!$ip) {
16438:             $ip = gethostbyname($dns); # Initial translation to IP is in net order.
16439:             if (length($ip) == 4) { 
16440: 	        $ip   = &IO::Socket::inet_ntoa($ip);
16441:             }
16442:         }
16443:         if ($ip) {
16444: 	    @hosts = get_hosts_from_ip($ip);
16445: 	    return $hosts[0];
16446:         }
16447:         return undef;
16448:     }
16449: 
16450:     sub get_internet_names {
16451:         my ($lonid) = @_;
16452:         return if ($lonid eq '');
16453:         my ($idnref,$cached)=
16454:             &is_cached_new('internetnames',$lonid);
16455:         if ($cached) {
16456:             return $idnref;
16457:         }
16458:         my $ip = &get_host_ip($lonid);
16459:         my @hosts = &get_hosts_from_ip($ip);
16460:         my %iphost = &get_iphost();
16461:         my (@idns,%seen);
16462:         foreach my $id (@hosts) {
16463:             my $dom = &host_domain($id);
16464:             my $prim_id = &domain($dom,'primary');
16465:             my $prim_ip = &get_host_ip($prim_id);
16466:             next if ($seen{$prim_ip});
16467:             if (ref($iphost{$prim_ip}) eq 'ARRAY') {
16468:                 foreach my $id (@{$iphost{$prim_ip}}) {
16469:                     my $intdom = &internet_dom($id);
16470:                     unless (grep(/^\Q$intdom\E$/,@idns)) {
16471:                         push(@idns,$intdom);
16472:                     }
16473:                 }
16474:             }
16475:             $seen{$prim_ip} = 1;
16476:         }
16477:         return &do_cache_new('internetnames',$lonid,\@idns,12*60*60);
16478:     }
16479: 
16480: }
16481: 
16482: sub all_loncaparevs {
16483:     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);
16484: }
16485: 
16486: # ---------------------------------------------------------- Read loncaparev table
16487: {
16488:     sub load_loncaparevs { 
16489:         if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
16490:             if (open(my $config,"<","$perlvar{'lonTabDir'}/loncaparevs.tab")) {
16491:                 while (my $configline=<$config>) {
16492:                     chomp($configline);
16493:                     my ($hostid,$loncaparev)=split(/:/,$configline);
16494:                     $loncaparevs{$hostid}=$loncaparev;
16495:                 }
16496:                 close($config);
16497:             }
16498:         }
16499:     }
16500: }
16501: 
16502: # ---------------------------------------------------------- Read serverhostID table
16503: {
16504:     sub load_serverhomeIDs {
16505:         if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
16506:             if (open(my $config,"<","$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
16507:                 while (my $configline=<$config>) {
16508:                     chomp($configline);
16509:                     my ($name,$id)=split(/:/,$configline);
16510:                     $serverhomeIDs{$name}=$id;
16511:                 }
16512:                 close($config);
16513:             }
16514:         }
16515:     }
16516: }
16517: 
16518: 
16519: BEGIN {
16520: 
16521: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
16522:     unless ($readit) {
16523: {
16524:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
16525:     %perlvar = (%perlvar,%{$configvars});
16526: }
16527: 
16528: 
16529: # ------------------------------------------------------ Read spare server file
16530: {
16531:     open(my $config,"<","$perlvar{'lonTabDir'}/spare.tab");
16532: 
16533:     while (my $configline=<$config>) {
16534:        chomp($configline);
16535:        if ($configline) {
16536: 	   my ($host,$type) = split(':',$configline,2);
16537: 	   if (!defined($type) || $type eq '') { $type = 'default' };
16538: 	   push(@{ $spareid{$type} }, $host);
16539:        }
16540:     }
16541:     close($config);
16542: }
16543: # ------------------------------------------------------------ Read permissions
16544: {
16545:     open(my $config,"<","$perlvar{'lonTabDir'}/roles.tab");
16546: 
16547:     while (my $configline=<$config>) {
16548: 	chomp($configline);
16549: 	if ($configline) {
16550: 	    my ($role,$perm)=split(/ /,$configline);
16551: 	    if ($perm ne '') { $pr{$role}=$perm; }
16552: 	}
16553:     }
16554:     close($config);
16555: }
16556: 
16557: # -------------------------------------------- Read plain texts for permissions
16558: {
16559:     open(my $config,"<","$perlvar{'lonTabDir'}/rolesplain.tab");
16560: 
16561:     while (my $configline=<$config>) {
16562: 	chomp($configline);
16563: 	if ($configline) {
16564: 	    my ($short,@plain)=split(/:/,$configline);
16565:             %{$prp{$short}} = ();
16566: 	    if (@plain > 0) {
16567:                 $prp{$short}{'std'} = $plain[0];
16568:                 for (my $i=1; $i<@plain; $i++) {
16569:                     $prp{$short}{'alt'.$i} = $plain[$i];  
16570:                 }
16571:             }
16572: 	}
16573:     }
16574:     close($config);
16575: }
16576: 
16577: # ---------------------------------------------------------- Read package table
16578: {
16579:     open(my $config,"<","$perlvar{'lonTabDir'}/packages.tab");
16580: 
16581:     while (my $configline=<$config>) {
16582: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
16583: 	chomp($configline);
16584: 	my ($short,$plain)=split(/:/,$configline);
16585: 	my ($pack,$name)=split(/\&/,$short);
16586: 	if ($plain ne '') {
16587: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
16588: 	    $packagetab{$short}=$plain; 
16589: 	}
16590:     }
16591:     close($config);
16592: }
16593: 
16594: # ---------------------------------------------------------- Read loncaparev table
16595: 
16596: &load_loncaparevs();
16597: 
16598: # ---------------------------------------------------------- Read serverhostID table
16599: 
16600: &load_serverhomeIDs();
16601: 
16602: # ---------------------------------------------------------- Read releaseslist XML
16603: {
16604:     my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
16605:     if (-e $file) {
16606:         my $parser = HTML::LCParser->new($file);
16607:         while (my $token = $parser->get_token()) {
16608:             if ($token->[0] eq 'S') {
16609:                 my $item = $token->[1];
16610:                 my $name = $token->[2]{'name'};
16611:                 my $value = $token->[2]{'value'};
16612:                 my $valuematch = $token->[2]{'valuematch'};
16613:                 my $namematch = $token->[2]{'namematch'};
16614:                 if ($item eq 'parameter') {
16615:                     if (($namematch ne '') || (($name ne '') && ($value ne '' || $valuematch ne ''))) {
16616:                         my $release = $parser->get_text();
16617:                         $release =~ s/(^\s*|\s*$ )//gx;
16618:                         $needsrelease{$item.':'.$name.':'.$value.':'.$valuematch.':'.$namematch} = $release;
16619:                     }
16620:                 } elsif ($item ne '' && $name ne '') {
16621:                     my $release = $parser->get_text();
16622:                     $release =~ s/(^\s*|\s*$ )//gx;
16623:                     $needsrelease{$item.':'.$name.':'.$value} = $release;
16624:                 }
16625:             }
16626:         }
16627:     }
16628: }
16629: 
16630: # ---------------------------------------------------------- Read managers table
16631: {
16632:     if (-e "$perlvar{'lonTabDir'}/managers.tab") {
16633:         if (open(my $config,"<","$perlvar{'lonTabDir'}/managers.tab")) {
16634:             while (my $configline=<$config>) {
16635:                 chomp($configline);
16636:                 next if ($configline =~ /^\#/);
16637:                 if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
16638:                     $managerstab{$configline} = 1;
16639:                 }
16640:             }
16641:             close($config);
16642:         }
16643:     }
16644: }
16645: 
16646: # ------------- set up temporary directory
16647: {
16648:     $tmpdir = LONCAPA::tempdir();
16649: 
16650: }
16651: 
16652: # ------------- set default texengine (domain default overrides this)
16653: {
16654:     $deftex = LONCAPA::texengine();
16655: }
16656: 
16657: # ------------- set default minimum length for passwords for internal auth users
16658: {
16659:     $passwdmin = LONCAPA::passwd_min();
16660: }
16661: 
16662: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
16663: 				'compress_threshold'=> 20_000,
16664:  			        });
16665: 
16666: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
16667: $dumpcount=0;
16668: $locknum=0;
16669: 
16670: &logtouch();
16671: &logthis('<font color="yellow">INFO: Read configuration</font>');
16672: $readit=1;
16673:     {
16674: 	use integer;
16675: 	my $test=(2**32)+1;
16676: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
16677: 	&logthis(" Detected 64bit platform ($_64bit)");
16678:     }
16679: }
16680: }
16681: 
16682: 1;
16683: __END__
16684: 
16685: =pod
16686: 
16687: =head1 NAME
16688: 
16689: Apache::lonnet - Subroutines to ask questions about things in the network.
16690: 
16691: =head1 SYNOPSIS
16692: 
16693: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
16694: 
16695:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
16696: 
16697: Common parameters:
16698: 
16699: =over 4
16700: 
16701: =item *
16702: 
16703: $uname : an internal username (if $cname expecting a course Id specifically)
16704: 
16705: =item *
16706: 
16707: $udom : a domain (if $cdom expecting a course's domain specifically)
16708: 
16709: =item *
16710: 
16711: $symb : a resource instance identifier
16712: 
16713: =item *
16714: 
16715: $namespace : the name of a .db file that contains the data needed or
16716: being set.
16717: 
16718: =back
16719: 
16720: =head1 OVERVIEW
16721: 
16722: lonnet provides subroutines which interact with the
16723: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
16724: about classes, users, and resources.
16725: 
16726: For many of these objects you can also use this to store data about
16727: them or modify them in various ways.
16728: 
16729: =head2 Symbs
16730: 
16731: To identify a specific instance of a resource, LON-CAPA uses symbols
16732: or "symbs"X<symb>. These identifiers are built from the URL of the
16733: map, the resource number of the resource in the map, and the URL of
16734: the resource itself. The latter is somewhat redundant, but might help
16735: if maps change.
16736: 
16737: An example is
16738: 
16739:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
16740: 
16741: The respective map entry is
16742: 
16743:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
16744:   title="Problem 2">
16745:  </resource>
16746: 
16747: Symbs are used by the random number generator, as well as to store and
16748: restore data specific to a certain instance of for example a problem.
16749: 
16750: =head2 Storing And Retrieving Data
16751: 
16752: X<store()>X<cstore()>X<restore()>Three of the most important functions
16753: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
16754: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
16755: is is the non-critical message twin of cstore. These functions are for
16756: handlers to store a perl hash to a user's permanent data space in an
16757: easy manner, and to retrieve it again on another call. It is expected
16758: that a handler would use this once at the beginning to retrieve data,
16759: and then again once at the end to send only the new data back.
16760: 
16761: The data is stored in the user's data directory on the user's
16762: homeserver under the ID of the course.
16763: 
16764: The hash that is returned by restore will have all of the previous
16765: value for all of the elements of the hash.
16766: 
16767: Example:
16768: 
16769:  #creating a hash
16770:  my %hash;
16771:  $hash{'foo'}='bar';
16772: 
16773:  #storing it
16774:  &Apache::lonnet::cstore(\%hash);
16775: 
16776:  #changing a value
16777:  $hash{'foo'}='notbar';
16778: 
16779:  #adding a new value
16780:  $hash{'bar'}='foo';
16781:  &Apache::lonnet::cstore(\%hash);
16782: 
16783:  #retrieving the hash
16784:  my %history=&Apache::lonnet::restore();
16785: 
16786:  #print the hash
16787:  foreach my $key (sort(keys(%history))) {
16788:    print("\%history{$key} = $history{$key}");
16789:  }
16790: 
16791: Will print out:
16792: 
16793:  %history{1:foo} = bar
16794:  %history{1:keys} = foo:timestamp
16795:  %history{1:timestamp} = 990455579
16796:  %history{2:bar} = foo
16797:  %history{2:foo} = notbar
16798:  %history{2:keys} = foo:bar:timestamp
16799:  %history{2:timestamp} = 990455580
16800:  %history{bar} = foo
16801:  %history{foo} = notbar
16802:  %history{timestamp} = 990455580
16803:  %history{version} = 2
16804: 
16805: Note that the special hash entries C<keys>, C<version> and
16806: C<timestamp> were added to the hash. C<version> will be equal to the
16807: total number of versions of the data that have been stored. The
16808: C<timestamp> attribute will be the UNIX time the hash was
16809: stored. C<keys> is available in every historical section to list which
16810: keys were added or changed at a specific historical revision of a
16811: hash.
16812: 
16813: B<Warning>: do not store the hash that restore returns directly. This
16814: will cause a mess since it will restore the historical keys as if the
16815: were new keys. I.E. 1:foo will become 1:1:foo etc.
16816: 
16817: Calling convention:
16818: 
16819:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname);
16820:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$laststore);
16821: 
16822: For more detailed information, see lonnet specific documentation.
16823: 
16824: =head1 RETURN MESSAGES
16825: 
16826: =over 4
16827: 
16828: =item * B<con_lost>: unable to contact remote host
16829: 
16830: =item * B<con_delayed>: unable to contact remote host, message will be delivered
16831: when the connection is brought back up
16832: 
16833: =item * B<con_failed>: unable to contact remote host and unable to save message
16834: for later delivery
16835: 
16836: =item * B<error:>: an error a occurred, a description of the error follows the :
16837: 
16838: =item * B<no_such_host>: unable to fund a host associated with the user/domain
16839: that was requested
16840: 
16841: =back
16842: 
16843: =head1 PUBLIC SUBROUTINES
16844: 
16845: =head2 Session Environment Functions
16846: 
16847: =over 4
16848: 
16849: =item * 
16850: X<appenv()>
16851: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
16852: the user envirnoment file, and will be restored for each access this
16853: user makes during this session, also modifies the %env for the current
16854: process. Optional rolesarrayref - if defined contains a reference to an array
16855: of roles which are exempt from the restriction on modifying user.role entries 
16856: in the user's environment.db and in %env.    
16857: 
16858: =item *
16859: X<delenv()>
16860: B<delenv($delthis,$regexp)>: removes all items from the session
16861: environment file that begin with $delthis. If the 
16862: optional second arg - $regexp - is true, $delthis is treated as a 
16863: regular expression, otherwise \Q$delthis\E is used. 
16864: The values are also deleted from the current processes %env.
16865: 
16866: =item * get_env_multiple($name) 
16867: 
16868: gets $name from the %env hash, it seemlessly handles the cases where multiple
16869: values may be defined and end up as an array ref.
16870: 
16871: returns an array of values
16872: 
16873: =back
16874: 
16875: =head2 User Information
16876: 
16877: =over 4
16878: 
16879: =item *
16880: X<queryauthenticate()>
16881: B<queryauthenticate($uname,$udom)>: try to determine user's current 
16882: authentication scheme
16883: 
16884: =item *
16885: X<authenticate()>
16886: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
16887: authenticate user from domain's lib servers (first use the current
16888: one). C<$upass> should be the users password.
16889: $checkdefauth is optional (value is 1 if a check should be made to
16890:    authenticate user using default authentication method, and allow
16891:    account creation if username does not have account in the domain).
16892: $clientcancheckhost is optional (value is 1 if checking whether the
16893:    server can host will occur on the client side in lonauth.pm).   
16894: 
16895: =item *
16896: X<homeserver()>
16897: B<homeserver($uname,$udom)>: find the server which has
16898: the user's directory and files (there must be only one), this caches
16899: the answer, and also caches if there is a borken connection.
16900: 
16901: =item *
16902: X<idget()>
16903: B<idget($udom,$idsref,$namespace)>: find the usernames behind either 
16904: a list of student/employee IDs or clicker IDs
16905: (student/employee IDs are a unique resource in a domain, there must be 
16906: only 1 ID per username, and only 1 username per ID in a specific domain).
16907: clickerIDs are not necessarily unique, as students might share clickers.
16908: (returns hash: id=>name,id=>name)
16909: 
16910: =item *
16911: X<idrget()>
16912: B<idrget($udom,@unames)>: find the IDs behind a list of
16913: usernames (returns hash: name=>id,name=>id)
16914: 
16915: =item *
16916: X<idput()>
16917: B<idput($udom,$idsref,$uhome,$namespace)>: store away a list of 
16918: names and associated student/employee IDs or clicker IDs.
16919: 
16920: =item *
16921: X<iddel()>
16922: B<iddel($udom,$idshashref,$uhome,$namespace)>: delete unwanted 
16923: student/employee ID or clicker ID username look-ups from domain.
16924: The homeserver ($uhome) and namespace ($namespace) are optional.
16925: If no $uhome is provided, it will be determined usig &homeserver()
16926: for each user.  If no $namespace is provided, the default is ids.
16927: 
16928: =item *
16929: X<updateclickers()>
16930: B<updateclickers($udom,$action,$idshashref,$uhome,$critical)>: update 
16931: clicker ID-to-username look-ups in clickers.db on library server.
16932: Permitted actions are add or del (i.e., add or delete). The 
16933: clickers.db contains clickerID as keys (escaped), and each corresponding
16934: value is an escaped comma-separated list of usernames (for whom the
16935: library server is the homeserver), who registered that particular ID.
16936: If $critical is true, the update will be sent via &critical, otherwise
16937: &reply() will be used.
16938: 
16939: =item *
16940: X<rolesinit()>
16941: B<rolesinit($udom,$username)>: get user privileges.
16942: returns user role, first access and timer interval hashes
16943: 
16944: =item *
16945: X<privileged()>
16946: B<privileged($username,$domain)>: returns a true if user has a
16947: privileged and active role (i.e. su or dc), false otherwise.
16948: 
16949: =item *
16950: X<getsection()>
16951: B<getsection($udom,$uname,$cname)>: finds the section of student in the
16952: course $cname, return section name/number or '' for "not in course"
16953: and '-1' for "no section"
16954: 
16955: =item *
16956: X<userenvironment()>
16957: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
16958: passed in @what from the requested user's environment, returns a hash
16959: 
16960: =item * 
16961: X<userlog_query()>
16962: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
16963: activity.log file. %filters defines filters applied when parsing the
16964: log file. These can be start or end timestamps, or the type of action
16965: - log to look for Login or Logout events, check for Checkin or
16966: Checkout, role for role selection. The response is in the form
16967: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
16968: escaped strings of the action recorded in the activity.log file.
16969: 
16970: =back
16971: 
16972: =head2 User Roles
16973: 
16974: =over 4
16975: 
16976: =item *
16977: 
16978: allowed($priv,$uri,$symb,$role,$clientip,$noblockcheck) : check for a user privilege; 
16979: returns codes for allowed actions.
16980: 
16981: The first argument is required, all others are optional.
16982: 
16983: $priv is the privilege being checked.
16984: $uri contains additional information about what is being checked for access (e.g.,
16985: URL, course ID etc.). 
16986: $symb is the unique resource instance identifier in a course; if needed,
16987: but not provided, it will be retrieved via a call to &symbread(). 
16988: $role is the role for which a priv is being checked (only used if priv is evb). 
16989: $clientip is the user's IP address (only used when checking for access to portfolio 
16990: files).
16991: $noblockcheck, if true, skips calls to &has_comm_blocking() for the bre priv. This 
16992: prevents recursive calls to &allowed.
16993: 
16994:  F: full access
16995:  U,I,K: authentication modes (cxx only)
16996:  '': forbidden
16997:  1: user needs to choose course
16998:  2: browse allowed
16999:  A: passphrase authentication needed
17000:  B: access temporarily blocked because of a blocking event in a course.
17001:  D: access blocked because access is required via session initiated via deep-link 
17002: 
17003: =item *
17004: 
17005: constructaccess($url,$setpriv) : check for access to construction space URL
17006: 
17007: See if the owner domain and name in the URL match those in the
17008: expected environment.  If so, return three element list
17009: ($ownername,$ownerdomain,$ownerhome).
17010: 
17011: Otherwise return the null string.
17012: 
17013: If second argument 'setpriv' is true, it assigns the privileges,
17014: and returns the same three element list, unless the owner has
17015: blocked "ad hoc" Domain Coordinator access to the Author Space,
17016: in which case the null string is returned.
17017: 
17018: =item *
17019: 
17020: definerole($rolename,$sysrole,$domrole,$courole,$uname,$udom) : define role;
17021: define a custom role rolename set privileges in format of lonTabs/roles.tab
17022: for system, domain, and course level. $uname and $udom are optional (current
17023: user's username and domain will be used when either of $uname or $udom are absent.
17024: 
17025: =item *
17026: 
17027: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
17028: (rolesplain.tab); plain text explanation of a user role term.
17029: $type is Course (default) or Community.
17030: If $forcedefault evaluates to true, text returned will be default 
17031: text for $type. Otherwise, if this is a course, the text returned 
17032: will be a custom name for the role (if defined in the course's 
17033: environment).  If no custom name is defined the default is returned.
17034:    
17035: =item *
17036: 
17037: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv) :
17038: All arguments are optional. Returns a hash of a roles, either for
17039: co-author/assistant author roles for a user's Construction Space
17040: (default), or if $context is 'userroles', roles for the user himself,
17041: In the hash, keys are set to colon-separated $uname,$udom,$role, and
17042: (optionally) if $withsec is true, a fourth colon-separated item - $section.
17043: For each key, value is set to colon-separated start and end times for
17044: the role.  If no username and domain are specified, will default to
17045: current user/domain. Types, roles, and roledoms are references to arrays
17046: of role statuses (active, future or previous), roles 
17047: (e.g., cc,in, st etc.) and domains of the roles which can be used
17048: to restrict the list of roles reported. If no array ref is 
17049: provided for types, will default to return only active roles.
17050: 
17051: =item *
17052: 
17053: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
17054: user: $uname:$udom has a role in the course: $cdom_$cnum. 
17055: 
17056: Additional optional arguments are: $type (if role checking is to be restricted 
17057: to certain user status types -- previous (expired roles), active (currently
17058: available roles) or future (roles available in the future), and
17059: $hideprivileged -- if true will not report course roles for users who
17060: have active Domain Coordinator role in course's domain or in additional
17061: domains (specified in 'Domains to check for privileged users' in course
17062: environment -- set via:  Course Settings -> Classlists and staff listing).
17063: 
17064: =item *
17065: 
17066: privileged($username,$domain,$possdomains,$possroles) : returns 1 if user
17067: $username:$domain is a privileged user (e.g., Domain Coordinator or Super User)
17068: $possdomains and $possroles are optional array refs -- to domains to check and
17069: roles to check.  If $possdomains is not specified, a dump will be done of the
17070: users' roles.db to check for a dc or su role in any domain. This can be
17071: time consuming if &privileged is called repeatedly (e.g., when displaying a
17072: classlist), so in such cases, supplying a $possdomains array is preferred, as
17073: this then allows &privileged_by_domain() to be used, which caches the identity
17074: of privileged users, eliminating the need for repeated calls to &dump().
17075: 
17076: =item *
17077: 
17078: privileged_by_domain($possdomains,$roles) : returns a hash of a hash of a hash,
17079: where the outer hash keys are domains specified in the $possdomains array ref,
17080: next inner hash keys are privileged roles specified in the $roles array ref,
17081: and the innermost hash contains key = value pairs for username:domain = end:start
17082: for active or future "privileged" users with that role in that domain. To avoid
17083: repeated dumps of domain roles -- via &get_domain_roles() -- contents of the
17084: innerhash are cached using priv_$role and $dom as the identifiers.
17085: 
17086: =back
17087: 
17088: =head2 User Modification
17089: 
17090: =over 4
17091: 
17092: =item *
17093: 
17094: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
17095: user for the level given by URL.  Optional start and end dates (leave empty
17096: string or zero for "no date")
17097: 
17098: =item *
17099: 
17100: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
17101: change a users, password, possible return values are: ok,
17102: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
17103: refused
17104: 
17105: =item *
17106: 
17107: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
17108: 
17109: =item *
17110: 
17111: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
17112:            $forceid,$desiredhome,$email,$inststatus,$candelete) :
17113: 
17114: will update user information (firstname,middlename,lastname,generation,
17115: permanentemail), and if forceid is true, student/employee ID also.
17116: A user's institutional affiliation(s) can also be updated.
17117: User information fields will not be overwritten with empty entries 
17118: unless the field is included in the $candelete array reference.
17119: This array is included when a single user is modified via "Manage Users",
17120: or when Autoupdate.pl is run by cron in a domain.
17121: 
17122: =item *
17123: 
17124: modifystudent
17125: 
17126: modify a student's enrollment and identification information.
17127: The course id is resolved based on the current user's environment.  
17128: This means the invoking user must be a course coordinator or otherwise
17129: associated with a course.
17130: 
17131: This call is essentially a wrapper for lonnet::modifyuser and
17132: lonnet::modify_student_enrollment
17133: 
17134: Inputs: 
17135: 
17136: =over 4
17137: 
17138: =item B<$udom> Student's loncapa domain
17139: 
17140: =item B<$uname> Student's loncapa login name
17141: 
17142: =item B<$uid> Student/Employee ID
17143: 
17144: =item B<$umode> Student's authentication mode
17145: 
17146: =item B<$upass> Student's password
17147: 
17148: =item B<$first> Student's first name
17149: 
17150: =item B<$middle> Student's middle name
17151: 
17152: =item B<$last> Student's last name
17153: 
17154: =item B<$gene> Student's generation
17155: 
17156: =item B<$usec> Student's section in course
17157: 
17158: =item B<$end> Unix time of the roles expiration
17159: 
17160: =item B<$start> Unix time of the roles start date
17161: 
17162: =item B<$forceid> If defined, allow $uid to be changed
17163: 
17164: =item B<$desiredhome> server to use as home server for student
17165: 
17166: =item B<$email> Student's permanent e-mail address
17167: 
17168: =item B<$type> Type of enrollment (auto or manual)
17169: 
17170: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
17171: 
17172: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
17173: 
17174: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
17175: 
17176: =item B<$context> role change context (shown in User Management Logs display in a course)
17177: 
17178: =item B<$inststatus> institutional status of user - : separated string of escaped status types
17179: 
17180: =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.
17181: 
17182: =back
17183: 
17184: =item *
17185: 
17186: modify_student_enrollment
17187: 
17188: Change a student's enrollment status in a class.  The environment variable
17189: 'role.request.course' must be defined for this function to proceed.
17190: 
17191: Inputs:
17192: 
17193: =over 4
17194: 
17195: =item $udom, student's domain
17196: 
17197: =item $uname, student's name
17198: 
17199: =item $uid, student's user id
17200: 
17201: =item $first, student's first name
17202: 
17203: =item $middle
17204: 
17205: =item $last
17206: 
17207: =item $gene
17208: 
17209: =item $usec
17210: 
17211: =item $end
17212: 
17213: =item $start
17214: 
17215: =item $type
17216: 
17217: =item $locktype
17218: 
17219: =item $cid
17220: 
17221: =item $selfenroll
17222: 
17223: =item $context
17224: 
17225: =item $credits, number of credits student will earn from this class
17226: 
17227: =item $instsec, institutional course section code for student
17228: 
17229: =back
17230: 
17231: 
17232: =item *
17233: 
17234: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
17235: custom role; give a custom role to a user for the level given by URL.  Specify
17236: name and domain of role author, and role name
17237: 
17238: =item *
17239: 
17240: revokerole($udom,$uname,$url,$role) : revoke a role for url
17241: 
17242: =item *
17243: 
17244: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
17245: 
17246: =back
17247: 
17248: =head2 Course Infomation
17249: 
17250: =over 4
17251: 
17252: =item *
17253: 
17254: coursedescription($courseid,$options) : returns a hash of information about the
17255: specified course id, including all environment settings for the
17256: course, the description of the course will be in the hash under the
17257: key 'description'
17258: 
17259: $options is an optional parameter that if supplied is a hash reference that controls
17260: what how this function works.  It has the following key/values:
17261: 
17262: =over 4
17263: 
17264: =item freshen_cache
17265: 
17266: If defined, and the environment cache for the course is valid, it is 
17267: returned in the returned hash.
17268: 
17269: =item one_time
17270: 
17271: If defined, the last cache time is set to _now_
17272: 
17273: =item user
17274: 
17275: If defined, the supplied username is used instead of the current user.
17276: 
17277: 
17278: =back
17279: 
17280: =item *
17281: 
17282: resdata($name,$domain,$type,@which) : request for current parameter
17283: setting for a specific $type, where $type is either 'course' or 'user',
17284: @what should be a list of parameters to ask about. This routine caches
17285: answers for 10 minutes.
17286: 
17287: =item *
17288: 
17289: get_courseresdata($courseid, $domain) : dump the entire course resource
17290: data base, returning a hash that is keyed by the resource name and has
17291: values that are the resource value.  I believe that the timestamps and
17292: versions are also returned.
17293: 
17294: =back
17295: 
17296: =head2 Course Modification
17297: 
17298: =over 4
17299: 
17300: =item *
17301: 
17302: writecoursepref($courseid,%prefs) : write preferences (environment
17303: database) for a course
17304: 
17305: =item *
17306: 
17307: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
17308: 
17309: =item *
17310: 
17311: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
17312: 
17313: =item *
17314: 
17315: is_course($courseid), is_course($cdom, $cnum)
17316: 
17317: Accepts either a combined $courseid (in the form of domain_courseid) or the
17318: two component version $cdom, $cnum. It checks if the specified course exists.
17319: 
17320: Returns:
17321:     undef if the course doesn't exist, otherwise
17322:     in scalar context the combined courseid.
17323:     in list context the two components of the course identifier, domain and 
17324:     courseid.    
17325: 
17326: =back
17327: 
17328: =head2 Bubblesheet Configuration
17329: 
17330: =over 4
17331: 
17332: =item *
17333: 
17334: get_scantron_config($which)
17335: 
17336: $which - the name of the configuration to parse from the file.
17337: 
17338: Parses and returns the bubblesheet configuration line selected as a
17339: hash of configuration file fields.
17340: 
17341: 
17342: Returns:
17343:     If the named configuration is not in the file, an empty
17344:     hash is returned.
17345: 
17346:     a hash with the fields
17347:       name         - internal name for the this configuration setup
17348:       description  - text to display to operator that describes this config
17349:       CODElocation - if 0 or the string 'none'
17350:                           - no CODE exists for this config
17351:                      if -1 || the string 'letter'
17352:                           - a CODE exists for this config and is
17353:                             a string of letters
17354:                      Unsupported value (but planned for future support)
17355:                           if a positive integer
17356:                                - The CODE exists as the first n items from
17357:                                  the question section of the form
17358:                           if the string 'number'
17359:                                - The CODE exists for this config and is
17360:                                  a string of numbers
17361:       CODEstart   - (only matter if a CODE exists) column in the line where
17362:                      the CODE starts
17363:       CODElength  - length of the CODE
17364:       IDstart     - column where the student/employee ID starts
17365:       IDlength    - length of the student/employee ID info
17366:       Qstart      - column where the information from the bubbled
17367:                     'questions' start
17368:       Qlength     - number of columns comprising a single bubble line from
17369:                     the sheet. (usually either 1 or 10)
17370:       Qon         - either a single character representing the character used
17371:                     to signal a bubble was chosen in the positional setup, or
17372:                     the string 'letter' if the letter of the chosen bubble is
17373:                     in the final, or 'number' if a number representing the
17374:                     chosen bubble is in the file (1->A 0->J)
17375:       Qoff        - the character used to represent that a bubble was
17376:                     left blank
17377:       PaperID     - if the scanning process generates a unique number for each
17378:                     sheet scanned the column that this ID number starts in
17379:       PaperIDlength - number of columns that comprise the unique ID number
17380:                       for the sheet of paper
17381:       FirstName   - column that the first name starts in
17382:       FirstNameLength - number of columns that the first name spans
17383:       LastName    - column that the last name starts in
17384:       LastNameLength - number of columns that the last name spans
17385:       BubblesPerRow - number of bubbles available in each row used to
17386:                       bubble an answer. (If not specified, 10 assumed).
17387: 
17388: 
17389: =item *
17390: 
17391: get_scantronformat_file($cdom)
17392: 
17393: $cdom - the course's domain (optional); if not supplied, uses
17394: domain for current $env{'request.course.id'}.
17395: 
17396: Returns an array containing lines from the scantron format file for
17397: the domain of the course.
17398: 
17399: If a url for a custom.tab file is listed in domain's configuration.db,
17400: lines are from this file.
17401: 
17402: Otherwise, if a default.tab has been published in RES space by the
17403: domainconfig user, lines are from this file.
17404: 
17405: Otherwise, fall back to getting lines from the legacy file on the
17406: local server:  /home/httpd/lonTabs/default_scantronformat.tab
17407: 
17408: =back
17409: 
17410: =head2 Resource Subroutines
17411: 
17412: =over 4
17413: 
17414: =item *
17415: 
17416: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
17417: 
17418: =item *
17419: 
17420: repcopy($filename) : subscribes to the requested file, and attempts to
17421: replicate from the owning library server, Might return
17422: 'unavailable', 'not_found', 'forbidden', 'ok', or
17423: 'bad_request', also attempts to grab the metadata for the
17424: resource. Expects the local filesystem pathname
17425: (/home/httpd/html/res/....)
17426: 
17427: =back
17428: 
17429: =head2 Resource Information
17430: 
17431: =over 4
17432: 
17433: =item *
17434: 
17435: EXT($varname,$symb,$udom,$uname,$usection,$recurse,$cid) : evaluates 
17436: and returns the value of a variety of different possible values,
17437: $varname should be a request string, and the other parameters can be
17438: used to specify who and what one is asking about. Ordinarily, $cid 
17439: does not need to be specified, as it is retrived from 
17440: $env{'request.course.id'}, but &Apache::lonnet::EXT() is called
17441: within lonuserstate::loadmap() when initializing a course, before
17442: $env{'request.course.id'} has been set, so it needs to be provided
17443: in that one case.
17444: 
17445: Possible values for $varname are environment.lastname (or other item
17446: from the envirnment hash), user.name (or someother aspect about the
17447: user), resource.0.maxtries (or some other part and parameter of a
17448: resource)
17449: 
17450: =item *
17451: 
17452: directcondval($number) : get current value of a condition; reads from a state
17453: string
17454: 
17455: =item *
17456: 
17457: condval($condidx) : value of condition index based on state
17458: 
17459: =item *
17460: 
17461: metadata($uri,$what,$toolsymb,$liburi,$prefix,$depthcount) : request a
17462: resource's metadata, $what should be either a specific key, or either
17463: 'keys' (to get a list of possible keys) or 'packages' to get a list of
17464: packages that this resource currently uses, the last 3 arguments are 
17465: only used internally for recursive metadata.
17466: 
17467: the toolsymb is only used where the uri is for an external tool (for which
17468: the uri as well as the symb are guaranteed to be unique).
17469: 
17470: this function automatically caches all requests except any made recursively
17471: to retrieve a list of metadata keys for an imported library file ($liburi is 
17472: defined).
17473: 
17474: =item *
17475: 
17476: metadata_query($query,$custom,$customshow) : make a metadata query against the
17477: network of library servers; returns file handle of where SQL and regex results
17478: will be stored for query
17479: 
17480: =item *
17481: 
17482: symbread($filename,$donotrecurse,$ignorecachednull,$checkforblock,$possibles) : 
17483: return symbolic list entry (all arguments optional). 
17484: 
17485: Args: filename is the filename (including path) for the file for which a symb 
17486: is required; donotrecurse, if true will prevent calls to allowed() being made 
17487: to check access status if more than one resource was found in the bighash 
17488: (see rev. 1.249) to avoid an infinite loop if an ambiguous resource is part of 
17489: a randompick); ignorecachednull, if true will prevent a symb of '' being 
17490: returned if $env{$cache_str} is defined as ''; checkforblock if true will
17491: cause possible symbs to be checked to determine if they are subject to content
17492: blocking, if so they will not be included as possible symbs; possibles is a
17493: ref to a hash, which, as a side effect, will be populated with all possible 
17494: symbs (content blocking not tested).
17495:  
17496: returns the data handle
17497: 
17498: =item *
17499: 
17500: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
17501: and is a possible symb for the URL in $thisfn, and if is an encrypted
17502: resource that the user accessed using /enc/ returns a 1 on success, 0
17503: on failure, user must be in a course, as it assumes the existence of
17504: the course initial hash, and uses $env('request.course.id'}.  The third
17505: arg is an optional reference to a scalar.  If this arg is passed in the 
17506: call to symbverify, it will be set to 1 if the symb has been set to be 
17507: encrypted; otherwise it will be null.  
17508: 
17509: =item *
17510: 
17511: symbclean($symb) : removes versions numbers from a symb, returns the
17512: cleaned symb
17513: 
17514: =item *
17515: 
17516: is_on_map($uri) : checks if the $uri is somewhere on the current
17517: course map, user must be in a course for it to work.
17518: 
17519: =item *
17520: 
17521: numval($salt) : return random seed value (addend for rndseed)
17522: 
17523: =item *
17524: 
17525: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
17526: a random seed, all arguments are optional, if they aren't sent it uses the
17527: environment to derive them. Note: if symb isn't sent and it can't get one
17528: from &symbread it will use the current time as its return value
17529: 
17530: =item *
17531: 
17532: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
17533: unfakeable, receipt
17534: 
17535: =item *
17536: 
17537: receipt() : API to ireceipt working off of env values; given out to users
17538: 
17539: =item *
17540: 
17541: countacc($url) : count the number of accesses to a given URL
17542: 
17543: =item *
17544: 
17545: 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
17546: 
17547: =item *
17548: 
17549: 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)
17550: 
17551: =item *
17552: 
17553: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
17554: 
17555: =item *
17556: 
17557: devalidate($symb) : devalidate temporary spreadsheet calculations,
17558: forcing spreadsheet to reevaluate the resource scores next time.
17559: 
17560: =item * 
17561: 
17562: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
17563: when viewing in course context.
17564: 
17565:  input: six args -- filename (decluttered), course number, course domain,
17566:                     url, symb (if registered) and group (if this is a 
17567:                     group item -- e.g., bulletin board, group page etc.).
17568: 
17569:  output: array of five scalars --
17570:          $cfile -- url for file editing if editable on current server
17571:          $home -- homeserver of resource (i.e., for author if published,
17572:                                           or course if uploaded.).
17573:          $switchserver --  1 if server switch will be needed.
17574:          $forceedit -- 1 if icon/link should be to go to edit mode 
17575:          $forceview -- 1 if icon/link should be to go to view mode
17576: 
17577: =item *
17578: 
17579: is_course_upload($file,$cnum,$cdom)
17580: 
17581: Used in course context to determine if current file was uploaded to 
17582: the course (i.e., would be found in /userfiles/docs on the course's 
17583: homeserver.
17584: 
17585:   input: 3 args -- filename (decluttered), course number and course domain.
17586:   output: boolean -- 1 if file was uploaded.
17587: 
17588: =back
17589: 
17590: =head2 Storing/Retreiving Data
17591: 
17592: =over 4
17593: 
17594: =item *
17595: 
17596: store($storehash,$symb,$namespace,$udom,$uname,$laststore) : stores hash
17597: permanently for this url; hashref needs to be given and should be a \%hashname;
17598: the remaining args aren't required and if they aren't passed or are '' they will
17599: be derived from the env (with the exception of $laststore, which is an 
17600: optional arg used when a user's submission is stored in grading).
17601: $laststore is $version=$timestamp, where $version is the most recent version
17602: number retrieved for the corresponding $symb in the $namespace db file, and
17603: $timestamp is the timestamp for that transaction (UNIX time).
17604: $laststore is currently only passed when cstore() is called by 
17605: structuretags::finalize_storage().
17606: 
17607: =item *
17608: 
17609: cstore($storehash,$symb,$namespace,$udom,$uname,$laststore) : same as store
17610: but uses critical subroutine
17611: 
17612: =item *
17613: 
17614: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
17615: all args are optional
17616: 
17617: =item *
17618: 
17619: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
17620: dumps the complete (or key matching regexp) namespace into a hash
17621: ($udom, $uname, $regexp, $range are optional) for a namespace that is
17622: normally &store()ed into
17623: 
17624: $range should be either an integer '100' (give me the first 100
17625:                                            matching records)
17626:               or be  two integers sperated by a - with no spaces
17627:                  '30-50' (give me the 30th through the 50th matching
17628:                           records)
17629: 
17630: 
17631: =item *
17632: 
17633: putstore($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog) :
17634: replaces a &store() version of data with a replacement set of data
17635: for a particular resource in a namespace passed in the $storehash hash 
17636: reference. If $tolog is true, the transaction is logged in the courselog
17637: with an action=PUTSTORE.
17638: 
17639: =item *
17640: 
17641: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
17642: works very similar to store/cstore, but all data is stored in a
17643: temporary location and can be reset using tmpreset, $storehash should
17644: be a hash reference, returns nothing on success
17645: 
17646: =item *
17647: 
17648: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
17649: similar to restore, but all data is stored in a temporary location and
17650: can be reset using tmpreset. Returns a hash of values on success,
17651: error string otherwise.
17652: 
17653: =item *
17654: 
17655: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
17656: deltes all keys for $symb form the temporary storage hash.
17657: 
17658: =item *
17659: 
17660: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
17661: reference filled in from namesp ($udom and $uname are optional)
17662: 
17663: =item *
17664: 
17665: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
17666: namesp ($udom and $uname are optional)
17667: 
17668: =item *
17669: 
17670: dump($namespace,$udom,$uname,$regexp,$range) : 
17671: dumps the complete (or key matching regexp) namespace into a hash
17672: ($udom, $uname, $regexp, $range are optional)
17673: 
17674: $range should be either an integer '100' (give me the first 100
17675:                                            matching records)
17676:               or be  two integers sperated by a - with no spaces
17677:                  '30-50' (give me the 30th through the 50th matching
17678:                           records)
17679: =item *
17680: 
17681: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
17682: $store can be a scalar, an array reference, or if the amount to be 
17683: incremented is > 1, a hash reference.
17684: 
17685: ($udom and $uname are optional)
17686: 
17687: =item *
17688: 
17689: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
17690: ($udom and $uname are optional)
17691: 
17692: =item *
17693: 
17694: cput($namespace,$storehash,$udom,$uname) : critical put
17695: ($udom and $uname are optional)
17696: 
17697: =item *
17698: 
17699: newput($namespace,$storehash,$udom,$uname) :
17700: 
17701: Attempts to store the items in the $storehash, but only if they don't
17702: currently exist, if this succeeds you can be certain that you have 
17703: successfully created a new key value pair in the $namespace db.
17704: 
17705: 
17706: Args:
17707:  $namespace: name of database to store values to
17708:  $storehash: hashref to store to the db
17709:  $udom: (optional) domain of user containing the db
17710:  $uname: (optional) name of user caontaining the db
17711: 
17712: Returns:
17713:  'ok' -> succeeded in storing all keys of $storehash
17714:  'key_exists: <key>' -> failed to anything out of $storehash, as at
17715:                         least <key> already existed in the db (other
17716:                         requested keys may also already exist)
17717:  'error: <msg>' -> unable to tie the DB or other error occurred
17718:  'con_lost' -> unable to contact request server
17719:  'refused' -> action was not allowed by remote machine
17720: 
17721: 
17722: =item *
17723: 
17724: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
17725: reference filled in from namesp (encrypts the return communication)
17726: ($udom and $uname are optional)
17727: 
17728: =item *
17729: 
17730: log($udom,$name,$home,$message) : write to permanent log for user; use
17731: critical subroutine
17732: 
17733: =item *
17734: 
17735: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
17736: array reference filled in from namespace found in domain level on either
17737: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
17738: 
17739: =item *
17740: 
17741: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
17742: domain level either on specified domain server ($uhome) or primary domain 
17743: server ($udom and $uhome are optional)
17744: 
17745: =item * 
17746: 
17747: get_domain_defaults($target_domain,$ignore_cache) : returns hash with defaults 
17748: for: authentication, language, quotas, timezone, date locale, and portal URL in
17749: the target domain.
17750: 
17751: May also include additional key => value pairs for the following groups:
17752: 
17753: =over
17754: 
17755: =item
17756: disk quotas (MB allocated by default to portfolios and authoring spaces).
17757: 
17758: =over
17759: 
17760: =item defaultquota, authorquota
17761: 
17762: =back
17763: 
17764: =item
17765: tools (availability of aboutme page, blog, webDAV access for authoring spaces,
17766: portfolio for users).
17767: 
17768: =over
17769: 
17770: =item
17771: aboutme, blog, webdav, portfolio
17772: 
17773: =back
17774: 
17775: =item
17776: requestcourses: ability to request courses, and how requests are processed.
17777: 
17778: =over
17779: 
17780: =item
17781: official, unofficial, community, textbook, placement
17782: 
17783: =back
17784: 
17785: =item
17786: inststatus: types of institutional affiliation, and order in which they are displayed.
17787: 
17788: =over
17789: 
17790: =item
17791: inststatustypes, inststatusorder, inststatusguest
17792: 
17793: =back
17794: 
17795: =item
17796: coursedefaults: can PDF forms can be created, default credits for courses, default quotas (MB)
17797: for course's uploaded content.
17798: 
17799: =over
17800: 
17801: =item
17802: canuse_pdfforms, officialcredits, unofficialcredits, textbookcredits, officialquota, unofficialquota, 
17803: communityquota, textbookquota, placementquota
17804: 
17805: =back
17806: 
17807: =item
17808: usersessions: set options for hosting of your users in other domains, and hosting of users from other domains
17809: on your servers.
17810: 
17811: =over
17812: 
17813: =item 
17814: remotesessions, hostedsessions
17815: 
17816: =back
17817: 
17818: =back
17819: 
17820: In cases where a domain coordinator has never used the "Set Domain Configuration"
17821: utility to create a configuration.db file on a domain's primary library server 
17822: only the following domain defaults: auth_def, auth_arg_def, lang_def
17823: -- corresponding values are authentication type (internal, krb4, krb5,
17824: or localauth), initial password or a kerberos realm, language (e.g., en-us) -- 
17825: will be available. Values are retrieved from cache (if current), unless the
17826: optional $ignore_cache arg is true, or from domain's configuration.db (if available),
17827: or lastly from values in lonTabs/dns_domain,tab, or lonTabs/domain.tab.
17828: 
17829: Typical usage:
17830: 
17831: %domdefaults = &get_domain_defaults($target_domain);
17832: 
17833: =back
17834: 
17835: =head2 Network Status Functions
17836: 
17837: =over 4
17838: 
17839: =item *
17840: 
17841: dirlist() : return directory list based on URI (first arg).
17842: 
17843: Inputs: 1 required, 5 optional.
17844: 
17845: =over
17846: 
17847: =item 
17848: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
17849: 
17850: =item
17851: $userdomain - domain of user/course to be listed. Extracted from $uri if absent. 
17852: 
17853: =item
17854: $username -  username of user/course to be listed. Extracted from $uri if absent. 
17855: 
17856: =item
17857: $getpropath - boolean: 1 if prepend path using &propath(). 
17858: 
17859: =item
17860: $getuserdir - boolean: 1 if prepend path for "userfiles".
17861: 
17862: =item 
17863: $alternateRoot - path to prepend in place of path from $uri.
17864: 
17865: =back
17866: 
17867: Returns: Array of up to two items.
17868: 
17869: =over
17870: 
17871: a reference to an array of files/subdirectories
17872: 
17873: =over
17874: 
17875: Each element in the array of files/subdirectories is a & separated list of
17876: item name and the result of running stat on the item.  If dirlist was requested
17877: for a file instead of a directory, the item name will be ''. For a directory 
17878: listing, if the item is a metadata file, the element will end &N&M 
17879: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
17880: default copyright set (1).  
17881: 
17882: =back
17883: 
17884: a scalar containing error condition (if encountered).
17885: 
17886: =over
17887: 
17888: =item 
17889: no_host (no homeserver identified for $username:$domain).
17890: 
17891: =item 
17892: no_such_host (server contacted for listing not identified as valid host).
17893: 
17894: =item 
17895: con_lost (connection to remote server failed).
17896: 
17897: =item 
17898: refused (invalid $username:$domain received on lond side).
17899: 
17900: =item 
17901: no_such_dir (directory at specified path on lond side does not exist). 
17902: 
17903: =item 
17904: empty (directory at specified path on lond side is empty).
17905: 
17906: =over
17907: 
17908: This is currently not encountered because the &ls3, &ls2, 
17909: &ls (_handler) routines on the lond side do not filter out
17910: . and .. from a directory listing. 
17911: 
17912: =back
17913: 
17914: =back
17915: 
17916: =back
17917: 
17918: =item *
17919: 
17920: spareserver() : find server with least workload from spare.tab
17921: 
17922: 
17923: =item *
17924: 
17925: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
17926: if there is no corresponding loncapa host.
17927: 
17928: =back
17929: 
17930: 
17931: =head2 Apache Request
17932: 
17933: =over 4
17934: 
17935: =item *
17936: 
17937: ssi($url,%hash) : server side include, does a complete request cycle on url to
17938: localhost, posts hash
17939: 
17940: =back
17941: 
17942: =head2 Data to String to Data
17943: 
17944: =over 4
17945: 
17946: =item *
17947: 
17948: hash2str(%hash) : convert a hash into a string complete with escaping and '='
17949: and '&' separators, supports elements that are arrayrefs and hashrefs
17950: 
17951: =item *
17952: 
17953: hashref2str($hashref) : convert a hashref into a string complete with
17954: escaping and '=' and '&' separators, supports elements that are
17955: arrayrefs and hashrefs
17956: 
17957: =item *
17958: 
17959: arrayref2str($arrayref) : convert an arrayref into a string complete
17960: with escaping and '&' separators, supports elements that are arrayrefs
17961: and hashrefs
17962: 
17963: =item *
17964: 
17965: str2hash($string) : convert string to hash using unescaping and
17966: splitting on '=' and '&', supports elements that are arrayrefs and
17967: hashrefs
17968: 
17969: =item *
17970: 
17971: str2array($string) : convert string to hash using unescaping and
17972: splitting on '&', supports elements that are arrayrefs and hashrefs
17973: 
17974: =back
17975: 
17976: =head2 Logging Routines
17977: 
17978: 
17979: These routines allow one to make log messages in the lonnet.log and
17980: lonnet.perm logfiles.
17981: 
17982: =over 4
17983: 
17984: =item *
17985: 
17986: logtouch() : make sure the logfile, lonnet.log, exists
17987: 
17988: =item *
17989: 
17990: logthis() : append message to the normal lonnet.log file, it gets
17991: preiodically rolled over and deleted.
17992: 
17993: =item *
17994: 
17995: logperm() : append a permanent message to lonnet.perm.log, this log
17996: file never gets deleted by any automated portion of the system, only
17997: messages of critical importance should go in here.
17998: 
17999: 
18000: =back
18001: 
18002: =head2 General File Helper Routines
18003: 
18004: =over 4
18005: 
18006: =item *
18007: 
18008: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
18009: (a) files in /uploaded
18010:   (i) If a local copy of the file exists - 
18011:       compares modification date of local copy with last-modified date for 
18012:       definitive version stored on home server for course. If local copy is 
18013:       stale, requests a new version from the home server and stores it. 
18014:       If the original has been removed from the home server, then local copy 
18015:       is unlinked.
18016:   (ii) If local copy does not exist -
18017:       requests the file from the home server and stores it. 
18018:   
18019:   If $caller is 'uploadrep':  
18020:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
18021:     for request for files originally uploaded via DOCS. 
18022:      - returns 'ok' if fresh local copy now available, -1 otherwise.
18023:   
18024:   Otherwise:
18025:      This indicates a call from the content generation phase of the request.
18026:      -  returns the entire contents of the file or -1.
18027:      
18028: (b) files in /res
18029:    - returns the entire contents of a file or -1; 
18030:    it properly subscribes to and replicates the file if neccessary.
18031: 
18032: 
18033: =item *
18034: 
18035: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
18036:                   reference
18037: 
18038: returns either a stat() list of data about the file or an empty list
18039: if the file doesn't exist or couldn't find out about it (connection
18040: problems or user unknown)
18041: 
18042: =item *
18043: 
18044: filelocation($dir,$file) : returns file system location of a file
18045: based on URI; meant to be "fairly clean" absolute reference, $dir is a
18046: directory that relative $file lookups are to looked in ($dir of /a/dir
18047: and a file of ../bob will become /a/bob)
18048: 
18049: =item *
18050: 
18051: hreflocation($dir,$file) : returns file system location or a URL; same as
18052: filelocation except for hrefs
18053: 
18054: =item *
18055: 
18056: declutter() : declutters URLs -- remove beginning slashes, 'res' etc.
18057: also removes beginning /home/httpd/html unless /priv/ follows it.
18058: 
18059: =back
18060: 
18061: =head2 Usererfile file routines (/uploaded*)
18062: 
18063: =over 4
18064: 
18065: =item *
18066: 
18067: userfileupload(): main rotine for putting a file in a user or course's
18068:                   filespace, arguments are,
18069: 
18070:  formname - required - this is the name of the element in $env where the
18071:            filename, and the contents of the file to create/modifed exist
18072:            the filename is in $env{'form.'.$formname.'.filename'} and the
18073:            contents of the file is located in $env{'form.'.$formname}
18074:  context - if coursedoc, store the file in the course of the active role
18075:              of the current user; 
18076:            if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
18077:            if 'canceloverwrite': delete file in tmp/overwrites directory
18078:  subdir - required - subdirectory to put the file in under ../userfiles/
18079:          if undefined, it will be placed in "unknown"
18080: 
18081:  (This routine calls clean_filename() to remove any dangerous
18082:  characters from the filename, and then calls finuserfileupload() to
18083:  complete the transaction)
18084: 
18085:  returns either the url of the uploaded file (/uploaded/....) if successful
18086:  and /adm/notfound.html if unsuccessful
18087: 
18088: =item *
18089: 
18090: clean_filename(): routine for cleaing a filename up for storage in
18091:                  userfile space, argument is:
18092: 
18093:  filename - proposed filename
18094: 
18095: returns: the new clean filename
18096: 
18097: =item *
18098: 
18099: finishuserfileupload(): routine that creates and sends the file to
18100: userspace, probably shouldn't be called directly
18101: 
18102:   docuname: username or courseid of destination for the file
18103:   docudom: domain of user/course of destination for the file
18104:   formname: same as for userfileupload()
18105:   fname: filename (including subdirectories) for the file
18106:   parser: if 'parse', will parse (html) file to extract references to objects, links etc.
18107:           if hashref, and context is scantron, will convert csv format to standard format
18108:   allfiles: reference to hash used to store objects found by parser
18109:   codebase: reference to hash used for codebases of java objects found by parser
18110:   thumbwidth: width (pixels) of thumbnail to be created for uploaded image
18111:   thumbheight: height (pixels) of thumbnail to be created for uploaded image
18112:   resizewidth: width to be used to resize image using resizeImage from ImageMagick
18113:   resizeheight: height to be used to resize image using resizeImage from ImageMagick
18114:   context: if 'overwrite', will move the uploaded file from its temporary location to
18115:             userfiles to facilitate overwriting a previously uploaded file with same name.
18116:   mimetype: reference to scalar to accommodate mime type determined
18117:             from File::MMagic if $parser = parse.
18118: 
18119:  returns either the url of the uploaded file (/uploaded/....) if successful
18120:  and /adm/notfound.html if unsuccessful (or an error message if context 
18121:  was 'overwrite').
18122:  
18123: 
18124: =item *
18125: 
18126: renameuserfile(): renames an existing userfile to a new name
18127: 
18128:   Args:
18129:    docuname: username or courseid of destination for the file
18130:    docudom: domain of user/course of destination for the file
18131:    old: current file name (including any subdirs under userfiles)
18132:    new: desired file name (including any subdirs under userfiles)
18133: 
18134: =item *
18135: 
18136: mkdiruserfile(): creates a directory is a userfiles dir
18137: 
18138:   Args:
18139:    docuname: username or courseid of destination for the file
18140:    docudom: domain of user/course of destination for the file
18141:    dir: dir to create (including any subdirs under userfiles)
18142: 
18143: =item *
18144: 
18145: removeuserfile(): removes a file that exists in userfiles
18146: 
18147:   Args:
18148:    docuname: username or courseid of destination for the file
18149:    docudom: domain of user/course of destination for the file
18150:    fname: filname to delete (including any subdirs under userfiles)
18151: 
18152: =item *
18153: 
18154: removeuploadedurl(): convience function for removeuserfile()
18155: 
18156:   Args:
18157:    url:  a full /uploaded/... url to delete
18158: 
18159: =item * 
18160: 
18161: get_portfile_permissions():
18162:   Args:
18163:     domain: domain of user or course contain the portfolio files
18164:     user: name of user or num of course contain the portfolio files
18165:   Returns:
18166:     hashref of a dump of the proper file_permissions.db
18167:    
18168: 
18169: =item * 
18170: 
18171: get_access_controls():
18172: 
18173: Args:
18174:   current_permissions: the hash ref returned from get_portfile_permissions()
18175:   group: (optional) the group you want the files associated with
18176:   file: (optional) the file you want access info on
18177: 
18178: Returns:
18179:     a hash (keys are file names) of hashes containing
18180:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
18181:         values are XML containing access control settings (see below) 
18182: 
18183: Internal notes:
18184: 
18185:  access controls are stored in file_permissions.db as key=value pairs.
18186:     key -> path to file/file_name\0uniqueID:scope_end_start
18187:         where scope -> public,guest,course,group,domains or users.
18188:               end -> UNIX time for end of access (0 -> no end date)
18189:               start -> UNIX time for start of access
18190: 
18191:     value -> XML description of access control
18192:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
18193:             <start></start>
18194:             <end></end>
18195: 
18196:             <password></password>  for scope type = guest
18197: 
18198:             <domain></domain>     for scope type = course or group
18199:             <number></number>
18200:             <roles id="">
18201:              <role></role>
18202:              <access></access>
18203:              <section></section>
18204:              <group></group>
18205:             </roles>
18206: 
18207:             <dom></dom>         for scope type = domains
18208: 
18209:             <users>             for scope type = users
18210:              <user>
18211:               <uname></uname>
18212:               <udom></udom>
18213:              </user>
18214:             </users>
18215:            </scope> 
18216:               
18217:  Access data is also aggregated for each file in an additional key=value pair:
18218:  key -> path to file/file_name\0accesscontrol 
18219:  value -> reference to hash
18220:           hash contains key = value pairs
18221:           where key = uniqueID:scope_end_start
18222:                 value = UNIX time record was last updated
18223: 
18224:           Used to improve speed of look-ups of access controls for each file.  
18225:  
18226:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
18227: 
18228: =item *
18229: 
18230: modify_access_controls():
18231: 
18232: Modifies access controls for a portfolio file
18233: Args
18234: 1. file name
18235: 2. reference to hash of required changes,
18236: 3. domain
18237: 4. username
18238:   where domain,username are the domain of the portfolio owner 
18239:   (either a user or a course) 
18240: 
18241: Returns:
18242: 1. result of additions or updates ('ok' or 'error', with error message). 
18243: 2. result of deletions ('ok' or 'error', with error message).
18244: 3. reference to hash of any new or updated access controls.
18245: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
18246:    key = integer (inbound ID)
18247:    value = uniqueID
18248: 
18249: =item *
18250: 
18251: get_timebased_id():
18252: 
18253: Attempts to get a unique timestamp-based suffix for use with items added to a 
18254: course via the Course Editor (e.g., folders, composite pages, 
18255: group bulletin boards).
18256: 
18257: Args: (first three required; six others optional)
18258: 
18259: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
18260:    docssequence, or name of group
18261: 
18262: 2. keyid (alphanumeric): name of temporary locking key in hash,
18263:    e.g., num, boardids
18264: 
18265: 3. namespace: name of gdbm file used to store suffixes already assigned;  
18266:    file will be named nohist_namespace.db
18267: 
18268: 4. cdom: domain of course; default is current course domain from %env
18269: 
18270: 5. cnum: course number; default is current course number from %env
18271: 
18272: 6. idtype: set to concat if an additional digit is to be appended to the 
18273:    unix timestamp to form the suffix, if the plain timestamp is already
18274:    in use.  Default is to not do this, but simply increment the unix 
18275:    timestamp by 1 until a unique key is obtained.
18276: 
18277: 7. who: holder of locking key; defaults to user:domain for user.
18278: 
18279: 8. locktries: number of attempts to obtain a lock (sleep of 1s before 
18280:    retrying); default is 3.
18281: 
18282: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.  
18283: 
18284: Returns:
18285: 
18286: 1. suffix obtained (numeric)
18287: 
18288: 2. result of deleting locking key (ok if deleted, or lock never obtained)
18289: 
18290: 3. error: contains (localized) error message if an error occurred.
18291: 
18292: 
18293: =back
18294: 
18295: =head2 HTTP Helper Routines
18296: 
18297: =over 4
18298: 
18299: =item *
18300: 
18301: escape() : unpack non-word characters into CGI-compatible hex codes
18302: 
18303: =item *
18304: 
18305: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
18306: 
18307: =back
18308: 
18309: =head1 PRIVATE SUBROUTINES
18310: 
18311: =head2 Underlying communication routines (Shouldn't call)
18312: 
18313: =over 4
18314: 
18315: =item *
18316: 
18317: subreply() : tries to pass a message to lonc, returns con_lost if incapable
18318: 
18319: =item *
18320: 
18321: reply() : uses subreply to send a message to remote machine, logs all failures
18322: 
18323: =item *
18324: 
18325: critical() : passes a critical message to another server; if cannot
18326: get through then place message in connection buffer directory and
18327: returns con_delayed, if incapable of saving message, returns
18328: con_failed
18329: 
18330: =item *
18331: 
18332: reconlonc() : tries to reconnect lonc client processes.
18333: 
18334: =back
18335: 
18336: =head2 Resource Access Logging
18337: 
18338: =over 4
18339: 
18340: =item *
18341: 
18342: flushcourselogs() : flush (save) buffer logs and access logs
18343: 
18344: =item *
18345: 
18346: courselog($what) : save message for course in hash
18347: 
18348: =item *
18349: 
18350: courseacclog($what) : save message for course using &courselog().  Perform
18351: special processing for specific resource types (problems, exams, quizzes, etc).
18352: 
18353: =item *
18354: 
18355: goodbye() : flush course logs and log shutting down; it is called in srm.conf
18356: as a PerlChildExitHandler
18357: 
18358: =back
18359: 
18360: =head2 Other
18361: 
18362: =over 4
18363: 
18364: =item *
18365: 
18366: symblist($mapname,%newhash) : update symbolic storage links
18367: 
18368: =back
18369: 
18370: =cut
18371: 

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