File:  [LON-CAPA] / loncom / lonnet / perl / lonnet.pm
Revision 1.1524: download - view: text, annotated - select for diffs
Fri Mar 29 17:32:03 2024 UTC (3 months, 2 weeks ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Allowed editors for co-author access to Authpring Space:
  - For coauthor roles, if authoreditors is absent in environment.db for the
    Authoring Space's author, use domain default, or if not yet set, default
    to edit,xml.

    1: # The LearningOnline Network
    2: # TCP networking package
    3: #
    4: # $Id: lonnet.pm,v 1.1524 2024/03/29 17:32:03 raeburn Exp $
    5: #
    6: # Copyright Michigan State University Board of Trustees
    7: #
    8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
    9: #
   10: # LON-CAPA is free software; you can redistribute it and/or modify
   11: # it under the terms of the GNU General Public License as published by
   12: # the Free Software Foundation; either version 2 of the License, or
   13: # (at your option) any later version.
   14: #
   15: # LON-CAPA is distributed in the hope that it will be useful,
   16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
   17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   18: # GNU General Public License for more details.
   19: #
   20: # You should have received a copy of the GNU General Public License
   21: # along with LON-CAPA; if not, write to the Free Software
   22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
   23: #
   24: # /home/httpd/html/adm/gpl.txt
   25: #
   26: # http://www.lon-capa.org/
   27: #
   28: ###
   29: 
   30: =pod
   31: 
   32: =head1 NAME
   33: 
   34: Apache::lonnet.pm
   35: 
   36: =head1 SYNOPSIS
   37: 
   38: This file is an interface to the lonc processes of
   39: the LON-CAPA network as well as set of elaborated functions for handling information
   40: necessary for navigating through a given cluster of LON-CAPA machines within a
   41: domain. There are over 40 specialized functions in this module which handle the
   42: reading and transmission of metadata, user information (ids, names, environments, roles,
   43: logs), file information (storage, reading, directories, extensions, replication, embedded
   44: styles and descriptors), educational resources (course descriptions, section names and
   45: numbers), url hashing (to assign roles on a url basis), and translating abbreviated symbols to
   46: and from more descriptive phrases or explanations.
   47: 
   48: This is part of the LearningOnline Network with CAPA project
   49: described at http://www.lon-capa.org.
   50: 
   51: =head1 Package Variables
   52: 
   53: These are largely undocumented, so if you decipher one please note it here.
   54: 
   55: =over 4
   56: 
   57: =item $processmarker
   58: 
   59: Contains the time this process was started and this servers host id.
   60: 
   61: =item $dumpcount
   62: 
   63: Counts the number of times a message log flush has been attempted (regardless
   64: of success) by this process.  Used as part of the filename when messages are
   65: delayed.
   66: 
   67: =back
   68: 
   69: =cut
   70: 
   71: package Apache::lonnet;
   72: 
   73: use strict;
   74: use HTTP::Date;
   75: use Image::Magick;
   76: use CGI::Cookie;
   77: 
   78: use Encode;
   79: 
   80: use vars qw(%perlvar %spareid %pr %prp $memcache %packagetab $tmpdir $deftex
   81:             $_64bit %env %protocol %loncaparevs %serverhomeIDs %needsrelease
   82:             %managerstab $passwdmin);
   83: 
   84: my (%badServerCache, $memcache, %courselogs, %accesshash, %domainrolehash,
   85:     %userrolehash, $processmarker, $dumpcount, %coursedombuf,
   86:     %coursenumbuf, %coursehombuf, %coursedescrbuf, %courseinstcodebuf,
   87:     %courseownerbuf, %coursetypebuf,$locknum);
   88: 
   89: use IO::Socket;
   90: use GDBM_File;
   91: use HTML::LCParser;
   92: use Fcntl qw(:flock);
   93: use Storable qw(thaw nfreeze);
   94: use Time::HiRes qw( sleep gettimeofday tv_interval );
   95: use Cache::Memcached;
   96: use Digest::MD5;
   97: use Math::Random;
   98: use File::MMagic;
   99: use Net::CIDR;
  100: use Sys::Hostname::FQDN();
  101: use LONCAPA qw(:DEFAULT :match);
  102: use LONCAPA::Configuration;
  103: use LONCAPA::lonmetadata;
  104: use LONCAPA::Lond;
  105: use LONCAPA::LWPReq;
  106: use LONCAPA::transliterate;
  107: 
  108: use File::Copy;
  109: 
  110: my $readit;
  111: my $max_connection_retries = 20;     # Or some such value.
  112: 
  113: require Exporter;
  114: 
  115: our @ISA = qw (Exporter);
  116: our @EXPORT = qw(%env);
  117: 
  118: 
  119: # ------------------------------------ Logging (parameters, docs, slots, roles)
  120: {
  121:     my $logid;
  122:     sub write_log {
  123: 	my ($context,$hash_name,$storehash,$delflag,$uname,$udom,$cnum,$cdom)=@_;
  124:         if ($context eq 'course') {
  125:             if (($cnum eq '') || ($cdom eq '')) {
  126:                 $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
  127:                 $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
  128:             }
  129:         }
  130: 	$logid ++;
  131:         my $now = time();
  132: 	my $id=$now.'00000'.$$.'00000'.$logid;
  133:         my $ip = &get_requestor_ip();
  134:         my $logentry = { 
  135:                           $id => {
  136:                                    'exe_uname' => $env{'user.name'},
  137:                                    'exe_udom'  => $env{'user.domain'},
  138:                                    'exe_time'  => $now,
  139:                                    'exe_ip'    => $ip,
  140:                                    'delflag'   => $delflag,
  141:                                    'logentry'  => $storehash,
  142:                                    'uname'     => $uname,
  143:                                    'udom'      => $udom,
  144:                                   }
  145:                        };
  146: 	return &put('nohist_'.$hash_name,$logentry,$cdom,$cnum);
  147:     }
  148: }
  149: 
  150: sub logtouch {
  151:     my $execdir=$perlvar{'lonDaemons'};
  152:     unless (-e "$execdir/logs/lonnet.log") {	
  153: 	open(my $fh,">>","$execdir/logs/lonnet.log");
  154: 	close $fh;
  155:     }
  156:     my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
  157:     chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
  158: }
  159: 
  160: sub logthis {
  161:     my $message=shift;
  162:     my $execdir=$perlvar{'lonDaemons'};
  163:     my $now=time;
  164:     my $local=localtime($now);
  165:     if (open(my $fh,">>","$execdir/logs/lonnet.log")) {
  166: 	my $logstring = $local. " ($$): ".$message."\n"; # Keep any \'s in string.
  167: 	print $fh $logstring;
  168: 	close($fh);
  169:     }
  170:     return 1;
  171: }
  172: 
  173: sub logperm {
  174:     my $message=shift;
  175:     my $execdir=$perlvar{'lonDaemons'};
  176:     my $now=time;
  177:     my $local=localtime($now);
  178:     if (open(my $fh,">>","$execdir/logs/lonnet.perm.log")) {
  179: 	print $fh "$now:$message:$local\n";
  180: 	close($fh);
  181:     }
  182:     return 1;
  183: }
  184: 
  185: sub create_connection {
  186:     my ($hostname,$lonid) = @_;
  187:     my $client=IO::Socket::UNIX->new(Peer    => $perlvar{'lonSockCreate'},
  188: 				     Type    => SOCK_STREAM,
  189: 				     Timeout => 10);
  190:     return 0 if (!$client);
  191:     print $client (join(':',$hostname,$lonid,&machine_ids($hostname),$loncaparevs{$lonid})."\n");
  192:     my $result = <$client>;
  193:     chomp($result);
  194:     return 1 if ($result eq 'done');
  195:     return 0;
  196: }
  197: 
  198: sub get_server_timezone {
  199:     my ($cnum,$cdom) = @_;
  200:     my $home=&homeserver($cnum,$cdom);
  201:     if ($home ne 'no_host') {
  202:         my $cachetime = 24*3600;
  203:         my ($timezone,$cached)=&is_cached_new('servertimezone',$home);
  204:         if (defined($cached)) {
  205:             return $timezone;
  206:         } else {
  207:             my $timezone = &reply('servertimezone',$home);
  208:             return &do_cache_new('servertimezone',$home,$timezone,$cachetime);
  209:         }
  210:     }
  211: }
  212: 
  213: sub get_server_distarch {
  214:     my ($lonhost,$ignore_cache) = @_;
  215:     if (defined($lonhost)) {
  216:         if (!defined(&hostname($lonhost))) {
  217:             return;
  218:         }
  219:         my $cachetime = 12*3600;
  220:         if (!$ignore_cache) {
  221:             my ($distarch,$cached)=&is_cached_new('serverdistarch',$lonhost);
  222:             if (defined($cached)) {
  223:                 return $distarch;
  224:             }
  225:         }
  226:         my $rep = &reply('serverdistarch',$lonhost);
  227:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
  228:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
  229:                 $rep eq '') {
  230:             return &do_cache_new('serverdistarch',$lonhost,$rep,$cachetime);
  231:         }
  232:     }
  233:     return;
  234: }
  235: 
  236: sub get_servercerts_info {
  237:     my ($lonhost,$hostname,$context) = @_;
  238:     return if ($lonhost eq '');
  239:     if ($hostname eq '') {
  240:         $hostname = &hostname($lonhost);
  241:     }
  242:     return if ($hostname eq '');
  243:     my ($rep,$uselocal);
  244:     if ($context eq 'install') {
  245:         $uselocal = 1;
  246:     } elsif (grep { $_ eq $lonhost } &current_machine_ids()) {
  247:         $uselocal = 1;
  248:     }
  249:     if (($context ne 'cgi') && ($context ne 'install') && ($uselocal)) {
  250:         my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
  251:         if ($distro eq '') {
  252:             $uselocal = 0;
  253:         } elsif ($distro =~ /^(?:centos|redhat|scientific)(\d+)$/) {
  254:             if ($1 < 6) {
  255:                 $uselocal = 0;
  256:             }
  257:         }  elsif ($distro =~ /^(?:sles)(\d+)$/) {
  258:             if ($1 < 12) {
  259:                 $uselocal = 0;
  260:             }
  261:         }
  262:     }
  263:     if ($uselocal) {
  264:         $rep = LONCAPA::Lond::server_certs(\%perlvar,$lonhost,$hostname);
  265:     } else {
  266:         $rep=&reply('servercerts',$lonhost);
  267:     }
  268:     my ($result,%returnhash);
  269:     if (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
  270:         ($rep eq 'unknown_cmd')) {
  271:         $result = $rep;
  272:     } else {
  273:         $result = 'ok';
  274:         my @pairs=split(/\&/,$rep);
  275:         foreach my $item (@pairs) {
  276:             my ($key,$value)=split(/=/,$item,2);
  277:             my $what = &unescape($key);
  278:             $returnhash{$what}=&thaw_unescape($value);
  279:         }
  280:     }
  281:     return ($result,\%returnhash);
  282: }
  283: 
  284: sub get_server_loncaparev {
  285:     my ($dom,$lonhost,$ignore_cache,$caller) = @_;
  286:     if (defined($lonhost)) {
  287:         if (!defined(&hostname($lonhost))) {
  288:             undef($lonhost);
  289:         }
  290:     }
  291:     if (!defined($lonhost)) {
  292:         if (defined(&domain($dom,'primary'))) {
  293:             $lonhost=&domain($dom,'primary');
  294:             if ($lonhost eq 'no_host') {
  295:                 undef($lonhost);
  296:             }
  297:         }
  298:     }
  299:     if (defined($lonhost)) {
  300:         my $cachetime = 12*3600;
  301:         if (!$ignore_cache) {
  302:             my ($loncaparev,$cached)=&is_cached_new('serverloncaparev',$lonhost);
  303:             if (defined($cached)) {
  304:                 return $loncaparev;
  305:             }
  306:         }
  307:         my ($answer,$loncaparev);
  308:         my @ids=&current_machine_ids();
  309:         if (grep(/^\Q$lonhost\E$/,@ids)) {
  310:             $answer = $perlvar{'lonVersion'};
  311:             if ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
  312:                 $loncaparev = $1;
  313:             }
  314:         } else {
  315:             $answer = &reply('serverloncaparev',$lonhost);
  316:             if (($answer eq 'unknown_cmd') || ($answer eq 'con_lost')) {
  317:                 if ($caller eq 'loncron') {
  318:                     my $hostname = &hostname($lonhost);
  319:                     my $protocol = $protocol{$lonhost};
  320:                     $protocol = 'http' if ($protocol ne 'https');
  321:                     my $url = $protocol.'://'.$hostname.'/adm/about.html';
  322:                     my $request=new HTTP::Request('GET',$url);
  323:                     my $response=&LONCAPA::LWPReq::makerequest($lonhost,$request,'',\%perlvar,4,1);
  324:                     unless ($response->is_error()) {
  325:                         my $content = $response->content;
  326:                         if ($content =~ /<p>VERSION\:\s*([\w.\-]+)<\/p>/) {
  327:                             $loncaparev = $1;
  328:                         }
  329:                     }
  330:                 } else {
  331:                     $loncaparev = $loncaparevs{$lonhost};
  332:                 }
  333:             } elsif ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
  334:                 $loncaparev = $1;
  335:             }
  336:         }
  337:         return &do_cache_new('serverloncaparev',$lonhost,$loncaparev,$cachetime);
  338:     }
  339: }
  340: 
  341: sub get_server_homeID {
  342:     my ($hostname,$ignore_cache,$caller) = @_;
  343:     unless ($ignore_cache) {
  344:         my ($serverhomeID,$cached)=&is_cached_new('serverhomeID',$hostname);
  345:         if (defined($cached)) {
  346:             return $serverhomeID;
  347:         }
  348:     }
  349:     my $cachetime = 12*3600;
  350:     my $serverhomeID;
  351:     if ($caller eq 'loncron') { 
  352:         my @machine_ids = &machine_ids($hostname);
  353:         foreach my $id (@machine_ids) {
  354:             my $response = &reply('serverhomeID',$id);
  355:             unless (($response eq 'unknown_cmd') || ($response eq 'con_lost')) {
  356:                 $serverhomeID = $response;
  357:                 last;
  358:             }
  359:         }
  360:         if ($serverhomeID eq '') {
  361:             $serverhomeID = $machine_ids[-1];
  362:         }
  363:     } else {
  364:         $serverhomeID = $serverhomeIDs{$hostname};
  365:     }
  366:     return &do_cache_new('serverhomeID',$hostname,$serverhomeID,$cachetime);
  367: }
  368: 
  369: sub get_remote_globals {
  370:     my ($lonhost,$whathash,$ignore_cache) = @_;
  371:     my ($result,%returnhash,%whatneeded);
  372:     if (ref($whathash) eq 'HASH') {
  373:         foreach my $what (sort(keys(%{$whathash}))) {
  374:             my $hashid = $lonhost.'-'.$what;
  375:             my ($response,$cached);
  376:             unless ($ignore_cache) {
  377:                 ($response,$cached)=&is_cached_new('lonnetglobal',$hashid);
  378:             }
  379:             if (defined($cached)) {
  380:                 $returnhash{$what} = $response;
  381:             } else {
  382:                 $whatneeded{$what} = 1;
  383:             }
  384:         }
  385:         if (keys(%whatneeded) == 0) {
  386:             $result = 'ok';
  387:         } else {
  388:             my $requested = &freeze_escape(\%whatneeded);
  389:             my $rep=&reply('readlonnetglobal:'.$requested,$lonhost);
  390:             if (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
  391:                 ($rep eq 'unknown_cmd')) {
  392:                 $result = $rep;
  393:             } else {
  394:                 $result = 'ok';
  395:                 my @pairs=split(/\&/,$rep);
  396:                 foreach my $item (@pairs) {
  397:                     my ($key,$value)=split(/=/,$item,2);
  398:                     my $what = &unescape($key);
  399:                     my $hashid = $lonhost.'-'.$what;
  400:                     $returnhash{$what}=&thaw_unescape($value);
  401:                     &do_cache_new('lonnetglobal',$hashid,$returnhash{$what},600);
  402:                 }
  403:             }
  404:         }
  405:     }
  406:     return ($result,\%returnhash);
  407: }
  408: 
  409: sub remote_devalidate_cache {
  410:     my ($lonhost,$cachekeys) = @_;
  411:     my $items;
  412:     return unless (ref($cachekeys) eq 'ARRAY');
  413:     my $cachestr = join('&',@{$cachekeys});
  414:     my $response = &reply('devalidatecache:'.&escape($cachestr),$lonhost);
  415:     return $response;
  416: }
  417: 
  418: sub sign_lti {
  419:     my ($cdom,$cnum,$crsdef,$type,$context,$url,$ltinum,$keynum,$paramsref,$inforef) = @_;
  420:     my $chome;
  421:     if (&domain($cdom) ne '') {
  422:         if ($crsdef) {
  423:             $chome = &homeserver($cnum,$cdom);
  424:         } else {
  425:             $chome = &domain($cdom,'primary');
  426:         }
  427:     }
  428:     if ($cdom && $chome && ($chome ne 'no_host')) {
  429:         if ((ref($paramsref) eq 'HASH') &&
  430:             (ref($inforef) eq 'HASH')) {
  431:             my $rep;
  432:             if (grep { $_ eq $chome } &current_machine_ids()) {
  433:                 # domain information is hosted on this machine
  434:                 $rep =
  435:                     &LONCAPA::Lond::sign_lti_payload($cdom,$cnum,$crsdef,$type,
  436:                                                      $context,$url,$ltinum,$keynum,
  437:                                                      $perlvar{'lonVersion'},
  438:                                                      $paramsref,$inforef);
  439:                 if (ref($rep) eq 'HASH') {
  440:                     return ('ok',$rep);
  441:                 }
  442:             } else {
  443:                 my ($escurl,$params,$info);
  444:                 $escurl = &escape($url);
  445:                 if (ref($paramsref) eq 'HASH') {
  446:                     $params = &freeze_escape($paramsref);
  447:                 }
  448:                 if (ref($inforef) eq 'HASH') {
  449:                     $info = &freeze_escape($inforef);
  450:                 }
  451:                 $rep=&reply("encrypt:signlti:$cdom:$cnum:$crsdef:$type:$context:$escurl:$ltinum:$keynum:$params:$info",$chome);
  452:             }
  453:             if (($rep eq '') || ($rep =~ /^con_lost|error|no_such_host|unknown_cmd/i)) {
  454:                 return ();
  455:             } elsif (($inforef->{'respfmt'} eq 'to_post_body') ||
  456:                      ($inforef->{'respfmt'} eq 'to_authorization_header')) {
  457:                 return ('ok',$rep);
  458:             } else {
  459:                 my %returnhash;
  460:                 foreach my $item (split(/\&/,$rep)) {
  461:                     my ($name,$value)=split(/\=/,$item);
  462:                     $returnhash{&unescape($name)}=&thaw_unescape($value);
  463:                 }
  464:                 return('ok',\%returnhash);
  465:             }
  466:         } else {
  467:             return ();
  468:         }
  469:     } else {
  470:         return ();
  471:         &logthis("sign_lti failed - no homeserver and/or domain ($cdom) ($chome)");
  472:     }
  473: }
  474: 
  475: # -------------------------------------------------- Non-critical communication
  476: sub subreply {
  477:     my ($cmd,$server)=@_;
  478:     my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
  479:     #
  480:     #  With loncnew process trimming, there's a timing hole between lonc server
  481:     #  process exit and the master server picking up the listen on the AF_UNIX
  482:     #  socket.  In that time interval, a lock file will exist:
  483: 
  484:     my $lockfile=$peerfile.".lock";
  485:     while (-e $lockfile) {	# Need to wait for the lockfile to disappear.
  486: 	sleep(0.1);
  487:     }
  488:     # At this point, either a loncnew parent is listening or an old lonc
  489:     # or loncnew child is listening so we can connect or everything's dead.
  490:     #
  491:     #   We'll give the connection a few tries before abandoning it.  If
  492:     #   connection is not possible, we'll con_lost back to the client.
  493:     #   
  494:     my $client;
  495:     for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
  496: 	$client=IO::Socket::UNIX->new(Peer    =>"$peerfile",
  497: 				      Type    => SOCK_STREAM,
  498: 				      Timeout => 10);
  499: 	if ($client) {
  500: 	    last;		# Connected!
  501: 	} else {
  502: 	    &create_connection(&hostname($server),$server);
  503: 	}
  504:         sleep(0.1);	# Try again later if failed connection.
  505:     }
  506:     my $answer;
  507:     if ($client) {
  508: 	print $client "sethost:$server:$cmd\n";
  509: 	$answer=<$client>;
  510: 	if (!$answer) { $answer="con_lost"; }
  511: 	chomp($answer);
  512:     } else {
  513: 	$answer = 'con_lost';	# Failed connection.
  514:     }
  515:     return $answer;
  516: }
  517: 
  518: sub reply {
  519:     my ($cmd,$server)=@_;
  520:     unless (defined(&hostname($server))) { return 'no_such_host'; }
  521:     my $answer=subreply($cmd,$server);
  522:     if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
  523:         my $logged = $cmd;
  524:         if ($cmd =~ /^encrypt:([^:]+):/) {
  525:             my $subcmd = $1;
  526:             if (($subcmd eq 'auth') || ($subcmd eq 'passwd') ||
  527:                 ($subcmd eq 'changeuserauth') || ($subcmd eq 'makeuser') ||
  528:                 ($subcmd eq 'putdom') || ($subcmd eq 'autoexportgrades') ||
  529:                 ($subcmd eq 'put')) {
  530:                 (undef,undef,my @rest) = split(/:/,$cmd);
  531:                 if (($subcmd eq 'auth') || ($subcmd eq 'putdom')) {
  532:                     splice(@rest,2,1,'Hidden');
  533:                 } elsif ($subcmd eq 'passwd') {
  534:                     splice(@rest,2,2,('Hidden','Hidden'));
  535:                 } elsif (($subcmd eq 'changeuserauth') || ($subcmd eq 'makeuser') ||
  536:                          ($subcmd eq 'autoexportgrades') || ($subcmd eq 'put')) {
  537:                     splice(@rest,3,1,'Hidden');
  538:                 }
  539:                 $logged = join(':',('encrypt:'.$subcmd,@rest));
  540:             }
  541:         }
  542:         &logthis("<font color=\"blue\">WARNING:".
  543:                  " $logged to $server returned $answer</font>");
  544:     }
  545:     return $answer;
  546: }
  547: 
  548: # ----------------------------------------------------------- Send USR1 to lonc
  549: 
  550: sub reconlonc {
  551:     my ($lonid) = @_;
  552:     if ($lonid) {
  553:         my $hostname = &hostname($lonid);
  554: 	my $peerfile="$perlvar{'lonSockDir'}/$hostname";
  555: 	if ($hostname && -e $peerfile) {
  556: 	    &logthis("Trying to reconnect lonc for $lonid ($hostname)");
  557: 	    my $client=IO::Socket::UNIX->new(Peer    => $peerfile,
  558: 					     Type    => SOCK_STREAM,
  559: 					     Timeout => 10);
  560: 	    if ($client) {
  561: 		print $client ("reset_retries\n");
  562: 		my $answer=<$client>;
  563: 		#reset just this one.
  564: 	    }
  565: 	}
  566: 	return;
  567:     }
  568: 
  569:     &logthis("Trying to reconnect lonc");
  570:     my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
  571:     if (open(my $fh,"<",$loncfile)) {
  572: 	my $loncpid=<$fh>;
  573:         chomp($loncpid);
  574:         if (kill 0 => $loncpid) {
  575: 	    &logthis("lonc at pid $loncpid responding, sending USR1");
  576:             kill USR1 => $loncpid;
  577:             sleep 1;
  578:         } else {
  579: 	    &logthis(
  580:                "<font color=\"blue\">WARNING:".
  581:                " lonc at pid $loncpid not responding, giving up</font>");
  582:         }
  583:     } else {
  584: 	&logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
  585:     }
  586: }
  587: 
  588: # ------------------------------------------------------ Critical communication
  589: 
  590: sub critical {
  591:     my ($cmd,$server)=@_;
  592:     unless (&hostname($server)) {
  593:         &logthis("<font color=\"blue\">WARNING:".
  594:                " Critical message to unknown server ($server)</font>");
  595:         return 'no_such_host';
  596:     }
  597:     my $answer=reply($cmd,$server);
  598:     if ($answer eq 'con_lost') {
  599: 	&reconlonc($server);
  600: 	my $answer=reply($cmd,$server);
  601:         if ($answer eq 'con_lost') {
  602:             my $now=time;
  603:             my $middlename=$cmd;
  604:             $middlename=substr($middlename,0,16);
  605:             $middlename=~s/\W//g;
  606:             my $dfilename=
  607:       "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
  608:             $dumpcount++;
  609:             {
  610: 		my $dfh;
  611: 		if (open($dfh,">",$dfilename)) {
  612: 		    print $dfh "$cmd\n"; 
  613: 		    close($dfh);
  614: 		}
  615:             }
  616:             sleep 1;
  617:             my $wcmd='';
  618:             {
  619: 		my $dfh;
  620: 		if (open($dfh,"<",$dfilename)) {
  621: 		    $wcmd=<$dfh>; 
  622: 		    close($dfh);
  623: 		}
  624:             }
  625:             chomp($wcmd);
  626:             if ($wcmd eq $cmd) {
  627: 		&logthis("<font color=\"blue\">WARNING: ".
  628:                          "Connection buffer $dfilename: $cmd</font>");
  629:                 &logperm("D:$server:$cmd");
  630: 	        return 'con_delayed';
  631:             } else {
  632:                 &logthis("<font color=\"red\">CRITICAL:"
  633:                         ." Critical connection failed: $server $cmd</font>");
  634:                 &logperm("F:$server:$cmd");
  635:                 return 'con_failed';
  636:             }
  637:         }
  638:     }
  639:     return $answer;
  640: }
  641: 
  642: # ------------------------------------------- check if return value is an error
  643: 
  644: sub error {
  645:     my ($result) = @_;
  646:     if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
  647: 	if ($2 == 2) { return undef; }
  648: 	return $1;
  649:     }
  650:     return undef;
  651: }
  652: 
  653: sub convert_and_load_session_env {
  654:     my ($lonidsdir,$handle)=@_;
  655:     my @profile;
  656:     {
  657: 	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
  658: 	if (!$opened) {
  659: 	    return 0;
  660: 	}
  661: 	flock($idf,LOCK_SH);
  662: 	@profile=<$idf>;
  663: 	close($idf);
  664:     }
  665:     my %temp_env;
  666:     foreach my $line (@profile) {
  667: 	if ($line !~ m/=/) {
  668: 	    return 0;
  669: 	}
  670: 	chomp($line);
  671: 	my ($envname,$envvalue)=split(/=/,$line,2);
  672: 	$temp_env{&unescape($envname)} = &unescape($envvalue);
  673:     }
  674:     unlink("$lonidsdir/$handle.id");
  675:     if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
  676: 	    0640)) {
  677: 	%disk_env = %temp_env;
  678: 	@env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
  679: 	untie(%disk_env);
  680:     }
  681:     return 1;
  682: }
  683: 
  684: # ------------------------------------------- Transfer profile into environment
  685: my $env_loaded;
  686: sub transfer_profile_to_env {
  687:     my ($lonidsdir,$handle,$force_transfer) = @_;
  688:     if (!$force_transfer && $env_loaded) { return; } 
  689: 
  690:     if (!defined($lonidsdir)) {
  691: 	$lonidsdir = $perlvar{'lonIDsDir'};
  692:     }
  693:     if (!defined($handle)) {
  694:         ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
  695:     }
  696: 
  697:     my $convert;
  698:     {
  699:     	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
  700: 	if (!$opened) {
  701: 	    return;
  702: 	}
  703: 	flock($idf,LOCK_SH);
  704: 	if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
  705: 		&GDBM_READER(),0640)) {
  706: 	    @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
  707: 	    untie(%disk_env);
  708: 	} else {
  709: 	    $convert = 1;
  710: 	}
  711:     }
  712:     if ($convert) {
  713: 	if (!&convert_and_load_session_env($lonidsdir,$handle)) {
  714: 	    &logthis("Failed to load session, or convert session.");
  715: 	}
  716:     }
  717: 
  718:     my %remove;
  719:     while ( my $envname = each(%env) ) {
  720:         if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
  721:             if ($time < time-300) {
  722:                 $remove{$key}++;
  723:             }
  724:         }
  725:     }
  726: 
  727:     $env{'user.environment'} = "$lonidsdir/$handle.id";
  728:     $env_loaded=1;
  729:     foreach my $expired_key (keys(%remove)) {
  730:         &delenv($expired_key);
  731:     }
  732: }
  733: 
  734: # ---------------------------------------------------- Check for valid session 
  735: sub check_for_valid_session {
  736:     my ($r,$name,$userhashref,$domref) = @_;
  737:     my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
  738:     my ($lonidsdir,$linkname,$pubname,$secure,$lonid);
  739:     if ($name eq 'lonDAV') {
  740:         $lonidsdir=$r->dir_config('lonDAVsessDir');
  741:     } else {
  742:         $lonidsdir=$r->dir_config('lonIDsDir');
  743:         if ($name eq '') {
  744:             $name = 'lonID';
  745:         }
  746:     }
  747:     if ($name eq 'lonID') {
  748:         $secure = 'lonSID';
  749:         $linkname = 'lonLinkID';
  750:         $pubname = 'lonPubID';
  751:         if (exists($cookies{$secure})) {
  752:             $lonid=$cookies{$secure};
  753:         } elsif (exists($cookies{$name})) {
  754:             $lonid=$cookies{$name};
  755:         } elsif ((exists($cookies{$linkname})) && ($ENV{'SERVER_PORT'} != 443)) {
  756:             $lonid=$cookies{$linkname};
  757:         } elsif (exists($cookies{$pubname})) {
  758:             $lonid=$cookies{$pubname};
  759:         }
  760:     } else {
  761:         $lonid=$cookies{$name};
  762:     }
  763:     return undef if (!$lonid);
  764: 
  765:     my $handle=&LONCAPA::clean_handle($lonid->value);
  766:     if (-l "$lonidsdir/$handle.id") {
  767:         my $link = readlink("$lonidsdir/$handle.id");
  768:         if ((-e $link) && ($link =~ m{^\Q$lonidsdir\E/(.+)\.id$})) {
  769:             $handle = $1;
  770:         }
  771:     }
  772:     if (!-e "$lonidsdir/$handle.id") {
  773:         if ((ref($domref)) && ($name eq 'lonID') && 
  774:             ($handle =~ /^($match_username)\_\d+\_($match_domain)\_(.+)$/)) {
  775:             my ($possuname,$possudom,$possuhome) = ($1,$2,$3);
  776:             if ((&domain($possudom) ne '') && (&homeserver($possuname,$possudom) eq $possuhome)) {
  777:                 $$domref = $possudom;
  778:             }
  779:         }
  780:         return undef;
  781:     }
  782: 
  783:     my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
  784:     return undef if (!$opened);
  785: 
  786:     flock($idf,LOCK_SH);
  787:     my %disk_env;
  788:     if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
  789: 	    &GDBM_READER(),0640)) {
  790: 	return undef;	
  791:     }
  792: 
  793:     if (!defined($disk_env{'user.name'})
  794: 	|| !defined($disk_env{'user.domain'})) {
  795:         untie(%disk_env);
  796: 	return undef;
  797:     }
  798: 
  799:     if (ref($userhashref) eq 'HASH') {
  800:         $userhashref->{'name'} = $disk_env{'user.name'};
  801:         $userhashref->{'domain'} = $disk_env{'user.domain'};
  802:         if ($disk_env{'request.role'}) {
  803:             $userhashref->{'role'} = $disk_env{'request.role'};
  804:         }
  805:         $userhashref->{'lti'} = $disk_env{'request.lti.login'};
  806:         if ($userhashref->{'lti'}) {
  807:             $userhashref->{'ltitarget'} = $disk_env{'request.lti.target'};
  808:             $userhashref->{'ltiuri'} = $disk_env{'request.lti.uri'};
  809:         }
  810:     }
  811:     untie(%disk_env);
  812: 
  813:     return $handle;
  814: }
  815: 
  816: sub timed_flock {
  817:     my ($file,$lock_type) = @_;
  818:     my $failed=0;
  819:     eval {
  820: 	local $SIG{__DIE__}='DEFAULT';
  821: 	local $SIG{ALRM}=sub {
  822: 	    $failed=1;
  823: 	    die("failed lock");
  824: 	};
  825: 	alarm(13);
  826: 	flock($file,$lock_type);
  827: 	alarm(0);
  828:     };
  829:     if ($failed) {
  830: 	return undef;
  831:     } else {
  832: 	return 1;
  833:     }
  834: }
  835: 
  836: sub get_sessionfile_vars {
  837:     my ($handle,$lonidsdir,$storearr) = @_;
  838:     my %returnhash;
  839:     unless (ref($storearr) eq 'ARRAY') {
  840:         return %returnhash;
  841:     }
  842:     if (-l "$lonidsdir/$handle.id") {
  843:         my $link = readlink("$lonidsdir/$handle.id");
  844:         if ((-e $link) && ($link =~ m{^\Q$lonidsdir\E/(.+)\.id$})) {
  845:             $handle = $1;
  846:         }
  847:     }
  848:     if ((-e "$lonidsdir/$handle.id") &&
  849:         ($handle =~ /^($match_username)\_\d+\_($match_domain)\_(.+)$/)) {
  850:         my ($possuname,$possudom,$possuhome) = ($1,$2,$3);
  851:         if ((&domain($possudom) ne '') && (&homeserver($possuname,$possudom) eq $possuhome)) {
  852:             if (open(my $idf,'+<',"$lonidsdir/$handle.id")) {
  853:                 flock($idf,LOCK_SH);
  854:                 if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
  855:                         &GDBM_READER(),0640)) {
  856:                     foreach my $item (@{$storearr}) {
  857:                         $returnhash{$item} = $disk_env{$item};
  858:                     }
  859:                     untie(%disk_env);
  860:                 }
  861:             }
  862:         }
  863:     }
  864:     return %returnhash;
  865: }
  866: 
  867: # ---------------------------------------------------------- Append Environment
  868: 
  869: sub appenv {
  870:     my ($newenv,$roles) = @_;
  871:     if (ref($newenv) eq 'HASH') {
  872:         foreach my $key (keys(%{$newenv})) {
  873:             my $refused = 0;
  874: 	    if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
  875:                 $refused = 1;
  876:                 if (ref($roles) eq 'ARRAY') {
  877:                     my ($type,$role) = ($key =~ m{^user\.(role|priv)\.(.+?)\./});
  878:                     if (grep(/^\Q$role\E$/,@{$roles})) {
  879:                         $refused = 0;
  880:                     }
  881:                 }
  882:             }
  883:             if ($refused) {
  884:                 &logthis("<font color=\"blue\">WARNING: ".
  885:                          "Attempt to modify environment ".$key." to ".$newenv->{$key}
  886:                          .'</font>');
  887: 	        delete($newenv->{$key});
  888:             } else {
  889:                 $env{$key}=$newenv->{$key};
  890:             }
  891:         }
  892:         my $lonids = $perlvar{'lonIDsDir'};
  893:         if ($env{'user.environment'} =~ m{^\Q$lonids/\E$match_username\_\d+\_$match_domain\_[\w\-.]+\.id$}) {
  894:             my $opened = open(my $env_file,'+<',$env{'user.environment'});
  895:             if ($opened
  896: 	        && &timed_flock($env_file,LOCK_EX)
  897: 	        &&
  898: 	        tie(my %disk_env,'GDBM_File',$env{'user.environment'},
  899: 	            (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
  900: 	        while (my ($key,$value) = each(%{$newenv})) {
  901: 	            $disk_env{$key} = $value;
  902: 	        }
  903: 	        untie(%disk_env);
  904:             }
  905:         }
  906:     }
  907:     return 'ok';
  908: }
  909: # ----------------------------------------------------- Delete from Environment
  910: 
  911: sub delenv {
  912:     my ($delthis,$regexp,$roles) = @_;
  913:     if (($delthis=~/^user\.role/) || ($delthis=~/^user\.priv/)) {
  914:         my $refused = 1;
  915:         if (ref($roles) eq 'ARRAY') {
  916:             my ($type,$role) = ($delthis =~ /^user\.(role|priv)\.([^.]+)\./);
  917:             if (grep(/^\Q$role\E$/,@{$roles})) {
  918:                 $refused = 0;
  919:             }
  920:         }
  921:         if ($refused) {
  922:             &logthis("<font color=\"blue\">WARNING: ".
  923:                      "Attempt to delete from environment ".$delthis);
  924:             return 'error';
  925:         }
  926:     }
  927:     my $opened = open(my $env_file,'+<',$env{'user.environment'});
  928:     if ($opened
  929: 	&& &timed_flock($env_file,LOCK_EX)
  930: 	&&
  931: 	tie(my %disk_env,'GDBM_File',$env{'user.environment'},
  932: 	    (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
  933: 	foreach my $key (keys(%disk_env)) {
  934: 	    if ($regexp) {
  935:                 if ($key=~/^$delthis/) {
  936:                     delete($env{$key});
  937:                     delete($disk_env{$key});
  938:                 } 
  939:             } else {
  940:                 if ($key=~/^\Q$delthis\E/) {
  941: 		    delete($env{$key});
  942: 		    delete($disk_env{$key});
  943: 	        }
  944:             }
  945: 	}
  946: 	untie(%disk_env);
  947:     }
  948:     return 'ok';
  949: }
  950: 
  951: sub get_env_multiple {
  952:     my ($name) = @_;
  953:     my @values;
  954:     if (defined($env{$name})) {
  955:         # exists is it an array
  956:         if (ref($env{$name})) {
  957:             @values=@{ $env{$name} };
  958:         } else {
  959:             $values[0]=$env{$name};
  960:         }
  961:     }
  962:     return(@values);
  963: }
  964: 
  965: # ------------------------------------------------------------------- Locking
  966: 
  967: sub set_lock {
  968:     my ($text)=@_;
  969:     $locknum++;
  970:     my $id=$$.'-'.$locknum;
  971:     &appenv({'session.locks' => $env{'session.locks'}.','.$id,
  972:              'session.lock.'.$id => $text});
  973:     return $id;
  974: }
  975: 
  976: sub get_locks {
  977:     my $num=0;
  978:     my %texts=();
  979:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
  980:        if ($lock=~/\w/) {
  981:           $num++;
  982:           $texts{$lock}=$env{'session.lock.'.$lock};
  983:        }
  984:    }
  985:    return ($num,%texts);
  986: }
  987: 
  988: sub remove_lock {
  989:     my ($id)=@_;
  990:     my $newlocks='';
  991:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
  992:        if (($lock=~/\w/) && ($lock ne $id)) {
  993:           $newlocks.=','.$lock;
  994:        }
  995:     }
  996:     &appenv({'session.locks' => $newlocks});
  997:     &delenv('session.lock.'.$id);
  998: }
  999: 
 1000: sub remove_all_locks {
 1001:     my $activelocks=$env{'session.locks'};
 1002:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
 1003:        if ($lock=~/\w/) {
 1004:           &remove_lock($lock);
 1005:        }
 1006:     }
 1007: }
 1008: 
 1009: 
 1010: # ------------------------------------------ Find out current server userload
 1011: sub userload {
 1012:     my $numusers=0;
 1013:     {
 1014: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
 1015: 	my $filename;
 1016: 	my $curtime=time;
 1017: 	while ($filename=readdir(LONIDS)) {
 1018: 	    next if ($filename eq '.' || $filename eq '..');
 1019: 	    next if ($filename =~ /publicuser_\d+\.id/);
 1020:             next if ($filename =~ /^[a-f0-9]+_linked\.id$/);
 1021: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
 1022: 	    if ($curtime-$mtime < 1800) { $numusers++; }
 1023: 	}
 1024: 	closedir(LONIDS);
 1025:     }
 1026:     my $userloadpercent=0;
 1027:     my $maxuserload=$perlvar{'lonUserLoadLim'};
 1028:     if ($maxuserload) {
 1029: 	$userloadpercent=100*$numusers/$maxuserload;
 1030:     }
 1031:     $userloadpercent=sprintf("%.2f",$userloadpercent);
 1032:     return $userloadpercent;
 1033: }
 1034: 
 1035: # ------------------------------ Find server with least workload from spare.tab
 1036: 
 1037: sub spareserver {
 1038:     my ($r,$loadpercent,$userloadpercent,$want_server_name,$udom) = @_;
 1039:     my $spare_server;
 1040:     if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
 1041:     my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent 
 1042:                                                      :  $userloadpercent;
 1043:     my ($uint_dom,$remotesessions);
 1044:     if (($udom ne '') && (&domain($udom) ne '')) {
 1045:         my $uprimary_id = &domain($udom,'primary');
 1046:         $uint_dom = &internet_dom($uprimary_id);
 1047:         my %udomdefaults = &get_domain_defaults($udom);
 1048:         $remotesessions = $udomdefaults{'remotesessions'};
 1049:     }
 1050:     my $spareshash = &this_host_spares($udom);
 1051:     if (ref($spareshash) eq 'HASH') {
 1052:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
 1053:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
 1054:                 next unless (&spare_can_host($udom,$uint_dom,$remotesessions,
 1055:                                              $try_server));
 1056: 	        ($spare_server, $lowest_load) =
 1057: 	            &compare_server_load($try_server, $spare_server, $lowest_load);
 1058:             }
 1059:         }
 1060: 
 1061:         my $found_server = ($spare_server ne '' && $lowest_load < 100);
 1062: 
 1063:         if (!$found_server) {
 1064:             if (ref($spareshash->{'default'}) eq 'ARRAY') { 
 1065: 	        foreach my $try_server (@{ $spareshash->{'default'} }) {
 1066:                     next unless (&spare_can_host($udom,$uint_dom,
 1067:                                                  $remotesessions,$try_server));
 1068: 	            ($spare_server, $lowest_load) =
 1069: 		        &compare_server_load($try_server, $spare_server, $lowest_load);
 1070:                 }
 1071: 	    }
 1072:         }
 1073:     }
 1074: 
 1075:     if (!$want_server_name) {
 1076:         if (defined($spare_server)) {
 1077:             my $hostname = &hostname($spare_server);
 1078:             if (defined($hostname)) {
 1079:                 my $protocol = 'http';
 1080:                 if ($protocol{$spare_server} eq 'https') {
 1081:                     $protocol = $protocol{$spare_server};
 1082:                 }
 1083:                 my $alias = &use_proxy_alias($r,$spare_server);
 1084:                 $hostname = $alias if ($alias ne '');
 1085: 	        $spare_server = $protocol.'://'.$hostname;
 1086:             }
 1087:         }
 1088:     }
 1089:     return $spare_server;
 1090: }
 1091: 
 1092: sub compare_server_load {
 1093:     my ($try_server, $spare_server, $lowest_load, $required) = @_;
 1094: 
 1095:     if ($required) {
 1096:         my ($reqdmajor,$reqdminor) = ($required =~ /^(\d+)\.(\d+)$/);
 1097:         my $remoterev = &get_server_loncaparev(undef,$try_server);
 1098:         my ($major,$minor) = ($remoterev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
 1099:         if (($major eq '' && $minor eq '') ||
 1100:             (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)))) {
 1101:             return ($spare_server,$lowest_load);
 1102:         }
 1103:     }
 1104: 
 1105:     my $loadans     = &reply('load',    $try_server);
 1106:     my $userloadans = &reply('userload',$try_server);
 1107: 
 1108:     if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
 1109: 	return ($spare_server, $lowest_load); #didn't get a number from the server
 1110:     }
 1111: 
 1112:     my $load;
 1113:     if ($loadans =~ /\d/) {
 1114: 	if ($userloadans =~ /\d/) {
 1115: 	    #both are numbers, pick the bigger one
 1116: 	    $load = ($loadans > $userloadans) ? $loadans 
 1117: 		                              : $userloadans;
 1118: 	} else {
 1119: 	    $load = $loadans;
 1120: 	}
 1121:     } else {
 1122: 	$load = $userloadans;
 1123:     }
 1124: 
 1125:     if (($load =~ /\d/) && ($load < $lowest_load)) {
 1126: 	$spare_server = $try_server;
 1127: 	$lowest_load  = $load;
 1128:     }
 1129:     return ($spare_server,$lowest_load);
 1130: }
 1131: 
 1132: # --------------------------- ask offload servers if user already has a session
 1133: sub find_existing_session {
 1134:     my ($udom,$uname) = @_;
 1135:     my $spareshash = &this_host_spares($udom);
 1136:     if (ref($spareshash) eq 'HASH') {
 1137:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
 1138:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
 1139:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
 1140:             }
 1141:         }
 1142:         if (ref($spareshash->{'default'}) eq 'ARRAY') {
 1143:             foreach my $try_server (@{ $spareshash->{'default'} }) {
 1144:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
 1145:             }
 1146:         }
 1147:     }
 1148:     return;
 1149: }
 1150: 
 1151: sub delusersession {
 1152:     my ($lonid,$udom,$uname) = @_;
 1153:     my $uprimary_id = &domain($udom,'primary');
 1154:     my $uintdom = &internet_dom($uprimary_id);
 1155:     my $intdom = &internet_dom($lonid);
 1156:     my $serverhomedom = &host_domain($lonid);
 1157:     if (($uintdom ne '') && ($uintdom eq $intdom)) {
 1158:         return &reply(join(':','delusersession',
 1159:                             map {&escape($_)} ($udom,$uname)),$lonid);
 1160:     }
 1161:     return;
 1162: }
 1163: 
 1164: # check if user's browser sent load balancer cookie and server still has session
 1165: # and is not overloaded.
 1166: sub check_for_balancer_cookie {
 1167:     my ($r,$update_mtime) = @_;
 1168:     my ($otherserver,$cookie);
 1169:     my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
 1170:     if (exists($cookies{'balanceID'})) {
 1171:         my $balid = $cookies{'balanceID'};
 1172:         $cookie=&LONCAPA::clean_handle($balid->value);
 1173:         my $balancedir=$r->dir_config('lonBalanceDir');
 1174:         if ((-d $balancedir) && (-e "$balancedir/$cookie.id")) {
 1175:             if ($cookie =~ /^($match_domain)_($match_username)_[a-f0-9]+$/) {
 1176:                 my ($possudom,$possuname) = ($1,$2);
 1177:                 my $has_session = 0;
 1178:                 if ((&domain($possudom) ne '') &&
 1179:                     (&homeserver($possuname,$possudom) ne 'no_host')) {
 1180:                     my $try_server;
 1181:                     my $opened = open(my $idf,'+<',"$balancedir/$cookie.id");
 1182:                     if ($opened) {
 1183:                         flock($idf,LOCK_SH);
 1184:                         while (my $line = <$idf>) {
 1185:                             chomp($line);
 1186:                             if (&hostname($line) ne '') {
 1187:                                 $try_server = $line;
 1188:                                 last;
 1189:                             }
 1190:                         }
 1191:                         close($idf);
 1192:                         if (($try_server) &&
 1193:                             (&has_user_session($try_server,$possudom,$possuname))) {
 1194:                             my $lowest_load = 30000;
 1195:                             ($otherserver,$lowest_load) =
 1196:                                 &compare_server_load($try_server,undef,$lowest_load);
 1197:                             if ($otherserver ne '' && $lowest_load < 100) {
 1198:                                 $has_session = 1;
 1199:                             } else {
 1200:                                 undef($otherserver);
 1201:                             }
 1202:                         }
 1203:                     }
 1204:                 }
 1205:                 if ($has_session) {
 1206:                     if ($update_mtime) {
 1207:                         my $atime = my $mtime = time;
 1208:                         utime($atime,$mtime,"$balancedir/$cookie.id");
 1209:                     }
 1210:                 } else {
 1211:                     unlink("$balancedir/$cookie.id");
 1212:                 }
 1213:             }
 1214:         }
 1215:     }
 1216:     return ($otherserver,$cookie);
 1217: }
 1218: 
 1219: sub updatebalcookie {
 1220:     my ($cookie,$balancer,$lastentry)=@_;
 1221:     if ($cookie =~ /^($match_domain)\_($match_username)\_[a-f0-9]{32}$/) {
 1222:         my ($udom,$uname) = ($1,$2);
 1223:         my $uprimary_id = &domain($udom,'primary');
 1224:         my $uintdom = &internet_dom($uprimary_id);
 1225:         my $intdom = &internet_dom($balancer);
 1226:         my $serverhomedom = &host_domain($balancer);
 1227:         if (($uintdom ne '') && ($uintdom eq $intdom)) {
 1228:             return &reply('updatebalcookie:'.&escape($cookie).':'.&escape($lastentry),$balancer);
 1229:         }
 1230:     }
 1231:     return;
 1232: }
 1233: 
 1234: sub delbalcookie {
 1235:     my ($cookie,$balancer) =@_;
 1236:     if ($cookie =~ /^($match_domain)\_($match_username)\_[a-f0-9]{32}$/) {
 1237:         my ($udom,$uname) = ($1,$2);
 1238:         my $uprimary_id = &domain($udom,'primary');
 1239:         my $uintdom = &internet_dom($uprimary_id);
 1240:         my $intdom = &internet_dom($balancer);
 1241:         my $serverhomedom = &host_domain($balancer);
 1242:         if (($uintdom ne '') && ($uintdom eq $intdom)) {
 1243:             return &reply('delbalcookie:'.&escape($cookie),$balancer);
 1244:         }
 1245:     }
 1246: }
 1247: 
 1248: # -------------------------------- ask if server already has a session for user
 1249: sub has_user_session {
 1250:     my ($lonid,$udom,$uname) = @_;
 1251:     my $result = &reply(join(':','userhassession',
 1252: 			     map {&escape($_)} ($udom,$uname)),$lonid);
 1253:     return 1 if ($result eq 'ok');
 1254: 
 1255:     return 0;
 1256: }
 1257: 
 1258: # --------- determine least loaded server in a user's domain which allows login
 1259: 
 1260: sub choose_server {
 1261:     my ($udom,$checkloginvia,$required,$skiploadbal) = @_;
 1262:     my %domconfhash = &Apache::loncommon::get_domainconf($udom);
 1263:     my %servers = &get_servers($udom);
 1264:     my $lowest_load = 30000;
 1265:     my ($login_host,$hostname,$portal_path,$isredirect,$balancers);
 1266:     if ($skiploadbal) {
 1267:         ($balancers,my $cached)=&is_cached_new('loadbalancing',$udom);
 1268:         unless (defined($cached)) {
 1269:             my $cachetime = 60*60*24;
 1270:             my %domconfig =
 1271:                 &get_dom('configuration',['loadbalancing'],$udom);
 1272:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
 1273:                 $balancers = &do_cache_new('loadbalancing',$udom,$domconfig{'loadbalancing'},
 1274:                                            $cachetime);
 1275:             }
 1276:         }
 1277:     }
 1278:     foreach my $lonhost (keys(%servers)) {
 1279:         if ($skiploadbal) {
 1280:             if (ref($balancers) eq 'HASH') {
 1281:                 next if (exists($balancers->{$lonhost}));
 1282:             }
 1283:         }
 1284:         my $loginvia;
 1285:         if ($checkloginvia) {
 1286:             $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
 1287:             if ($loginvia) {
 1288:                 my ($server,$path) = split(/:/,$loginvia);
 1289:                 ($login_host, $lowest_load) =
 1290:                     &compare_server_load($server, $login_host, $lowest_load, $required);
 1291:                 if ($login_host eq $server) {
 1292:                     $portal_path = $path;
 1293:                     $isredirect = 1;
 1294:                 }
 1295:             } else {
 1296:                 ($login_host, $lowest_load) =
 1297:                     &compare_server_load($lonhost, $login_host, $lowest_load, $required);
 1298:                 if ($login_host eq $lonhost) {
 1299:                     $portal_path = '';
 1300:                     $isredirect = ''; 
 1301:                 }
 1302:             }
 1303:         } else {
 1304:             ($login_host, $lowest_load) =
 1305:                 &compare_server_load($lonhost, $login_host, $lowest_load, $required);
 1306:         }
 1307:     }
 1308:     if ($login_host ne '') {
 1309:         $hostname = &hostname($login_host);
 1310:     }
 1311:     return ($login_host,$hostname,$portal_path,$isredirect,$lowest_load);
 1312: }
 1313: 
 1314: sub get_course_sessions {
 1315:     my ($cnum,$cdom,$lastactivity) = @_;
 1316:     my %servers = &internet_dom_servers($cdom);
 1317:     my %returnhash;
 1318:     foreach my $server (sort(keys(%servers))) {
 1319:         my $rep = &reply("coursesessions:$cdom:$cnum:$lastactivity",$server);
 1320:         my @pairs=split(/\&/,$rep);
 1321:         unless (($rep eq 'unknown_cmd') || ($rep =~ /^error/)) {
 1322:             foreach my $item (@pairs) {
 1323:                 my ($key,$value)=split(/=/,$item,2);
 1324:                 $key = &unescape($key);
 1325:                 next if ($key =~ /^error: 2 /);
 1326:                 if (exists($returnhash{$key})) {
 1327:                     next if ($value < $returnhash{$key});
 1328:                 }
 1329:                 $returnhash{$key}=$value;
 1330:             }
 1331:         }
 1332:     }
 1333:     return %returnhash;
 1334: }
 1335: 
 1336: # --------------------------------------------- Try to change a user's password
 1337: 
 1338: sub changepass {
 1339:     my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
 1340:     $currentpass = &escape($currentpass);
 1341:     $newpass     = &escape($newpass);
 1342:     my $lonhost = $perlvar{'lonHostID'};
 1343:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
 1344: 		       $server);
 1345:     if (! $answer) {
 1346: 	&logthis("No reply on password change request to $server ".
 1347: 		 "by $uname in domain $udom.");
 1348:     } elsif ($answer =~ "^ok") {
 1349:         &logthis("$uname in $udom successfully changed their password ".
 1350: 		 "on $server.");
 1351:     } elsif ($answer =~ "^pwchange_failure") {
 1352: 	&logthis("$uname in $udom was unable to change their password ".
 1353: 		 "on $server.  The action was blocked by either lcpasswd ".
 1354: 		 "or pwchange");
 1355:     } elsif ($answer =~ "^non_authorized") {
 1356:         &logthis("$uname in $udom did not get their password correct when ".
 1357: 		 "attempting to change it on $server.");
 1358:     } elsif ($answer =~ "^auth_mode_error") {
 1359:         &logthis("$uname in $udom attempted to change their password despite ".
 1360: 		 "not being locally or internally authenticated on $server.");
 1361:     } elsif ($answer =~ "^unknown_user") {
 1362:         &logthis("$uname in $udom attempted to change their password ".
 1363: 		 "on $server but were unable to because $server is not ".
 1364: 		 "their home server.");
 1365:     } elsif ($answer =~ "^refused") {
 1366: 	&logthis("$server refused to change $uname in $udom password because ".
 1367: 		 "it was sent an unencrypted request to change the password.");
 1368:     } elsif ($answer =~ "invalid_client") {
 1369:         &logthis("$server refused to change $uname in $udom password because ".
 1370:                  "it was a reset by e-mail originating from an invalid server.");
 1371:     } elsif ($answer =~ "^prioruse") {
 1372:        &logthis("$server refused to change $uname in $udom password because ".
 1373:                 "the password had been used before");
 1374:     }
 1375:     return $answer;
 1376: }
 1377: 
 1378: # ----------------------- Try to determine user's current authentication scheme
 1379: 
 1380: sub queryauthenticate {
 1381:     my ($uname,$udom)=@_;
 1382:     my $uhome=&homeserver($uname,$udom);
 1383:     if ((!$uhome) || ($uhome eq 'no_host')) {
 1384: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
 1385: 	return 'no_host';
 1386:     }
 1387:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
 1388:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
 1389: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
 1390:     }
 1391:     return $answer;
 1392: }
 1393: 
 1394: # --------- Try to authenticate user from domain's lib servers (first this one)
 1395: 
 1396: sub authenticate {
 1397:     my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
 1398:     $upass=&escape($upass);
 1399:     $uname= &LONCAPA::clean_username($uname);
 1400:     my $uhome=&homeserver($uname,$udom,1);
 1401:     my $newhome;
 1402:     if ((!$uhome) || ($uhome eq 'no_host')) {
 1403: # Maybe the machine was offline and only re-appeared again recently?
 1404:         &reconlonc();
 1405: # One more
 1406: 	$uhome=&homeserver($uname,$udom,1);
 1407:         if (($uhome eq 'no_host') && $checkdefauth) {
 1408:             if (defined(&domain($udom,'primary'))) {
 1409:                 $newhome=&domain($udom,'primary');
 1410:             }
 1411:             if ($newhome ne '') {
 1412:                 $uhome = $newhome;
 1413:             }
 1414:         }
 1415: 	if ((!$uhome) || ($uhome eq 'no_host')) {
 1416: 	    &logthis("User $uname at $udom is unknown in authenticate");
 1417: 	    return 'no_host';
 1418:         }
 1419:     }
 1420:     my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
 1421:     if ($answer eq 'authorized') {
 1422:         if ($newhome) {
 1423:             &logthis("User $uname at $udom authorized by $uhome, but needs account");
 1424:             return 'no_account_on_host'; 
 1425:         } else {
 1426:             &logthis("User $uname at $udom authorized by $uhome");
 1427:             return $uhome;
 1428:         }
 1429:     }
 1430:     if ($answer eq 'non_authorized') {
 1431: 	&logthis("User $uname at $udom rejected by $uhome");
 1432: 	return 'no_host';
 1433:     }
 1434:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
 1435:     return 'no_host';
 1436: }
 1437: 
 1438: sub can_switchserver {
 1439:     my ($udom,$home) = @_;
 1440:     my ($canswitch,@intdoms);
 1441:     my $internet_names = &get_internet_names($home);
 1442:     if (ref($internet_names) eq 'ARRAY') {
 1443:         @intdoms = @{$internet_names};
 1444:     }
 1445:     my $uint_dom = &internet_dom(&domain($udom,'primary'));
 1446:     if ($uint_dom ne '' && grep(/^\Q$uint_dom\E$/,@intdoms)) {
 1447:         $canswitch = 1;
 1448:     } else {
 1449:          my $serverhomeID = &get_server_homeID(&hostname($home));
 1450:          my $serverhomedom = &host_domain($serverhomeID);
 1451:          my %defdomdefaults = &get_domain_defaults($serverhomedom);
 1452:          my %udomdefaults = &get_domain_defaults($udom);
 1453:          my $remoterev = &get_server_loncaparev('',$home);
 1454:          $canswitch = &can_host_session($udom,$home,$remoterev,
 1455:                                         $udomdefaults{'remotesessions'},
 1456:                                         $defdomdefaults{'hostedsessions'});
 1457:     }
 1458:     return $canswitch;
 1459: }
 1460: 
 1461: sub can_host_session {
 1462:     my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
 1463:     my $canhost = 1;
 1464:     my $host_idn = &internet_dom($lonhost);
 1465:     if (ref($remotesessions) eq 'HASH') {
 1466:         if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
 1467:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
 1468:                 $canhost = 0;
 1469:             } else {
 1470:                 $canhost = 1;
 1471:             }
 1472:         }
 1473:         if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
 1474:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
 1475:                 $canhost = 1;
 1476:             } else {
 1477:                 $canhost = 0;
 1478:             }
 1479:         }
 1480:         if ($canhost) {
 1481:             if ($remotesessions->{'version'} ne '') {
 1482:                 my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
 1483:                 if ($reqmajor ne '' && $reqminor ne '') {
 1484:                     if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
 1485:                         my $major = $1;
 1486:                         my $minor = $2;
 1487:                         if (($major < $reqmajor ) ||
 1488:                             (($major == $reqmajor) && ($minor < $reqminor))) {
 1489:                             $canhost = 0;
 1490:                         }
 1491:                     } else {
 1492:                         $canhost = 0;
 1493:                     }
 1494:                 }
 1495:             }
 1496:         }
 1497:     }
 1498:     if ($canhost) {
 1499:         if (ref($hostedsessions) eq 'HASH') {
 1500:             my $uprimary_id = &domain($udom,'primary');
 1501:             my $uint_dom = &internet_dom($uprimary_id);
 1502:             if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
 1503:                 if (($uint_dom ne '') && 
 1504:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'excludedomain'}}))) {
 1505:                     $canhost = 0;
 1506:                 } else {
 1507:                     $canhost = 1;
 1508:                 }
 1509:             }
 1510:             if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
 1511:                 if (($uint_dom ne '') && 
 1512:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'includedomain'}}))) {
 1513:                     $canhost = 1;
 1514:                 } else {
 1515:                     $canhost = 0;
 1516:                 }
 1517:             }
 1518:         }
 1519:     }
 1520:     return $canhost;
 1521: }
 1522: 
 1523: sub spare_can_host {
 1524:     my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
 1525:     my $canhost=1;
 1526:     my $try_server_hostname = &hostname($try_server);
 1527:     my $serverhomeID = &get_server_homeID($try_server_hostname);
 1528:     my $serverhomedom = &host_domain($serverhomeID);
 1529:     my %defdomdefaults = &get_domain_defaults($serverhomedom);
 1530:     if (ref($defdomdefaults{'offloadnow'}) eq 'HASH') {
 1531:         if ($defdomdefaults{'offloadnow'}{$try_server}) {
 1532:             $canhost = 0;
 1533:         }
 1534:     }
 1535:     if ($canhost) {
 1536:         if (ref($defdomdefaults{'offloadoth'}) eq 'HASH') {
 1537:             if ($defdomdefaults{'offloadoth'}{$try_server}) {
 1538:                 unless (&shared_institution($udom,$try_server)) {
 1539:                     $canhost = 0;
 1540:                 }
 1541:             }
 1542:         }
 1543:     }
 1544:     if (($canhost) && ($uint_dom)) {
 1545:         my @intdoms;
 1546:         my $internet_names = &get_internet_names($try_server);
 1547:         if (ref($internet_names) eq 'ARRAY') {
 1548:             @intdoms = @{$internet_names};
 1549:         }
 1550:         unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
 1551:             my $remoterev = &get_server_loncaparev(undef,$try_server);
 1552:             $canhost = &can_host_session($udom,$try_server,$remoterev,
 1553:                                          $remotesessions,
 1554:                                          $defdomdefaults{'hostedsessions'});
 1555:         }
 1556:     }
 1557:     return $canhost;
 1558: }
 1559: 
 1560: sub this_host_spares {
 1561:     my ($dom) = @_;
 1562:     my ($dom_in_use,$lonhost_in_use,$result);
 1563:     my @hosts = &current_machine_ids();
 1564:     foreach my $lonhost (@hosts) {
 1565:         if (&host_domain($lonhost) eq $dom) {
 1566:             $dom_in_use = $dom;
 1567:             $lonhost_in_use = $lonhost;
 1568:             last;
 1569:         }
 1570:     }
 1571:     if ($dom_in_use ne '') {
 1572:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
 1573:     }
 1574:     if (ref($result) ne 'HASH') {
 1575:         $lonhost_in_use = $perlvar{'lonHostID'};
 1576:         $dom_in_use = &host_domain($lonhost_in_use);
 1577:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
 1578:         if (ref($result) ne 'HASH') {
 1579:             $result = \%spareid;
 1580:         }
 1581:     }
 1582:     return $result;
 1583: }
 1584: 
 1585: sub spares_for_offload  {
 1586:     my ($dom_in_use,$lonhost_in_use) = @_;
 1587:     my ($result,$cached)=&is_cached_new('spares',$dom_in_use);
 1588:     if (defined($cached)) {
 1589:         return $result;
 1590:     } else {
 1591:         my $cachetime = 60*60*24;
 1592:         my %domconfig =
 1593:             &get_dom('configuration',['usersessions'],$dom_in_use);
 1594:         if (ref($domconfig{'usersessions'}) eq 'HASH') {
 1595:             if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
 1596:                 if (ref($domconfig{'usersessions'}{'spares'}{$lonhost_in_use}) eq 'HASH') {
 1597:                     return &do_cache_new('spares',$dom_in_use,$domconfig{'usersessions'}{'spares'}{$lonhost_in_use},$cachetime);
 1598:                 }
 1599:             }
 1600:         }
 1601:     }
 1602:     return;
 1603: }
 1604: 
 1605: sub get_lonbalancer_config {
 1606:     my ($servers) = @_;
 1607:     my ($currbalancer,$currtargets);
 1608:     if (ref($servers) eq 'HASH') {
 1609:         foreach my $server (keys(%{$servers})) {
 1610:             my %what = (
 1611:                          spareid => 1,
 1612:                          perlvar => 1,
 1613:                        );
 1614:             my ($result,$returnhash) = &get_remote_globals($server,\%what);
 1615:             if ($result eq 'ok') {
 1616:                 if (ref($returnhash) eq 'HASH') {
 1617:                     if (ref($returnhash->{'perlvar'}) eq 'HASH') {
 1618:                         if ($returnhash->{'perlvar'}->{'lonBalancer'} eq 'yes') {
 1619:                             $currbalancer = $server;
 1620:                             $currtargets = {};
 1621:                             if (ref($returnhash->{'spareid'}) eq 'HASH') {
 1622:                                 if (ref($returnhash->{'spareid'}->{'primary'}) eq 'ARRAY') {
 1623:                                     $currtargets->{'primary'} = $returnhash->{'spareid'}->{'primary'};
 1624:                                 }
 1625:                                 if (ref($returnhash->{'spareid'}->{'default'}) eq 'ARRAY') {
 1626:                                     $currtargets->{'default'} = $returnhash->{'spareid'}->{'default'};
 1627:                                 }
 1628:                             }
 1629:                             last;
 1630:                         }
 1631:                     }
 1632:                 }
 1633:             }
 1634:         }
 1635:     }
 1636:     return ($currbalancer,$currtargets);
 1637: }
 1638: 
 1639: sub check_loadbalancing {
 1640:     my ($uname,$udom,$caller) = @_;
 1641:     my ($is_balancer,$currtargets,$currrules,$dom_in_use,$homeintdom,
 1642:         $rule_in_effect,$offloadto,$otherserver,$setcookie,$dom_balancers);
 1643:     my $lonhost = $perlvar{'lonHostID'};
 1644:     my @hosts = &current_machine_ids();
 1645:     my $uprimary_id = &domain($udom,'primary');
 1646:     my $uintdom = &internet_dom($uprimary_id);
 1647:     my $intdom = &internet_dom($lonhost);
 1648:     my $serverhomedom = &host_domain($lonhost);
 1649:     my $domneedscache;
 1650:     my $cachetime = 60*60*24;
 1651: 
 1652:     if (($uintdom ne '') && ($uintdom eq $intdom)) {
 1653:         $dom_in_use = $udom;
 1654:         $homeintdom = 1;
 1655:     } else {
 1656:         $dom_in_use = $serverhomedom;
 1657:     }
 1658:     my ($result,$cached)=&is_cached_new('loadbalancing',$dom_in_use);
 1659:     unless (defined($cached)) {
 1660:         my %domconfig =
 1661:             &get_dom('configuration',['loadbalancing'],$dom_in_use);
 1662:         if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
 1663:             $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
 1664:         } else {
 1665:             $domneedscache = $dom_in_use;
 1666:         }
 1667:     }
 1668:     if (ref($result) eq 'HASH') {
 1669:         ($is_balancer,$currtargets,$currrules,$setcookie,$dom_balancers) =
 1670:             &check_balancer_result($result,@hosts);
 1671:         if ($is_balancer) {
 1672:             if (ref($currrules) eq 'HASH') {
 1673:                 if ($homeintdom) {
 1674:                     if ($uname ne '') {
 1675:                         if (($currrules->{'_LC_adv'} ne '') || ($currrules->{'_LC_author'} ne '')) {
 1676:                             my ($is_adv,$is_author) = &is_advanced_user($udom,$uname);
 1677:                             if (($currrules->{'_LC_author'} ne '') && ($is_author)) {
 1678:                                 $rule_in_effect = $currrules->{'_LC_author'};
 1679:                             } elsif (($currrules->{'_LC_adv'} ne '') && ($is_adv)) {
 1680:                                 $rule_in_effect = $currrules->{'_LC_adv'}
 1681:                             }
 1682:                         }
 1683:                         if ($rule_in_effect eq '') {
 1684:                             my %userenv = &userenvironment($udom,$uname,'inststatus');
 1685:                             if ($userenv{'inststatus'} ne '') {
 1686:                                 my @statuses = map { &unescape($_); } split(/:/,$userenv{'inststatus'});
 1687:                                 my ($othertitle,$usertypes,$types) =
 1688:                                     &Apache::loncommon::sorted_inst_types($udom);
 1689:                                 if (ref($types) eq 'ARRAY') {
 1690:                                     foreach my $type (@{$types}) {
 1691:                                         if (grep(/^\Q$type\E$/,@statuses)) {
 1692:                                             if (exists($currrules->{$type})) {
 1693:                                                 $rule_in_effect = $currrules->{$type};
 1694:                                             }
 1695:                                         }
 1696:                                     }
 1697:                                 }
 1698:                             } else {
 1699:                                 if (exists($currrules->{'default'})) {
 1700:                                     $rule_in_effect = $currrules->{'default'};
 1701:                                 }
 1702:                             }
 1703:                         }
 1704:                     } else {
 1705:                         if (exists($currrules->{'default'})) {
 1706:                             $rule_in_effect = $currrules->{'default'};
 1707:                         }
 1708:                     }
 1709:                 } else {
 1710:                     if ($currrules->{'_LC_external'} ne '') {
 1711:                         $rule_in_effect = $currrules->{'_LC_external'};
 1712:                     }
 1713:                 }
 1714:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
 1715:                                                        $uname,$udom);
 1716:             }
 1717:         }
 1718:     } elsif (($homeintdom) && ($udom ne $serverhomedom)) {
 1719:         ($result,$cached)=&is_cached_new('loadbalancing',$serverhomedom);
 1720:         unless (defined($cached)) {
 1721:             my %domconfig =
 1722:                 &get_dom('configuration',['loadbalancing'],$serverhomedom);
 1723:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
 1724:                 $result = &do_cache_new('loadbalancing',$serverhomedom,$domconfig{'loadbalancing'},$cachetime);
 1725:             } else {
 1726:                 $domneedscache = $serverhomedom;
 1727:             }
 1728:         }
 1729:         if (ref($result) eq 'HASH') {
 1730:             ($is_balancer,$currtargets,$currrules,$setcookie,$dom_balancers) =
 1731:                 &check_balancer_result($result,@hosts);
 1732:             if ($is_balancer) {
 1733:                 if (ref($currrules) eq 'HASH') {
 1734:                     if ($currrules->{'_LC_internetdom'} ne '') {
 1735:                         $rule_in_effect = $currrules->{'_LC_internetdom'};
 1736:                     }
 1737:                 }
 1738:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
 1739:                                                        $uname,$udom);
 1740:             }
 1741:         } else {
 1742:             if ($perlvar{'lonBalancer'} eq 'yes') {
 1743:                 $is_balancer = 1;
 1744:                 $offloadto = &this_host_spares($dom_in_use);
 1745:             }
 1746:             unless (defined($cached)) {
 1747:                 $domneedscache = $serverhomedom;
 1748:             }
 1749:         }
 1750:     } else {
 1751:         if ($perlvar{'lonBalancer'} eq 'yes') {
 1752:             $is_balancer = 1;
 1753:             $offloadto = &this_host_spares($dom_in_use);
 1754:         }
 1755:         unless (defined($cached)) {
 1756:             $domneedscache = $serverhomedom;
 1757:         }
 1758:     }
 1759:     if ($domneedscache) {
 1760:         &do_cache_new('loadbalancing',$domneedscache,$is_balancer,$cachetime);
 1761:     }
 1762:     if (($is_balancer) && ($caller ne 'switchserver')) {
 1763:         my $lowest_load = 30000;
 1764:         if (ref($offloadto) eq 'HASH') {
 1765:             if (ref($offloadto->{'primary'}) eq 'ARRAY') {
 1766:                 foreach my $try_server (@{$offloadto->{'primary'}}) {
 1767:                     ($otherserver,$lowest_load) =
 1768:                         &compare_server_load($try_server,$otherserver,$lowest_load);
 1769:                 }
 1770:             }
 1771:             my $found_server = ($otherserver ne '' && $lowest_load < 100);
 1772: 
 1773:             if (!$found_server) {
 1774:                 if (ref($offloadto->{'default'}) eq 'ARRAY') {
 1775:                     foreach my $try_server (@{$offloadto->{'default'}}) {
 1776:                         ($otherserver,$lowest_load) =
 1777:                             &compare_server_load($try_server,$otherserver,$lowest_load);
 1778:                     }
 1779:                 }
 1780:             }
 1781:         } elsif (ref($offloadto) eq 'ARRAY') {
 1782:             if (@{$offloadto} == 1) {
 1783:                 $otherserver = $offloadto->[0];
 1784:             } elsif (@{$offloadto} > 1) {
 1785:                 foreach my $try_server (@{$offloadto}) {
 1786:                     ($otherserver,$lowest_load) =
 1787:                         &compare_server_load($try_server,$otherserver,$lowest_load);
 1788:                 }
 1789:             }
 1790:         }
 1791:         unless ($caller eq 'login') {
 1792:             if (($otherserver ne '') && (grep(/^\Q$otherserver\E$/,@hosts))) {
 1793:                 $is_balancer = 0;
 1794:                 if ($uname ne '' && $udom ne '') {
 1795:                     if (($env{'user.name'} eq $uname) && ($env{'user.domain'} eq $udom)) {
 1796:                         &appenv({'user.loadbalexempt'     => $lonhost,
 1797:                                  'user.loadbalcheck.time' => time});
 1798:                     }
 1799:                 }
 1800:             }
 1801:         }
 1802:     }
 1803:     if (($is_balancer) && (!$homeintdom)) {
 1804:         undef($setcookie);
 1805:     }
 1806:     return ($is_balancer,$otherserver,$setcookie,$offloadto,$dom_balancers);
 1807: }
 1808: 
 1809: sub check_balancer_result {
 1810:     my ($result,@hosts) = @_;
 1811:     my ($is_balancer,$currtargets,$currrules,$setcookie,$dom_balancers);
 1812:     if (ref($result) eq 'HASH') {
 1813:         if ($result->{'lonhost'} ne '') {
 1814:             my $currbalancer = $result->{'lonhost'};
 1815:             if (grep(/^\Q$currbalancer\E$/,@hosts)) {
 1816:                 $is_balancer = 1;
 1817:                 $currtargets = $result->{'targets'};
 1818:                 $currrules = $result->{'rules'};
 1819:             }
 1820:             $dom_balancers = $currbalancer;
 1821:         } else {
 1822:             if (keys(%{$result})) {
 1823:                 foreach my $key (keys(%{$result})) {
 1824:                     if (($key ne '') && (grep(/^\Q$key\E$/,@hosts)) &&
 1825:                         (ref($result->{$key}) eq 'HASH')) {
 1826:                         $is_balancer = 1;
 1827:                         $currrules = $result->{$key}{'rules'};
 1828:                         $currtargets = $result->{$key}{'targets'};
 1829:                         $setcookie = $result->{$key}{'cookie'};
 1830:                         last;
 1831:                     }
 1832:                 }
 1833:                 $dom_balancers = join(',',sort(keys(%{$result})));
 1834:             }
 1835:         }
 1836:     }
 1837:     return ($is_balancer,$currtargets,$currrules,$setcookie,$dom_balancers);
 1838: }
 1839: 
 1840: sub get_loadbalancer_targets {
 1841:     my ($rule_in_effect,$currtargets,$uname,$udom) = @_;
 1842:     my $offloadto;
 1843:     if ($rule_in_effect eq 'none') {
 1844:         return [$perlvar{'lonHostID'}];
 1845:     } elsif ($rule_in_effect eq '') {
 1846:         $offloadto = $currtargets;
 1847:     } else {
 1848:         if ($rule_in_effect eq 'homeserver') {
 1849:             my $homeserver = &homeserver($uname,$udom);
 1850:             if ($homeserver ne 'no_host') {
 1851:                 $offloadto = [$homeserver];
 1852:             }
 1853:         } elsif ($rule_in_effect eq 'externalbalancer') {
 1854:             my %domconfig =
 1855:                 &get_dom('configuration',['loadbalancing'],$udom);
 1856:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
 1857:                 if ($domconfig{'loadbalancing'}{'lonhost'} ne '') {
 1858:                     if (&hostname($domconfig{'loadbalancing'}{'lonhost'}) ne '') {
 1859:                         $offloadto = [$domconfig{'loadbalancing'}{'lonhost'}];
 1860:                     }
 1861:                 }
 1862:             } else {
 1863:                 my %servers = &internet_dom_servers($udom);
 1864:                 my ($remotebalancer,$remotetargets) = &get_lonbalancer_config(\%servers);
 1865:                 if (&hostname($remotebalancer) ne '') {
 1866:                     $offloadto = [$remotebalancer];
 1867:                 }
 1868:             }
 1869:         } elsif (&hostname($rule_in_effect) ne '') {
 1870:             $offloadto = [$rule_in_effect];
 1871:         }
 1872:     }
 1873:     return $offloadto;
 1874: }
 1875: 
 1876: sub internet_dom_servers {
 1877:     my ($dom) = @_;
 1878:     my (%uniqservers,%servers);
 1879:     my $primaryserver = &hostname(&domain($dom,'primary'));
 1880:     my @machinedoms = &machine_domains($primaryserver);
 1881:     foreach my $mdom (@machinedoms) {
 1882:         my %currservers = %servers;
 1883:         my %server = &get_servers($mdom);
 1884:         %servers = (%currservers,%server);
 1885:     }
 1886:     my %by_hostname;
 1887:     foreach my $id (keys(%servers)) {
 1888:         push(@{$by_hostname{$servers{$id}}},$id);
 1889:     }
 1890:     foreach my $hostname (sort(keys(%by_hostname))) {
 1891:         if (@{$by_hostname{$hostname}} > 1) {
 1892:             my $match = 0;
 1893:             foreach my $id (@{$by_hostname{$hostname}}) {
 1894:                 if (&host_domain($id) eq $dom) {
 1895:                     $uniqservers{$id} = $hostname;
 1896:                     $match = 1;
 1897:                 }
 1898:             }
 1899:             unless ($match) {
 1900:                 $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
 1901:             }
 1902:         } else {
 1903:             $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
 1904:         }
 1905:     }
 1906:     return %uniqservers;
 1907: }
 1908: 
 1909: sub trusted_domains {
 1910:     my ($cmdtype,$calldom) = @_;
 1911:     my ($trusted,$untrusted);
 1912:     if (&domain($calldom) eq '') {
 1913:         return ($trusted,$untrusted);
 1914:     }
 1915:     unless ($cmdtype =~ /^(content|shared|enroll|coaurem|othcoau|domroles|catalog|reqcrs|msg)$/) {
 1916:         return ($trusted,$untrusted);
 1917:     }
 1918:     my $callprimary = &domain($calldom,'primary');
 1919:     my $intcalldom = &internet_dom($callprimary);
 1920:     if ($intcalldom eq '') {
 1921:         return ($trusted,$untrusted);
 1922:     }
 1923: 
 1924:     my ($trustconfig,$cached)=&is_cached_new('trust',$calldom);
 1925:     unless (defined($cached)) {
 1926:         my %domconfig = &get_dom('configuration',['trust'],$calldom);
 1927:         &do_cache_new('trust',$calldom,$domconfig{'trust'},3600);
 1928:         $trustconfig = $domconfig{'trust'};
 1929:     }
 1930:     if (ref($trustconfig)) {
 1931:         my (%possexc,%possinc,@allexc,@allinc); 
 1932:         if (ref($trustconfig->{$cmdtype}) eq 'HASH') {
 1933:             if (ref($trustconfig->{$cmdtype}->{'exc'}) eq 'ARRAY') {
 1934:                 map { $possexc{$_} = 1; } @{$trustconfig->{$cmdtype}->{'exc'}}; 
 1935:             }
 1936:             if (ref($trustconfig->{$cmdtype}->{'inc'}) eq 'ARRAY') {
 1937:                 $possinc{$intcalldom} = 1;
 1938:                 map { $possinc{$_} = 1; } @{$trustconfig->{$cmdtype}->{'inc'}};
 1939:             }
 1940:         }
 1941:         if (keys(%possexc)) {
 1942:             if (keys(%possinc)) {
 1943:                 foreach my $key (sort(keys(%possexc))) {
 1944:                     next if ($key eq $intcalldom);
 1945:                     unless ($possinc{$key}) {
 1946:                         push(@allexc,$key);
 1947:                     }
 1948:                 }
 1949:             } else {
 1950:                 @allexc = sort(keys(%possexc));
 1951:             }
 1952:         }
 1953:         if (keys(%possinc)) {
 1954:             $possinc{$intcalldom} = 1;
 1955:             @allinc = sort(keys(%possinc));
 1956:         }
 1957:         if ((@allexc > 0) || (@allinc > 0)) {
 1958:             my %doms_by_intdom;
 1959:             my %allintdoms = &all_host_intdom();
 1960:             my %alldoms = &all_host_domain();
 1961:             foreach my $key (%allintdoms) {
 1962:                 if (ref($doms_by_intdom{$allintdoms{$key}}) eq 'ARRAY') {
 1963:                     unless (grep(/^\Q$alldoms{$key}\E$/,@{$doms_by_intdom{$allintdoms{$key}}})) {
 1964:                         push(@{$doms_by_intdom{$allintdoms{$key}}},$alldoms{$key});
 1965:                     }
 1966:                 } else {
 1967:                     $doms_by_intdom{$allintdoms{$key}} = [$alldoms{$key}]; 
 1968:                 }
 1969:             }
 1970:             foreach my $exc (@allexc) {
 1971:                 if (ref($doms_by_intdom{$exc}) eq 'ARRAY') {
 1972:                     push(@{$untrusted},@{$doms_by_intdom{$exc}});
 1973:                 }
 1974:             }
 1975:             foreach my $inc (@allinc) {
 1976:                 if (ref($doms_by_intdom{$inc}) eq 'ARRAY') {
 1977:                     push(@{$trusted},@{$doms_by_intdom{$inc}});
 1978:                 }
 1979:             }
 1980:         }
 1981:     }
 1982:     return ($trusted,$untrusted);
 1983: }
 1984: 
 1985: sub will_trust {
 1986:     my ($cmdtype,$domain,$possdom) = @_;
 1987:     return 1 if ($domain eq $possdom);
 1988:     my ($trustedref,$untrustedref) = &trusted_domains($cmdtype,$possdom);
 1989:     my $willtrust; 
 1990:     if ((ref($trustedref) eq 'ARRAY') && (@{$trustedref} > 0)) {
 1991:         if (grep(/^\Q$domain\E$/,@{$trustedref})) {
 1992:             $willtrust = 1;
 1993:         }
 1994:     } elsif ((ref($untrustedref) eq 'ARRAY') && (@{$untrustedref} > 0)) {
 1995:         unless (grep(/^\Q$domain\E$/,@{$untrustedref})) {
 1996:             $willtrust = 1;
 1997:         }
 1998:     } else {
 1999:         $willtrust = 1;
 2000:     }
 2001:     return $willtrust;
 2002: }
 2003: 
 2004: # ---------------------- Find the homebase for a user from domain's lib servers
 2005: 
 2006: my %homecache;
 2007: sub homeserver {
 2008:     my ($uname,$udom,$ignoreBadCache)=@_;
 2009:     my $index="$uname:$udom";
 2010: 
 2011:     if (exists($homecache{$index})) { return $homecache{$index}; }
 2012: 
 2013:     my %servers = &get_servers($udom,'library');
 2014:     foreach my $tryserver (keys(%servers)) {
 2015:         next if ($ignoreBadCache ne 'true' && 
 2016: 		 exists($badServerCache{$tryserver}));
 2017: 
 2018: 	my $answer=reply("home:$udom:$uname",$tryserver);
 2019: 	if ($answer eq 'found') {
 2020: 	    delete($badServerCache{$tryserver}); 
 2021: 	    return $homecache{$index}=$tryserver;
 2022: 	} elsif ($answer eq 'no_host') {
 2023: 	    $badServerCache{$tryserver}=1;
 2024: 	}
 2025:     }    
 2026:     return 'no_host';
 2027: }
 2028: 
 2029: # ----- Find the usernames behind a list of student/employee IDs or clicker IDs
 2030: 
 2031: sub idget {
 2032:     my ($udom,$idsref,$namespace)=@_;
 2033:     my %returnhash=();
 2034:     my @ids=(); 
 2035:     if (ref($idsref) eq 'ARRAY') {
 2036:         @ids = @{$idsref};
 2037:     } else {
 2038:         return %returnhash; 
 2039:     }
 2040:     if ($namespace eq '') {
 2041:         $namespace = 'ids';
 2042:     }
 2043:     
 2044:     my %servers = &get_servers($udom,'library');
 2045:     foreach my $tryserver (keys(%servers)) {
 2046: 	my $idlist=join('&', map { &escape($_); } @ids);
 2047: 	if ($namespace eq 'ids') {
 2048: 	    $idlist=~tr/A-Z/a-z/;
 2049: 	}
 2050: 	my $reply;
 2051: 	if ($namespace eq 'ids') {
 2052: 	    $reply=&reply("idget:$udom:".$idlist,$tryserver);
 2053: 	} else {
 2054: 	    $reply=&reply("getdom:$udom:$namespace:$idlist",$tryserver);
 2055: 	}
 2056: 	my @answer=();
 2057: 	if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
 2058: 	    @answer=split(/\&/,$reply);
 2059: 	}                    ;
 2060: 	my $i;
 2061: 	for ($i=0;$i<=$#ids;$i++) {
 2062: 	    if ($answer[$i]) {
 2063: 		$returnhash{$ids[$i]}=&unescape($answer[$i]);
 2064: 	    }
 2065: 	}
 2066:     }
 2067:     return %returnhash;
 2068: }
 2069: 
 2070: # ------------------------------------- Find the IDs behind a list of usernames
 2071: 
 2072: sub idrget {
 2073:     my ($udom,@unames)=@_;
 2074:     my %returnhash=();
 2075:     foreach my $uname (@unames) {
 2076:         $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
 2077:     }
 2078:     return %returnhash;
 2079: }
 2080: 
 2081: # Store away a list of names and associated student/employee IDs or clicker IDs
 2082: 
 2083: sub idput {
 2084:     my ($udom,$idsref,$uhom,$namespace)=@_;
 2085:     my %servers=();
 2086:     my %ids=();
 2087:     my %byid = ();
 2088:     if (ref($idsref) eq 'HASH') {
 2089:         %ids=%{$idsref};
 2090:     }
 2091:     if ($namespace eq '') {
 2092:         $namespace = 'ids'; 
 2093:     }
 2094:     foreach my $uname (keys(%ids)) {
 2095: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
 2096:         if ($uhom eq '') {
 2097:             $uhom=&homeserver($uname,$udom);
 2098:         }
 2099:         if ($uhom ne 'no_host') {
 2100:             my $esc_unam=&escape($uname);
 2101:             if ($namespace eq 'ids') {
 2102:                 my $id=&escape($ids{$uname});
 2103:                 $id=~tr/A-Z/a-z/;
 2104:                 my $esc_unam=&escape($uname);
 2105:                 $servers{$uhom}.=$id.'='.$esc_unam.'&';
 2106:             } else {
 2107:                 my @currids = split(/,/,$ids{$uname});
 2108:                 foreach my $id (@currids) {
 2109:                     $byid{$uhom}{$id} .= $uname.',';
 2110:                 }
 2111:             }
 2112:         }
 2113:     }
 2114:     if ($namespace eq 'clickers') {
 2115:         foreach my $server (keys(%byid)) {
 2116:             if (ref($byid{$server}) eq 'HASH') {
 2117:                 foreach my $id (keys(%{$byid{$server}})) {
 2118:                     $byid{$server} =~ s/,$//;
 2119:                     $servers{$uhom}.=&escape($id).'='.&escape($byid{$server}).'&'; 
 2120:                 }
 2121:             }
 2122:         }
 2123:     }
 2124:     foreach my $server (keys(%servers)) {
 2125:         $servers{$server} =~ s/\&$//;
 2126:         if ($namespace eq 'ids') {     
 2127:             &critical('idput:'.$udom.':'.$servers{$server},$server);
 2128:         } else {
 2129:             &critical('updateclickers:'.$udom.':add:'.$servers{$server},$server);
 2130:         }
 2131:     }
 2132: }
 2133: 
 2134: # ------------- Delete unwanted student/employee IDs or clicker IDs from domain
 2135: 
 2136: sub iddel {
 2137:     my ($udom,$idshashref,$uhome,$namespace)=@_;
 2138:     my %result=();
 2139:     my %ids=();
 2140:     my %byid = ();
 2141:     if (ref($idshashref) eq 'HASH') {
 2142:         %ids=%{$idshashref};
 2143:     } else {
 2144:         return %result;
 2145:     }
 2146:     if ($namespace eq '') {
 2147:         $namespace = 'ids';
 2148:     }
 2149:     my %servers=();
 2150:     while (my ($id,$unamestr) = each(%ids)) {
 2151:         if ($namespace eq 'ids') {
 2152:             my $uhom = $uhome;
 2153:             if ($uhom eq '') { 
 2154:                 $uhom=&homeserver($unamestr,$udom);
 2155:             }
 2156:             if ($uhom ne 'no_host') {
 2157:                 $servers{$uhom}.='&'.&escape($id);
 2158:             }
 2159:          } else {
 2160:             my @curritems = split(/,/,$ids{$id});
 2161:             foreach my $uname (@curritems) {
 2162:                 my $uhom = $uhome;
 2163:                 if ($uhom eq '') {
 2164:                     $uhom=&homeserver($uname,$udom);
 2165:                 }
 2166:                 if ($uhom ne 'no_host') { 
 2167:                     $byid{$uhom}{$id} .= $uname.',';
 2168:                 }
 2169:             }
 2170:         }
 2171:     }
 2172:     if ($namespace eq 'clickers') {
 2173:         foreach my $server (keys(%byid)) {
 2174:             if (ref($byid{$server}) eq 'HASH') {
 2175:                 foreach my $id (keys(%{$byid{$server}})) {
 2176:                     $byid{$server}{$id} =~ s/,$//;
 2177:                     $servers{$server}.=&escape($id).'='.&escape($byid{$server}{$id}).'&';
 2178:                 }
 2179:             }
 2180:         }
 2181:     }
 2182:     foreach my $server (keys(%servers)) {
 2183:         $servers{$server} =~ s/\&$//;
 2184:         if ($namespace eq 'ids') {
 2185:             $result{$server} = &critical('iddel:'.$udom.':'.$servers{$server},$uhome);
 2186:         } elsif ($namespace eq 'clickers') {
 2187:             $result{$server} = &critical('updateclickers:'.$udom.':del:'.$servers{$server},$server);
 2188:         }
 2189:     }
 2190:     return %result;
 2191: }
 2192: 
 2193: # ----- Update clicker ID-to-username look-ups in clickers.db on library server 
 2194: 
 2195: sub updateclickers {
 2196:     my ($udom,$action,$idshashref,$uhome,$critical) = @_;
 2197:     my %clickers;
 2198:     if (ref($idshashref) eq 'HASH') {
 2199:         %clickers=%{$idshashref};
 2200:     } else {
 2201:         return;
 2202:     }
 2203:     my $items='';
 2204:     foreach my $item (keys(%clickers)) {
 2205:         $items.=&escape($item).'='.&escape($clickers{$item}).'&';
 2206:     }
 2207:     $items=~s/\&$//;
 2208:     my $request = "updateclickers:$udom:$action:$items";
 2209:     if ($critical) {
 2210:         return &critical($request,$uhome);
 2211:     } else {
 2212:         return &reply($request,$uhome);
 2213:     }
 2214: }
 2215: 
 2216: # ------------------------------dump from db file owned by domainconfig user
 2217: sub dump_dom {
 2218:     my ($namespace, $udom, $regexp) = @_;
 2219: 
 2220:     $udom ||= $env{'user.domain'};
 2221: 
 2222:     return () unless $udom;
 2223: 
 2224:     return &dump($namespace, $udom, &get_domainconfiguser($udom), $regexp);
 2225: }
 2226: 
 2227: # ------------------------------------------ get items from domain db files   
 2228: 
 2229: sub get_dom {
 2230:     my ($namespace,$storearr,$udom,$uhome,$encrypt)=@_;
 2231:     return if ($udom eq 'public');
 2232:     my $items='';
 2233:     foreach my $item (@$storearr) {
 2234:         $items.=&escape($item).'&';
 2235:     }
 2236:     $items=~s/\&$//;
 2237:     if (!$udom) {
 2238:         $udom=$env{'user.domain'};
 2239:         return if ($udom eq 'public');
 2240:         if (defined(&domain($udom,'primary'))) {
 2241:             $uhome=&domain($udom,'primary');
 2242:         } else {
 2243:             undef($uhome);
 2244:         }
 2245:     } else {
 2246:         if (!$uhome) {
 2247:             if (defined(&domain($udom,'primary'))) {
 2248:                 $uhome=&domain($udom,'primary');
 2249:             }
 2250:         }
 2251:     }
 2252:     if ($udom && $uhome && ($uhome ne 'no_host')) {
 2253:         my $rep;
 2254:         if (grep { $_ eq $uhome } &current_machine_ids()) {
 2255:             # domain information is hosted on this machine
 2256:             $rep = &LONCAPA::Lond::get_dom("getdom:$udom:$namespace:$items");
 2257:         } else {
 2258:             if ($encrypt) {
 2259:                 $rep=&reply("encrypt:egetdom:$udom:$namespace:$items",$uhome);
 2260:             } else {
 2261:                 $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
 2262:             }
 2263:         }
 2264:         my %returnhash;
 2265:         if ($rep eq '' || $rep =~ /^error: 2 /) {
 2266:             return %returnhash;
 2267:         }
 2268:         my @pairs=split(/\&/,$rep);
 2269:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
 2270:             return @pairs;
 2271:         }
 2272:         my $i=0;
 2273:         foreach my $item (@$storearr) {
 2274:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
 2275:             $i++;
 2276:         }
 2277:         return %returnhash;
 2278:     } else {
 2279:         &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
 2280:     }
 2281: }
 2282: 
 2283: # -------------------------------------------- put items in domain db files 
 2284: 
 2285: sub put_dom {
 2286:     my ($namespace,$storehash,$udom,$uhome,$encrypt)=@_;
 2287:     if (!$udom) {
 2288:         $udom=$env{'user.domain'};
 2289:         if (defined(&domain($udom,'primary'))) {
 2290:             $uhome=&domain($udom,'primary');
 2291:         } else {
 2292:             undef($uhome);
 2293:         }
 2294:     } else {
 2295:         if (!$uhome) {
 2296:             if (defined(&domain($udom,'primary'))) {
 2297:                 $uhome=&domain($udom,'primary');
 2298:             }
 2299:         }
 2300:     } 
 2301:     if ($udom && $uhome && ($uhome ne 'no_host')) {
 2302:         my $items='';
 2303:         foreach my $item (keys(%$storehash)) {
 2304:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 2305:         }
 2306:         $items=~s/\&$//;
 2307:         if ($encrypt) {
 2308:             return &reply("encrypt:putdom:$udom:$namespace:$items",$uhome);
 2309:         } else {
 2310:             return &reply("putdom:$udom:$namespace:$items",$uhome);
 2311:         }
 2312:     } else {
 2313:         &logthis("put_dom failed - no homeserver and/or domain");
 2314:     }
 2315: }
 2316: 
 2317: # --------------------- newput for items in db file owned by domainconfig user
 2318: sub newput_dom {
 2319:     my ($namespace,$storehash,$udom) = @_;
 2320:     my $result;
 2321:     if (!$udom) {
 2322:         $udom=$env{'user.domain'};
 2323:     }
 2324:     if ($udom) {
 2325:         my $uname = &get_domainconfiguser($udom);
 2326:         $result = &newput($namespace,$storehash,$udom,$uname);
 2327:     }
 2328:     return $result;
 2329: }
 2330: 
 2331: # --------------------- delete for items in db file owned by domainconfig user
 2332: sub del_dom {
 2333:     my ($namespace,$storearr,$udom)=@_;
 2334:     if (ref($storearr) eq 'ARRAY') {
 2335:         if (!$udom) {
 2336:             $udom=$env{'user.domain'};
 2337:         }
 2338:         if ($udom) {
 2339:             my $uname = &get_domainconfiguser($udom); 
 2340:             return &del($namespace,$storearr,$udom,$uname);
 2341:         }
 2342:     }
 2343: }
 2344: 
 2345: sub store_dom {
 2346:     my ($storehash,$id,$namespace,$dom,$home,$encrypt) = @_;
 2347:     $$storehash{'ip'}=&get_requestor_ip();
 2348:     $$storehash{'host'}=$perlvar{'lonHostID'};
 2349:     my $namevalue='';
 2350:     foreach my $key (keys(%{$storehash})) {
 2351:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 2352:     }
 2353:     $namevalue=~s/\&$//;
 2354:     if (grep { $_ eq $home } current_machine_ids()) {
 2355:         return LONCAPA::Lond::store_dom("storedom:$dom:$namespace:$id:$namevalue");
 2356:     } else {
 2357:         if ($namespace eq 'private') {
 2358:             return 'refused';
 2359:         } elsif ($encrypt) {
 2360:             return reply("encrypt:storedom:$dom:$namespace:$id:$namevalue",$home);
 2361:         } else {
 2362:             return reply("storedom:$dom:$namespace:$id:$namevalue",$home);
 2363:         }
 2364:     }
 2365: }
 2366: 
 2367: sub restore_dom {
 2368:     my ($id,$namespace,$dom,$home,$encrypt) = @_;
 2369:     my $answer;
 2370:     if (grep { $_ eq $home } current_machine_ids()) {
 2371:         $answer = LONCAPA::Lond::restore_dom("restoredom:$dom:$namespace:$id");
 2372:     } elsif ($namespace ne 'private') {
 2373:         if ($encrypt) {
 2374:             $answer=&reply("encrypt:restoredom:$dom:$namespace:$id",$home);
 2375:         } else {
 2376:             $answer=&reply("restoredom:$dom:$namespace:$id",$home);
 2377:         }
 2378:     }
 2379:     my %returnhash=();
 2380:     unless (($answer eq '') || ($answer eq 'con_lost') || ($answer eq 'refused') || 
 2381:             ($answer eq 'unknown_cmd') || ($answer eq 'rejected')) {
 2382:         foreach my $line (split(/\&/,$answer)) {
 2383:             my ($name,$value)=split(/\=/,$line);
 2384:             $returnhash{&unescape($name)}=&thaw_unescape($value);
 2385:         }
 2386:         my $version;
 2387:         for ($version=1;$version<=$returnhash{'version'};$version++) {
 2388:             foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
 2389:                 $returnhash{$item}=$returnhash{$version.':'.$item};
 2390:             }
 2391:         }
 2392:     }
 2393:     return %returnhash;
 2394: }
 2395: 
 2396: # ----------------------------------construct domainconfig user for a domain 
 2397: sub get_domainconfiguser {
 2398:     my ($udom) = @_;
 2399:     return $udom.'-domainconfig';
 2400: }
 2401: 
 2402: sub retrieve_inst_usertypes {
 2403:     my ($udom) = @_;
 2404:     my (%returnhash,@order);
 2405:     my %domdefs = &get_domain_defaults($udom);
 2406:     if ((ref($domdefs{'inststatustypes'}) eq 'HASH') && 
 2407:         (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
 2408:         return ($domdefs{'inststatustypes'},$domdefs{'inststatusorder'});
 2409:     } else {
 2410:         if (defined(&domain($udom,'primary'))) {
 2411:             my $uhome=&domain($udom,'primary');
 2412:             my $rep=&reply("inst_usertypes:$udom",$uhome);
 2413:             if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
 2414:                 &logthis("retrieve_inst_usertypes failed - $rep returned from $uhome in domain: $udom");
 2415:                 return (\%returnhash,\@order);
 2416:             }
 2417:             my ($hashitems,$orderitems) = split(/:/,$rep); 
 2418:             my @pairs=split(/\&/,$hashitems);
 2419:             foreach my $item (@pairs) {
 2420:                 my ($key,$value)=split(/=/,$item,2);
 2421:                 $key = &unescape($key);
 2422:                 next if ($key =~ /^error: 2 /);
 2423:                 $returnhash{$key}=&thaw_unescape($value);
 2424:             }
 2425:             my @esc_order = split(/\&/,$orderitems);
 2426:             foreach my $item (@esc_order) {
 2427:                 push(@order,&unescape($item));
 2428:             }
 2429:         } else {
 2430:             &logthis("retrieve_inst_usertypes failed - no primary domain server for $udom");
 2431:         }
 2432:         return (\%returnhash,\@order);
 2433:     }
 2434: }
 2435: 
 2436: sub is_domainimage {
 2437:     my ($url) = @_;
 2438:     if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo|login)/+[^/]-) {
 2439:         if (&domain($1) ne '') {
 2440:             return '1';
 2441:         }
 2442:     }
 2443:     return;
 2444: }
 2445: 
 2446: sub inst_directory_query {
 2447:     my ($srch) = @_;
 2448:     my $udom = $srch->{'srchdomain'};
 2449:     my %results;
 2450:     my $homeserver = &domain($udom,'primary');
 2451:     my $outcome;
 2452:     if ($homeserver ne '') {
 2453:         unless ($homeserver eq $perlvar{'lonHostID'}) {
 2454:             if ($srch->{'srchby'} eq 'email') {
 2455:                 my $lcrev = &get_server_loncaparev($udom,$homeserver);
 2456:                 my ($major,$minor) = ($lcrev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
 2457:                 if (($major eq '' && $minor eq '') || ($major < 2) ||
 2458:                     (($major == 2) && ($minor < 12))) {
 2459:                     return;
 2460:                 }
 2461:             }
 2462:         }
 2463: 	my $queryid=&reply("querysend:instdirsearch:".
 2464: 			   &escape($srch->{'srchby'}).':'.
 2465: 			   &escape($srch->{'srchterm'}).':'.
 2466: 			   &escape($srch->{'srchtype'}),$homeserver);
 2467: 	my $host=&hostname($homeserver);
 2468: 	if ($queryid !~/^\Q$host\E\_/) {
 2469: 	    &logthis('institutional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.' in domain '.$udom);
 2470: 	    return;
 2471: 	}
 2472: 	my $response = &get_query_reply($queryid);
 2473: 	my $maxtries = 5;
 2474: 	my $tries = 1;
 2475: 	while (($response=~/^timeout/) && ($tries < $maxtries)) {
 2476: 	    $response = &get_query_reply($queryid);
 2477: 	    $tries ++;
 2478: 	}
 2479: 
 2480:         if (!&error($response) && $response ne 'refused') {
 2481:             if ($response eq 'unavailable') {
 2482:                 $outcome = $response;
 2483:             } else {
 2484:                 $outcome = 'ok';
 2485:                 my @matches = split(/\n/,$response);
 2486:                 foreach my $match (@matches) {
 2487:                     my ($key,$value) = split(/=/,$match);
 2488:                     $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
 2489:                 }
 2490:             }
 2491:         }
 2492:     }
 2493:     return ($outcome,%results);
 2494: }
 2495: 
 2496: sub usersearch {
 2497:     my ($srch) = @_;
 2498:     my $dom = $srch->{'srchdomain'};
 2499:     my %results;
 2500:     my %libserv = &all_library();
 2501:     my $query = 'usersearch';
 2502:     foreach my $tryserver (keys(%libserv)) {
 2503:         if (&host_domain($tryserver) eq $dom) {
 2504:             unless ($tryserver eq $perlvar{'lonHostID'}) {
 2505:                 if ($srch->{'srchby'} eq 'email') {
 2506:                     my $lcrev = &get_server_loncaparev($dom,$tryserver);
 2507:                     my ($major,$minor) = ($lcrev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
 2508:                     next if (($major eq '' && $minor eq '') || ($major < 2) ||
 2509:                              (($major == 2) && ($minor < 12)));
 2510:                 }
 2511:             }
 2512:             my $host=&hostname($tryserver);
 2513:             my $queryid=
 2514:                 &reply("querysend:".&escape($query).':'.
 2515:                        &escape($srch->{'srchby'}).':'.
 2516:                        &escape($srch->{'srchtype'}).':'.
 2517:                        &escape($srch->{'srchterm'}),$tryserver);
 2518:             if ($queryid !~/^\Q$host\E\_/) {
 2519:                 &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
 2520:                 next;
 2521:             }
 2522:             my $reply = &get_query_reply($queryid);
 2523:             my $maxtries = 1;
 2524:             my $tries = 1;
 2525:             while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 2526:                 $reply = &get_query_reply($queryid);
 2527:                 $tries ++;
 2528:             }
 2529:             if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 2530:                 &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') -  maxtries: '.$maxtries.' tries: '.$tries);
 2531:             } else {
 2532:                 my @matches;
 2533:                 if ($reply =~ /\n/) {
 2534:                     @matches = split(/\n/,$reply);
 2535:                 } else {
 2536:                     @matches = split(/\&/,$reply);
 2537:                 }
 2538:                 foreach my $match (@matches) {
 2539:                     my ($uname,$udom,%userhash);
 2540:                     foreach my $entry (split(/:/,$match)) {
 2541:                         my ($key,$value) =
 2542:                             map {&unescape($_);} split(/=/,$entry);
 2543:                         $userhash{$key} = $value;
 2544:                         if ($key eq 'username') {
 2545:                             $uname = $value;
 2546:                         } elsif ($key eq 'domain') {
 2547:                             $udom = $value;
 2548:                         }
 2549:                     }
 2550:                     $results{$uname.':'.$udom} = \%userhash;
 2551:                 }
 2552:             }
 2553:         }
 2554:     }
 2555:     return %results;
 2556: }
 2557: 
 2558: sub get_instuser {
 2559:     my ($udom,$uname,$id) = @_;
 2560:     my $homeserver = &domain($udom,'primary');
 2561:     my ($outcome,%results);
 2562:     if ($homeserver ne '') {
 2563:         my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
 2564:                            &escape($id).':'.&escape($udom),$homeserver);
 2565:         my $host=&hostname($homeserver);
 2566:         if ($queryid !~/^\Q$host\E\_/) {
 2567:             &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
 2568:             return;
 2569:         }
 2570:         my $response = &get_query_reply($queryid);
 2571:         my $maxtries = 5;
 2572:         my $tries = 1;
 2573:         while (($response=~/^timeout/) && ($tries < $maxtries)) {
 2574:             $response = &get_query_reply($queryid);
 2575:             $tries ++;
 2576:         }
 2577:         if (!&error($response) && $response ne 'refused') {
 2578:             if ($response eq 'unavailable') {
 2579:                 $outcome = $response;
 2580:             } else {
 2581:                 $outcome = 'ok';
 2582:                 my @matches = split(/\n/,$response);
 2583:                 foreach my $match (@matches) {
 2584:                     my ($key,$value) = split(/=/,$match);
 2585:                     $results{&unescape($key)} = &thaw_unescape($value);
 2586:                 }
 2587:             }
 2588:         }
 2589:     }
 2590:     my %userinfo;
 2591:     if (ref($results{$uname}) eq 'HASH') {
 2592:         %userinfo = %{$results{$uname}};
 2593:     } 
 2594:     return ($outcome,%userinfo);
 2595: }
 2596: 
 2597: sub get_multiple_instusers {
 2598:     my ($udom,$users,$caller) = @_;
 2599:     my ($outcome,$results);
 2600:     if (ref($users) eq 'HASH') {
 2601:         my $count = keys(%{$users}); 
 2602:         my $requested = &freeze_escape($users);
 2603:         my $homeserver = &domain($udom,'primary');
 2604:         if ($homeserver ne '') {
 2605:             my $queryid=&reply('querysend:getmultinstusers:::'.$caller.'='.$requested,$homeserver);
 2606:             my $host=&hostname($homeserver);
 2607:             if ($queryid !~/^\Q$host\E\_/) {
 2608:                 &logthis('get_multiple_instusers invalid queryid: '.$queryid.
 2609:                          ' for host: '.$homeserver.'in domain '.$udom);
 2610:                 return ($outcome,$results);
 2611:             }
 2612:             my $response = &get_query_reply($queryid);
 2613:             my $maxtries = 5;
 2614:             if ($count > 100) {
 2615:                 $maxtries = 1+int($count/20);
 2616:             }
 2617:             my $tries = 1;
 2618:             while (($response=~/^timeout/) && ($tries <= $maxtries)) {
 2619:                 $response = &get_query_reply($queryid);
 2620:                 $tries ++;
 2621:             }
 2622:             if ($response eq '') {
 2623:                 $results = {};
 2624:                 foreach my $key (keys(%{$users})) {
 2625:                     my ($uname,$id);
 2626:                     if ($caller eq 'id') {
 2627:                         $id = $key;
 2628:                     } else {
 2629:                         $uname = $key;
 2630:                     }
 2631:                     my ($resp,%info) = &get_instuser($udom,$uname,$id);
 2632:                     $outcome = $resp;
 2633:                     if ($resp eq 'ok') {
 2634:                         %{$results} = (%{$results}, %info);
 2635:                     } else {
 2636:                         last;
 2637:                     }
 2638:                 }
 2639:             } elsif(!&error($response) && ($response ne 'refused')) {
 2640:                 if (($response eq 'unavailable') || ($response eq 'invalid') || ($response eq 'timeout')) {
 2641:                     $outcome = $response;
 2642:                 } else {
 2643:                     ($outcome,my $userdata) = split(/=/,$response,2);
 2644:                     if ($outcome eq 'ok') {
 2645:                         $results = &thaw_unescape($userdata); 
 2646:                     }
 2647:                 }
 2648:             }
 2649:         }
 2650:     }
 2651:     return ($outcome,$results);
 2652: }
 2653: 
 2654: sub inst_rulecheck {
 2655:     my ($udom,$uname,$id,$item,$rules) = @_;
 2656:     my %returnhash;
 2657:     if ($udom ne '') {
 2658:         if (ref($rules) eq 'ARRAY') {
 2659:             @{$rules} = map {&escape($_);} (@{$rules});
 2660:             my $rulestr = join(':',@{$rules});
 2661:             my $homeserver=&domain($udom,'primary');
 2662:             if (($homeserver ne '') && ($homeserver ne 'no_host')) {
 2663:                 my $response;
 2664:                 if ($item eq 'username') {                
 2665:                     $response=&unescape(&reply('instrulecheck:'.&escape($udom).
 2666:                                               ':'.&escape($uname).':'.$rulestr,
 2667:                                               $homeserver));
 2668:                 } elsif ($item eq 'id') {
 2669:                     $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
 2670:                                               ':'.&escape($id).':'.$rulestr,
 2671:                                               $homeserver));
 2672:                 } elsif ($item eq 'selfcreate') {
 2673:                     $response=&unescape(&reply('instselfcreatecheck:'.
 2674:                                                &escape($udom).':'.&escape($uname).
 2675:                                               ':'.$rulestr,$homeserver));
 2676:                 } elsif ($item eq 'unamemap') {
 2677:                     $response=&unescape(&reply('instunamemapcheck:'.
 2678:                                                &escape($udom).':'.&escape($uname).
 2679:                                               ':'.$rulestr,$homeserver));
 2680:                 }
 2681:                 if ($response ne 'refused') {
 2682:                     my @pairs=split(/\&/,$response);
 2683:                     foreach my $item (@pairs) {
 2684:                         my ($key,$value)=split(/=/,$item,2);
 2685:                         $key = &unescape($key);
 2686:                         next if ($key =~ /^error: 2 /);
 2687:                         $returnhash{$key}=&thaw_unescape($value);
 2688:                     }
 2689:                 }
 2690:             }
 2691:         }
 2692:     }
 2693:     return %returnhash;
 2694: }
 2695: 
 2696: sub inst_userrules {
 2697:     my ($udom,$check) = @_;
 2698:     my (%ruleshash,@ruleorder);
 2699:     if ($udom ne '') {
 2700:         my $homeserver=&domain($udom,'primary');
 2701:         if (($homeserver ne '') && ($homeserver ne 'no_host')) {
 2702:             my $response;
 2703:             if ($check eq 'id') {
 2704:                 $response=&reply('instidrules:'.&escape($udom),
 2705:                                  $homeserver);
 2706:             } elsif ($check eq 'email') {
 2707:                 $response=&reply('instemailrules:'.&escape($udom),
 2708:                                  $homeserver);
 2709:             } elsif ($check eq 'unamemap') {
 2710:                 $response=&reply('unamemaprules:'.&escape($udom),
 2711:                                  $homeserver); 
 2712:             } else {
 2713:                 $response=&reply('instuserrules:'.&escape($udom),
 2714:                                  $homeserver);
 2715:             }
 2716:             if (($response ne 'refused') && ($response ne 'error') && 
 2717:                 ($response ne 'unknown_cmd') && 
 2718:                 ($response ne 'no_such_host')) {
 2719:                 my ($hashitems,$orderitems) = split(/:/,$response);
 2720:                 my @pairs=split(/\&/,$hashitems);
 2721:                 foreach my $item (@pairs) {
 2722:                     my ($key,$value)=split(/=/,$item,2);
 2723:                     $key = &unescape($key);
 2724:                     next if ($key =~ /^error: 2 /);
 2725:                     $ruleshash{$key}=&thaw_unescape($value);
 2726:                 }
 2727:                 my @esc_order = split(/\&/,$orderitems);
 2728:                 foreach my $item (@esc_order) {
 2729:                     push(@ruleorder,&unescape($item));
 2730:                 }
 2731:             }
 2732:         }
 2733:     }
 2734:     return (\%ruleshash,\@ruleorder);
 2735: }
 2736: 
 2737: # ------------- Get Authentication, Language and User Tools Defaults for Domain
 2738: 
 2739: sub get_domain_defaults {
 2740:     my ($domain,$ignore_cache) = @_;
 2741:     return if (($domain eq '') || ($domain eq 'public'));
 2742:     my $cachetime = 60*60*24;
 2743:     unless ($ignore_cache) {
 2744:         my ($result,$cached)=&is_cached_new('domdefaults',$domain);
 2745:         if (defined($cached)) {
 2746:             if (ref($result) eq 'HASH') {
 2747:                 return %{$result};
 2748:             }
 2749:         }
 2750:     }
 2751:     my %domdefaults;
 2752:     my %domconfig =
 2753:          &get_dom('configuration',['defaults','quotas',
 2754:                                   'requestcourses','inststatus',
 2755:                                   'coursedefaults','usersessions',
 2756:                                   'requestauthor','authordefaults',
 2757:                                   'selfenrollment','coursecategories',
 2758:                                   'ssl','autoenroll','trust',
 2759:                                   'helpsettings','wafproxy',
 2760:                                   'ltisec','toolsec','privacy'],$domain);
 2761:     my @coursetypes = ('official','unofficial','community','textbook','placement');
 2762:     if (ref($domconfig{'defaults'}) eq 'HASH') {
 2763:         $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'}; 
 2764:         $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
 2765:         $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
 2766:         $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
 2767:         $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
 2768:         $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
 2769:         $domdefaults{'portal_def_email'} = $domconfig{'defaults'}{'portal_def_email'};
 2770:         $domdefaults{'portal_def_web'} = $domconfig{'defaults'}{'portal_def_web'};
 2771:         $domdefaults{'intauth_cost'} = $domconfig{'defaults'}{'intauth_cost'};
 2772:         $domdefaults{'intauth_switch'} = $domconfig{'defaults'}{'intauth_switch'};
 2773:         $domdefaults{'intauth_check'} = $domconfig{'defaults'}{'intauth_check'};
 2774:         $domdefaults{'unamemap_rule'} = $domconfig{'defaults'}{'unamemap_rule'};
 2775:     } else {
 2776:         $domdefaults{'lang_def'} = &domain($domain,'lang_def');
 2777:         $domdefaults{'auth_def'} = &domain($domain,'auth_def');
 2778:         $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
 2779:     }
 2780:     if (ref($domconfig{'quotas'}) eq 'HASH') {
 2781:         if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
 2782:             $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
 2783:         } else {
 2784:             $domdefaults{'defaultquota'} = $domconfig{'quotas'};
 2785:         }
 2786:         my @usertools = ('aboutme','blog','webdav','portfolio','portaccess');
 2787:         foreach my $item (@usertools) {
 2788:             if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
 2789:                 $domdefaults{$item} = $domconfig{'quotas'}{$item};
 2790:             }
 2791:         }
 2792:         if (ref($domconfig{'quotas'}{'authorquota'}) eq 'HASH') {
 2793:             $domdefaults{'authorquota'} = $domconfig{'quotas'}{'authorquota'};
 2794:         }
 2795:     }
 2796:     if (ref($domconfig{'requestcourses'}) eq 'HASH') {
 2797:         foreach my $item ('official','unofficial','community','textbook','placement') {
 2798:             $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
 2799:         }
 2800:     }
 2801:     if (ref($domconfig{'requestauthor'}) eq 'HASH') {
 2802:         $domdefaults{'requestauthor'} = $domconfig{'requestauthor'};
 2803:     }
 2804:     if (ref($domconfig{'authordefaults'}) eq 'HASH') {
 2805:         foreach my $item ('nocodemirror','copyright','sourceavail','domcoordacc','editors') {
 2806:             if ($item eq 'editors') {
 2807:                 if (ref($domconfig{'authordefaults'}{'editors'}) eq 'ARRAY') {
 2808:                     $domdefaults{$item} = join(',',@{$domconfig{'authordefaults'}{'editors'}});
 2809:                 }
 2810:             } else {
 2811:                 $domdefaults{$item} = $domconfig{'authordefaults'}{$item};
 2812:             }
 2813:         }
 2814:     }
 2815:     if (ref($domconfig{'inststatus'}) eq 'HASH') {
 2816:         foreach my $item ('inststatustypes','inststatusorder','inststatusguest') {
 2817:             $domdefaults{$item} = $domconfig{'inststatus'}{$item};
 2818:         }
 2819:     }
 2820:     if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
 2821:         $domdefaults{'canuse_pdfforms'} = $domconfig{'coursedefaults'}{'canuse_pdfforms'};
 2822:         $domdefaults{'usejsme'} = $domconfig{'coursedefaults'}{'usejsme'};
 2823:         $domdefaults{'inline_chem'} = $domconfig{'coursedefaults'}{'inline_chem'};
 2824:         $domdefaults{'uselcmath'} = $domconfig{'coursedefaults'}{'uselcmath'};
 2825:         if (ref($domconfig{'coursedefaults'}{'postsubmit'}) eq 'HASH') {
 2826:             $domdefaults{'postsubmit'} = $domconfig{'coursedefaults'}{'postsubmit'}{'client'};
 2827:         }
 2828:         foreach my $type (@coursetypes) {
 2829:             if (ref($domconfig{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
 2830:                 unless ($type eq 'community') {
 2831:                     $domdefaults{$type.'credits'} = $domconfig{'coursedefaults'}{'coursecredits'}{$type};
 2832:                 }
 2833:             }
 2834:             if (ref($domconfig{'coursedefaults'}{'uploadquota'}) eq 'HASH') {
 2835:                 $domdefaults{$type.'quota'} = $domconfig{'coursedefaults'}{'uploadquota'}{$type};
 2836:             }
 2837:             if (ref($domconfig{'coursedefaults'}{'coursequota'}) eq 'HASH') {
 2838:                 $domdefaults{$type.'coursequota'} = $domconfig{'coursedefaults'}{'coursequota'}{$type};
 2839:             }
 2840:             if ($domdefaults{'postsubmit'} eq 'on') {
 2841:                 if (ref($domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}) eq 'HASH') {
 2842:                     $domdefaults{$type.'postsubtimeout'} = 
 2843:                         $domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}{$type}; 
 2844:                 }
 2845:             }
 2846:             if (ref($domconfig{'coursedefaults'}{'domexttool'}) eq 'HASH') {
 2847:                 $domdefaults{$type.'domexttool'} = $domconfig{'coursedefaults'}{'domexttool'}{$type};
 2848:             } else {
 2849:                 $domdefaults{$type.'domexttool'} = 1;
 2850:             }
 2851:             if (ref($domconfig{'coursedefaults'}{'exttool'}) eq 'HASH') {
 2852:                 $domdefaults{$type.'exttool'} = $domconfig{'coursedefaults'}{'exttool'}{$type};
 2853:             } else {
 2854:                 $domdefaults{$type.'exttool'} = 0;
 2855:             }
 2856:             if (ref($domconfig{'coursedefaults'}{'crsauthor'}) eq 'HASH') {
 2857:                 $domdefaults{$type.'crsauthor'} = $domconfig{'coursedefaults'}{'crsauthor'}{$type};
 2858:             } else {
 2859:                 $domdefaults{$type.'crsauthor'} = 1;
 2860:             }
 2861:         }
 2862:         if (ref($domconfig{'coursedefaults'}{'canclone'}) eq 'HASH') {
 2863:             if (ref($domconfig{'coursedefaults'}{'canclone'}{'instcode'}) eq 'ARRAY') {
 2864:                 my @clonecodes = @{$domconfig{'coursedefaults'}{'canclone'}{'instcode'}};
 2865:                 if (@clonecodes) {
 2866:                     $domdefaults{'canclone'} = join('+',@clonecodes);
 2867:                 }
 2868:             }
 2869:         } elsif ($domconfig{'coursedefaults'}{'canclone'}) {
 2870:             $domdefaults{'canclone'}=$domconfig{'coursedefaults'}{'canclone'};
 2871:         }
 2872:         if ($domconfig{'coursedefaults'}{'texengine'}) {
 2873:             $domdefaults{'texengine'} = $domconfig{'coursedefaults'}{'texengine'};
 2874:         }
 2875:         if (exists($domconfig{'coursedefaults'}{'ltiauth'})) {
 2876:             $domdefaults{'crsltiauth'} = $domconfig{'coursedefaults'}{'ltiauth'};
 2877:         }
 2878:     }
 2879:     if (ref($domconfig{'usersessions'}) eq 'HASH') {
 2880:         if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
 2881:             $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
 2882:         }
 2883:         if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
 2884:             $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
 2885:         }
 2886:         if (ref($domconfig{'usersessions'}{'offloadnow'}) eq 'HASH') {
 2887:             $domdefaults{'offloadnow'} = $domconfig{'usersessions'}{'offloadnow'};
 2888:         }
 2889:         if (ref($domconfig{'usersessions'}{'offloadoth'}) eq 'HASH') {
 2890:             $domdefaults{'offloadoth'} = $domconfig{'usersessions'}{'offloadoth'};
 2891:         }
 2892:     }
 2893:     if (ref($domconfig{'selfenrollment'}) eq 'HASH') {
 2894:         if (ref($domconfig{'selfenrollment'}{'admin'}) eq 'HASH') {
 2895:             my @settings = ('types','registered','enroll_dates','access_dates','section',
 2896:                             'approval','limit');
 2897:             foreach my $type (@coursetypes) {
 2898:                 if (ref($domconfig{'selfenrollment'}{'admin'}{$type}) eq 'HASH') {
 2899:                     my @mgrdc = ();
 2900:                     foreach my $item (@settings) {
 2901:                         if ($domconfig{'selfenrollment'}{'admin'}{$type}{$item} eq '0') {
 2902:                             push(@mgrdc,$item);
 2903:                         }
 2904:                     }
 2905:                     if (@mgrdc) {
 2906:                         $domdefaults{$type.'selfenrolladmdc'} = join(',',@mgrdc);
 2907:                     }
 2908:                 }
 2909:             }
 2910:         }
 2911:         if (ref($domconfig{'selfenrollment'}{'default'}) eq 'HASH') {
 2912:             foreach my $type (@coursetypes) {
 2913:                 if (ref($domconfig{'selfenrollment'}{'default'}{$type}) eq 'HASH') {
 2914:                     foreach my $item (keys(%{$domconfig{'selfenrollment'}{'default'}{$type}})) {
 2915:                         $domdefaults{$type.'selfenroll'.$item} = $domconfig{'selfenrollment'}{'default'}{$type}{$item};
 2916:                     }
 2917:                 }
 2918:             }
 2919:         }
 2920:     }
 2921:     if (ref($domconfig{'coursecategories'}) eq 'HASH') {
 2922:         $domdefaults{'catauth'} = 'std';
 2923:         $domdefaults{'catunauth'} = 'std';
 2924:         if ($domconfig{'coursecategories'}{'auth'}) {
 2925:             $domdefaults{'catauth'} = $domconfig{'coursecategories'}{'auth'};
 2926:         }
 2927:         if ($domconfig{'coursecategories'}{'unauth'}) {
 2928:             $domdefaults{'catunauth'} = $domconfig{'coursecategories'}{'unauth'};
 2929:         }
 2930:     }
 2931:     if (ref($domconfig{'ssl'}) eq 'HASH') {
 2932:         if (ref($domconfig{'ssl'}{'replication'}) eq 'HASH') {
 2933:             $domdefaults{'replication'} = $domconfig{'ssl'}{'replication'};
 2934:         }
 2935:         if (ref($domconfig{'ssl'}{'connto'}) eq 'HASH') {
 2936:             $domdefaults{'connect'} = $domconfig{'ssl'}{'connto'};
 2937:         }
 2938:         if (ref($domconfig{'ssl'}{'connfrom'}) eq 'HASH') {
 2939:             $domdefaults{'connect'} = $domconfig{'ssl'}{'connfrom'};
 2940:         }
 2941:     }
 2942:     if (ref($domconfig{'trust'}) eq 'HASH') {
 2943:         my @prefixes = qw(content shared enroll othcoau coaurem domroles catalog reqcrs msg);
 2944:         foreach my $prefix (@prefixes) {
 2945:             if (ref($domconfig{'trust'}{$prefix}) eq 'HASH') {
 2946:                 $domdefaults{'trust'.$prefix} = $domconfig{'trust'}{$prefix};
 2947:             }
 2948:         }
 2949:     }
 2950:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
 2951:         $domdefaults{'autofailsafe'} = $domconfig{'autoenroll'}{'autofailsafe'};
 2952:         $domdefaults{'failsafe'} = $domconfig{'autoenroll'}{'failsafe'};
 2953:     }
 2954:     if (ref($domconfig{'helpsettings'}) eq 'HASH') {
 2955:         $domdefaults{'submitbugs'} = $domconfig{'helpsettings'}{'submitbugs'};
 2956:         if (ref($domconfig{'helpsettings'}{'adhoc'}) eq 'HASH') {
 2957:             $domdefaults{'adhocroles'} = $domconfig{'helpsettings'}{'adhoc'};
 2958:         }
 2959:     }
 2960:     if (ref($domconfig{'wafproxy'}) eq 'HASH') {
 2961:         foreach my $item ('ipheader','trusted','vpnint','vpnext','sslopt') {
 2962:             if ($domconfig{'wafproxy'}{$item}) {
 2963:                 $domdefaults{'waf_'.$item} = $domconfig{'wafproxy'}{$item};
 2964:             }
 2965:         }
 2966:     }
 2967:     if (ref($domconfig{'ltisec'}) eq 'HASH') {
 2968:         if (ref($domconfig{'ltisec'}{'encrypt'}) eq 'HASH') {
 2969:             $domdefaults{'linkprotenc_crs'} = $domconfig{'ltisec'}{'encrypt'}{'crs'};
 2970:             $domdefaults{'linkprotenc_dom'} = $domconfig{'ltisec'}{'encrypt'}{'dom'};
 2971:             $domdefaults{'ltienc_consumers'} = $domconfig{'ltisec'}{'encrypt'}{'consumers'};
 2972:         }
 2973:         if (ref($domconfig{'ltisec'}{'private'}) eq 'HASH') {
 2974:             if (ref($domconfig{'ltisec'}{'private'}{'keys'}) eq 'ARRAY') {
 2975:                 $domdefaults{'ltiprivhosts'} = $domconfig{'ltisec'}{'private'}{'keys'};
 2976:             }
 2977:         }
 2978:         if (ref($domconfig{'ltisec'}{'suggested'}) eq 'HASH') {
 2979:             my %suggestions = %{$domconfig{'ltisec'}{'suggested'}};
 2980:             foreach my $item (keys(%{$domconfig{'ltisec'}{'suggested'}})) {
 2981:                 unless (ref($domconfig{'ltisec'}{'suggested'}{$item}) eq 'HASH') {
 2982:                     delete($suggestions{$item});
 2983:                 }
 2984:             }
 2985:             if (keys(%suggestions)) {
 2986:                 $domdefaults{'linkprotsuggested'} = \%suggestions;
 2987:             }
 2988:         }
 2989:     }
 2990:     if (ref($domconfig{'toolsec'}) eq 'HASH') {
 2991:         if (ref($domconfig{'toolsec'}{'encrypt'}) eq 'HASH') {
 2992:             $domdefaults{'toolenc_crs'} = $domconfig{'toolsec'}{'encrypt'}{'crs'};
 2993:             $domdefaults{'toolenc_dom'} = $domconfig{'toolsec'}{'encrypt'}{'dom'};
 2994:         }
 2995:         if (ref($domconfig{'toolsec'}{'private'}) eq 'HASH') {
 2996:             if (ref($domconfig{'toolsec'}{'private'}{'keys'}) eq 'ARRAY') {
 2997:                 $domdefaults{'toolprivhosts'} = $domconfig{'toolsec'}{'private'}{'keys'};
 2998:             }
 2999:         }
 3000:     }
 3001:     if (ref($domconfig{'privacy'}) eq 'HASH') {
 3002:         if (ref($domconfig{'privacy'}{'approval'}) eq 'HASH') {
 3003:             foreach my $domtype ('instdom','extdom') {
 3004:                 if (ref($domconfig{'privacy'}{'approval'}{$domtype}) eq 'HASH') {
 3005:                     foreach my $roletype ('domain','author','course','community') {
 3006:                         if ($domconfig{'privacy'}{'approval'}{$domtype}{$roletype} eq 'user') {
 3007:                             $domdefaults{'userapprovals'} = 1;
 3008:                             last;
 3009:                         }
 3010:                     }
 3011:                 }
 3012:                 last if ($domdefaults{'userapprovals'});
 3013:             }
 3014:         }
 3015:     }
 3016:     &do_cache_new('domdefaults',$domain,\%domdefaults,$cachetime);
 3017:     return %domdefaults;
 3018: }
 3019: 
 3020: sub get_dom_cats {
 3021:     my ($dom) = @_;
 3022:     return unless (&domain($dom));
 3023:     my ($cats,$cached)=&is_cached_new('cats',$dom);
 3024:     unless (defined($cached)) {
 3025:         my %domconfig = &get_dom('configuration',['coursecategories'],$dom);
 3026:         if (ref($domconfig{'coursecategories'}) eq 'HASH') {
 3027:             if (ref($domconfig{'coursecategories'}{'cats'}) eq 'HASH') {
 3028:                 %{$cats} = %{$domconfig{'coursecategories'}{'cats'}};
 3029:             } else {
 3030:                 $cats = {};
 3031:             }
 3032:         } else {
 3033:             $cats = {};
 3034:         }
 3035:         &do_cache_new('cats',$dom,$cats,3600);
 3036:     }
 3037:     return $cats;
 3038: }
 3039: 
 3040: sub get_dom_instcats {
 3041:     my ($dom) = @_;
 3042:     return unless (&domain($dom));
 3043:     my ($instcats,$cached)=&is_cached_new('instcats',$dom);
 3044:     unless (defined($cached)) {
 3045:         my (%coursecodes,%codes,@codetitles,%cat_titles,%cat_order);
 3046:         my $totcodes = &retrieve_instcodes(\%coursecodes,$dom);
 3047:         if ($totcodes > 0) {
 3048:             my $caller = 'global';
 3049:             if (&auto_instcode_format($caller,$dom,\%coursecodes,\%codes,
 3050:                                       \@codetitles,\%cat_titles,\%cat_order) eq 'ok') {
 3051:                 $instcats = {
 3052:                                 totcodes => $totcodes,
 3053:                                 codes => \%codes,
 3054:                                 codetitles => \@codetitles,
 3055:                                 cat_titles => \%cat_titles,
 3056:                                 cat_order => \%cat_order,
 3057:                             };
 3058:                 &do_cache_new('instcats',$dom,$instcats,3600);
 3059:             }
 3060:         }
 3061:     }
 3062:     return $instcats;
 3063: }
 3064: 
 3065: sub retrieve_instcodes {
 3066:     my ($coursecodes,$dom) = @_;
 3067:     my $totcodes;
 3068:     my %courses = &courseiddump($dom,'.',1,'.','.','.',undef,undef,'Course');
 3069:     foreach my $course (keys(%courses)) {
 3070:         if (ref($courses{$course}) eq 'HASH') {
 3071:             if ($courses{$course}{'inst_code'} ne '') {
 3072:                 $$coursecodes{$course} = $courses{$course}{'inst_code'};
 3073:                 $totcodes ++;
 3074:             }
 3075:         }
 3076:     }
 3077:     return $totcodes;
 3078: }
 3079: 
 3080: sub course_portal_url {
 3081:     my ($cnum,$cdom,$r) = @_;
 3082:     my $chome = &homeserver($cnum,$cdom);
 3083:     my $hostname = &hostname($chome);
 3084:     my $protocol = $protocol{$chome};
 3085:     $protocol = 'http' if ($protocol ne 'https');
 3086:     my %domdefaults = &get_domain_defaults($cdom);
 3087:     my $firsturl;
 3088:     if ($domdefaults{'portal_def'}) {
 3089:         $firsturl = $domdefaults{'portal_def'};
 3090:     } else {
 3091:         my $alias = &use_proxy_alias($r,$chome);
 3092:         $hostname = $alias if ($alias ne '');
 3093:         $firsturl = $protocol.'://'.$hostname;
 3094:     }
 3095:     return $firsturl;
 3096: }
 3097: 
 3098: sub url_prefix {
 3099:     my ($r,$dom,$home,$context) = @_;
 3100:     my $prefix;
 3101:     my %domdefs = &get_domain_defaults($dom);
 3102:     if ($domdefs{'portal_def'} && $domdefs{'portal_def_'.$context}) {
 3103:         if ($domdefs{'portal_def'} =~ m{^(https?://[^/]+)}) {
 3104:             $prefix = $1;
 3105:         }
 3106:     }
 3107:     if ($prefix eq '') {
 3108:         my $hostname = &hostname($home);
 3109:         my $protocol = $protocol{$home};
 3110:         $protocol = 'http' if ($protocol{$home} ne 'https');
 3111:         my $alias = &use_proxy_alias($r,$home);
 3112:         $hostname = $alias if ($alias ne '');
 3113:         $prefix = $protocol.'://'.$hostname;
 3114:     }
 3115:     return $prefix;
 3116: }
 3117: 
 3118: # --------------------------------------------- Get domain config for passwords
 3119: 
 3120: sub get_passwdconf {
 3121:     my ($dom) = @_;
 3122:     my (%passwdconf,$gotconf,$lookup);
 3123:     my ($result,$cached)=&is_cached_new('passwdconf',$dom);
 3124:     if (defined($cached)) {
 3125:         if (ref($result) eq 'HASH') {
 3126:             %passwdconf = %{$result};
 3127:             $gotconf = 1;
 3128:         }
 3129:     }
 3130:     unless ($gotconf) {
 3131:         my %domconfig = &get_dom('configuration',['passwords'],$dom);
 3132:         if (ref($domconfig{'passwords'}) eq 'HASH') {
 3133:             %passwdconf = %{$domconfig{'passwords'}};
 3134:         }
 3135:         my $cachetime = 24*60*60;
 3136:         &do_cache_new('passwdconf',$dom,\%passwdconf,$cachetime);
 3137:     }
 3138:     return %passwdconf;
 3139: }
 3140: 
 3141: # --------------------------------------------------- Assign a key to a student
 3142: 
 3143: sub assign_access_key {
 3144: #
 3145: # a valid key looks like uname:udom#comments
 3146: # comments are being appended
 3147: #
 3148:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
 3149:     $kdom=
 3150:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
 3151:     $knum=
 3152:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
 3153:     $cdom=
 3154:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 3155:     $cnum=
 3156:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 3157:     $udom=$env{'user.name'} unless (defined($udom));
 3158:     $uname=$env{'user.domain'} unless (defined($uname));
 3159:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
 3160:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
 3161:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
 3162:                                                   # assigned to this person
 3163:                                                   # - this should not happen,
 3164:                                                   # unless something went wrong
 3165:                                                   # the first time around
 3166: # ready to assign
 3167:         $logentry=$1.'; '.$logentry;
 3168:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
 3169:                                                  $kdom,$knum) eq 'ok') {
 3170: # key now belongs to user
 3171: 	    my $envkey='key.'.$cdom.'_'.$cnum;
 3172:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
 3173:                 &appenv({'environment.'.$envkey => $ckey});
 3174:                 return 'ok';
 3175:             } else {
 3176:                 return 
 3177:   'error: Count not permanently assign key, will need to be re-entered later.';
 3178: 	    }
 3179:         } else {
 3180:             return 'error: Could not assign key, try again later.';
 3181:         }
 3182:     } elsif (!$existing{$ckey}) {
 3183: # the key does not exist
 3184: 	return 'error: The key does not exist';
 3185:     } else {
 3186: # the key is somebody else's
 3187: 	return 'error: The key is already in use';
 3188:     }
 3189: }
 3190: 
 3191: # ------------------------------------------ put an additional comment on a key
 3192: 
 3193: sub comment_access_key {
 3194: #
 3195: # a valid key looks like uname:udom#comments
 3196: # comments are being appended
 3197: #
 3198:     my ($ckey,$cdom,$cnum,$logentry)=@_;
 3199:     $cdom=
 3200:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 3201:     $cnum=
 3202:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 3203:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
 3204:     if ($existing{$ckey}) {
 3205:         $existing{$ckey}.='; '.$logentry;
 3206: # ready to assign
 3207:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
 3208:                                                  $cdom,$cnum) eq 'ok') {
 3209: 	    return 'ok';
 3210:         } else {
 3211: 	    return 'error: Count not store comment.';
 3212:         }
 3213:     } else {
 3214: # the key does not exist
 3215: 	return 'error: The key does not exist';
 3216:     }
 3217: }
 3218: 
 3219: # ------------------------------------------------------ Generate a set of keys
 3220: 
 3221: sub generate_access_keys {
 3222:     my ($number,$cdom,$cnum,$logentry)=@_;
 3223:     $cdom=
 3224:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 3225:     $cnum=
 3226:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 3227:     unless (&allowed('mky',$cdom)) { return 0; }
 3228:     unless (($cdom) && ($cnum)) { return 0; }
 3229:     if ($number>10000) { return 0; }
 3230:     sleep(2); # make sure don't get same seed twice
 3231:     srand(time()^($$+($$<<15))); # from "Programming Perl"
 3232:     my $total=0;
 3233:     for (my $i=1;$i<=$number;$i++) {
 3234:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
 3235:                   sprintf("%lx",int(100000*rand)).'-'.
 3236:                   sprintf("%lx",int(100000*rand));
 3237:        $newkey=~s/1/g/g; # folks mix up 1 and l
 3238:        $newkey=~s/0/h/g; # and also 0 and O
 3239:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
 3240:        if ($existing{$newkey}) {
 3241:            $i--;
 3242:        } else {
 3243: 	  if (&put('accesskeys',
 3244:               { $newkey => '# generated '.localtime().
 3245:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
 3246:                            '; '.$logentry },
 3247: 		   $cdom,$cnum) eq 'ok') {
 3248:               $total++;
 3249: 	  }
 3250:        }
 3251:     }
 3252:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
 3253:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
 3254:     return $total;
 3255: }
 3256: 
 3257: # ------------------------------------------------------- Validate an accesskey
 3258: 
 3259: sub validate_access_key {
 3260:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
 3261:     $cdom=
 3262:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 3263:     $cnum=
 3264:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 3265:     $udom=$env{'user.domain'} unless (defined($udom));
 3266:     $uname=$env{'user.name'} unless (defined($uname));
 3267:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
 3268:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
 3269: }
 3270: 
 3271: # ------------------------------------- Find the section of student in a course
 3272: sub devalidate_getsection_cache {
 3273:     my ($udom,$unam,$courseid)=@_;
 3274:     my $hashid="$udom:$unam:$courseid";
 3275:     &devalidate_cache_new('getsection',$hashid);
 3276: }
 3277: 
 3278: sub courseid_to_courseurl {
 3279:     my ($courseid) = @_;
 3280:     #already url style courseid
 3281:     return $courseid if ($courseid =~ m{^/});
 3282: 
 3283:     if (exists($env{'course.'.$courseid.'.num'})) {
 3284: 	my $cnum = $env{'course.'.$courseid.'.num'};
 3285: 	my $cdom = $env{'course.'.$courseid.'.domain'};
 3286: 	return "/$cdom/$cnum";
 3287:     }
 3288: 
 3289:     my %courseinfo=&coursedescription($courseid);
 3290:     if (exists($courseinfo{'num'})) {
 3291: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
 3292:     }
 3293: 
 3294:     return undef;
 3295: }
 3296: 
 3297: sub getsection {
 3298:     my ($udom,$unam,$courseid)=@_;
 3299:     my $cachetime=1800;
 3300: 
 3301:     my $hashid="$udom:$unam:$courseid";
 3302:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
 3303:     if (defined($cached)) { return $result; }
 3304: 
 3305:     my %Pending; 
 3306:     my %Expired;
 3307:     #
 3308:     # Each role can either have not started yet (pending), be active, 
 3309:     #    or have expired.
 3310:     #
 3311:     # If there is an active role, we are done.
 3312:     #
 3313:     # If there is more than one role which has not started yet, 
 3314:     #     choose the one which will start sooner
 3315:     # If there is one role which has not started yet, return it.
 3316:     #
 3317:     # If there is more than one expired role, choose the one which ended last.
 3318:     # If there is a role which has expired, return it.
 3319:     #
 3320:     $courseid = &courseid_to_courseurl($courseid);
 3321:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
 3322:     foreach my $key (keys(%roleshash)) {
 3323:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
 3324:         my $section=$1;
 3325:         if ($key eq $courseid.'_st') { $section=''; }
 3326:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
 3327:         my $now=time;
 3328:         if (defined($end) && $end && ($now > $end)) {
 3329:             $Expired{$end}=$section;
 3330:             next;
 3331:         }
 3332:         if (defined($start) && $start && ($now < $start)) {
 3333:             $Pending{$start}=$section;
 3334:             next;
 3335:         }
 3336:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
 3337:     }
 3338:     #
 3339:     # Presumedly there will be few matching roles from the above
 3340:     # loop and the sorting time will be negligible.
 3341:     if (scalar(keys(%Pending))) {
 3342:         my ($time) = sort {$a <=> $b} keys(%Pending);
 3343:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
 3344:     } 
 3345:     if (scalar(keys(%Expired))) {
 3346:         my @sorted = sort {$a <=> $b} keys(%Expired);
 3347:         my $time = pop(@sorted);
 3348:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
 3349:     }
 3350:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
 3351: }
 3352: 
 3353: sub save_cache {
 3354:     &purge_remembered();
 3355:     #&Apache::loncommon::validate_page();
 3356:     undef(%env);
 3357:     undef($env_loaded);
 3358: }
 3359: 
 3360: my $to_remember=-1;
 3361: my %remembered;
 3362: my %accessed;
 3363: my $kicks=0;
 3364: my $hits=0;
 3365: sub make_key {
 3366:     my ($name,$id) = @_;
 3367:     if (length($id) > 65 
 3368: 	&& length(&escape($id)) > 200) {
 3369: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
 3370:     }
 3371:     return &escape($name.':'.$id);
 3372: }
 3373: 
 3374: sub devalidate_cache_new {
 3375:     my ($name,$id,$debug) = @_;
 3376:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
 3377:     my $remembered_id=$name.':'.$id;
 3378:     $id=&make_key($name,$id);
 3379:     $memcache->delete($id);
 3380:     delete($remembered{$remembered_id});
 3381:     delete($accessed{$remembered_id});
 3382: }
 3383: 
 3384: sub is_cached_new {
 3385:     my ($name,$id,$debug) = @_;
 3386:     my $remembered_id=$name.':'.$id; # this is to avoid make_key (which is slow) whenever possible
 3387:     if (exists($remembered{$remembered_id})) {
 3388: 	if ($debug) { &Apache::lonnet::logthis("Early return $remembered_id of $remembered{$remembered_id} "); }
 3389: 	$accessed{$remembered_id}=[&gettimeofday()];
 3390: 	$hits++;
 3391: 	return ($remembered{$remembered_id},1);
 3392:     }
 3393:     $id=&make_key($name,$id);
 3394:     my $value = $memcache->get($id);
 3395:     if (!(defined($value))) {
 3396: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
 3397: 	return (undef,undef);
 3398:     }
 3399:     if ($value eq '__undef__') {
 3400: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
 3401: 	$value=undef;
 3402:     }
 3403:     &make_room($remembered_id,$value,$debug);
 3404:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
 3405:     return ($value,1);
 3406: }
 3407: 
 3408: sub do_cache_new {
 3409:     my ($name,$id,$value,$time,$debug) = @_;
 3410:     my $remembered_id=$name.':'.$id;
 3411:     $id=&make_key($name,$id);
 3412:     my $setvalue=$value;
 3413:     if (!defined($setvalue)) {
 3414: 	$setvalue='__undef__';
 3415:     }
 3416:     if (!defined($time) ) {
 3417: 	$time=600;
 3418:     }
 3419:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
 3420:     my $result = $memcache->set($id,$setvalue,$time);
 3421:     if (! $result) {
 3422: 	&logthis("caching of id -> $id  failed");
 3423: 	$memcache->disconnect_all();
 3424:     }
 3425:     # need to make a copy of $value
 3426:     &make_room($remembered_id,$value,$debug);
 3427:     return $value;
 3428: }
 3429: 
 3430: sub make_room {
 3431:     my ($remembered_id,$value,$debug)=@_;
 3432: 
 3433:     $remembered{$remembered_id}= (ref($value)) ? &Storable::dclone($value)
 3434:                                     : $value;
 3435:     if ($to_remember<0) { return; }
 3436:     $accessed{$remembered_id}=[&gettimeofday()];
 3437:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
 3438:     my $to_kick;
 3439:     my $max_time=0;
 3440:     foreach my $other (keys(%accessed)) {
 3441: 	if (&tv_interval($accessed{$other}) > $max_time) {
 3442: 	    $to_kick=$other;
 3443: 	    $max_time=&tv_interval($accessed{$other});
 3444: 	}
 3445:     }
 3446:     delete($remembered{$to_kick});
 3447:     delete($accessed{$to_kick});
 3448:     $kicks++;
 3449:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
 3450:     return;
 3451: }
 3452: 
 3453: sub purge_remembered {
 3454:     #&logthis("Tossing ".scalar(keys(%remembered)));
 3455:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
 3456:     undef(%remembered);
 3457:     undef(%accessed);
 3458: }
 3459: # ------------------------------------- Read an entry from a user's environment
 3460: 
 3461: sub userenvironment {
 3462:     my ($udom,$unam,@what)=@_;
 3463:     my $items;
 3464:     foreach my $item (@what) {
 3465:         $items.=&escape($item).'&';
 3466:     }
 3467:     $items=~s/\&$//;
 3468:     my %returnhash=();
 3469:     my $uhome = &homeserver($unam,$udom);
 3470:     unless ($uhome eq 'no_host') {
 3471:         my @answer=split(/\&/, 
 3472:             &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
 3473:         if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
 3474:             return %returnhash;
 3475:         }
 3476:         my $i;
 3477:         for ($i=0;$i<=$#what;$i++) {
 3478: 	    $returnhash{$what[$i]}=&unescape($answer[$i]);
 3479:         }
 3480:     }
 3481:     return %returnhash;
 3482: }
 3483: 
 3484: # ---------------------------------------------------------- Get a studentphoto
 3485: sub studentphoto {
 3486:     my ($udom,$unam,$ext) = @_;
 3487:     my $home=&homeserver($unam,$udom);
 3488:     if (defined($env{'request.course.id'})) {
 3489:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
 3490:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
 3491:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
 3492:             } else {
 3493:                 my ($result,$perm_reqd)=
 3494: 		    &auto_photo_permission($unam,$udom);
 3495:                 if ($result eq 'ok') {
 3496:                     if (!($perm_reqd eq 'yes')) {
 3497:                         return(&retrievestudentphoto($udom,$unam,$ext));
 3498:                     }
 3499:                 }
 3500:             }
 3501:         }
 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:     return '/adm/lonKaputt/lonlogo_broken.gif';
 3512: }
 3513: 
 3514: sub retrievestudentphoto {
 3515:     my ($udom,$unam,$ext,$type) = @_;
 3516:     my $home=&homeserver($unam,$udom);
 3517:     my $ret=&reply("studentphoto:$udom:$unam:$ext:$type",$home);
 3518:     if ($ret eq 'ok') {
 3519:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
 3520:         if ($type eq 'thumbnail') {
 3521:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
 3522:         }
 3523:         my $tokenurl=&tokenwrapper($url);
 3524:         return $tokenurl;
 3525:     } else {
 3526:         if ($type eq 'thumbnail') {
 3527:             return '/adm/lonKaputt/genericstudent_tn.gif';
 3528:         } else { 
 3529:             return '/adm/lonKaputt/lonlogo_broken.gif';
 3530:         }
 3531:     }
 3532: }
 3533: 
 3534: # -------------------------------------------------------------------- New chat
 3535: 
 3536: sub chatsend {
 3537:     my ($newentry,$anon,$group)=@_;
 3538:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
 3539:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 3540:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
 3541:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
 3542: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
 3543: 		   &escape($newentry)).':'.$group,$chome);
 3544: }
 3545: 
 3546: # ------------------------------------------ Find current version of a resource
 3547: 
 3548: sub getversion {
 3549:     my $fname=&clutter(shift);
 3550:     unless ($fname=~m{^(/adm/wrapper|)/res/}) { return -1; }
 3551:     return &currentversion(&filelocation('',$fname));
 3552: }
 3553: 
 3554: sub currentversion {
 3555:     my $fname=shift;
 3556:     my $author=$fname;
 3557:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 3558:     my ($udom,$uname)=split(/\//,$author);
 3559:     my $home=&homeserver($uname,$udom);
 3560:     if ($home eq 'no_host') { 
 3561:         return -1; 
 3562:     }
 3563:     my $answer=&reply("currentversion:$fname",$home);
 3564:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
 3565: 	return -1;
 3566:     }
 3567:     return $answer;
 3568: }
 3569: 
 3570: #
 3571: # Return special version number of resource if set by override, empty otherwise
 3572: #
 3573: sub usedversion {
 3574:     my $fname=shift;
 3575:     unless ($fname) { $fname=$env{'request.uri'}; }
 3576:     my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
 3577:     if ($urlversion) { return $urlversion; }
 3578:     return '';
 3579: }
 3580: 
 3581: # ----------------------------- Subscribe to a resource, return URL if possible
 3582: 
 3583: sub subscribe {
 3584:     my $fname=shift;
 3585:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
 3586:     $fname=~s/[\n\r]//g;
 3587:     my $author=$fname;
 3588:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 3589:     my ($udom,$uname)=split(/\//,$author);
 3590:     my $home=homeserver($uname,$udom);
 3591:     if ($home eq 'no_host') {
 3592:         return 'not_found';
 3593:     }
 3594:     my $answer=reply("sub:$fname",$home);
 3595:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
 3596: 	$answer.=' by '.$home;
 3597:     }
 3598:     return $answer;
 3599: }
 3600:     
 3601: # -------------------------------------------------------------- Replicate file
 3602: 
 3603: sub repcopy {
 3604:     my $filename=shift;
 3605:     $filename=~s/\/+/\//g;
 3606:     my $londocroot = $perlvar{'lonDocRoot'};
 3607:     if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
 3608:     if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
 3609:     if ($filename=~m{^\Q$londocroot/userfiles/\E} or
 3610: 	$filename=~m{^/*(uploaded|editupload)/}) {
 3611: 	return &repcopy_userfile($filename);
 3612:     }
 3613:     $filename=~s/[\n\r]//g;
 3614:     my $transname="$filename.in.transfer";
 3615: # FIXME: this should flock
 3616:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
 3617:     my $remoteurl=subscribe($filename);
 3618:     if ($remoteurl =~ /^con_lost by/) {
 3619: 	   &logthis("Subscribe returned $remoteurl: $filename");
 3620:            return 'unavailable';
 3621:     } elsif ($remoteurl eq 'not_found') {
 3622: 	   #&logthis("Subscribe returned not_found: $filename");
 3623: 	   return 'not_found';
 3624:     } elsif ($remoteurl =~ /^rejected by/) {
 3625: 	   &logthis("Subscribe returned $remoteurl: $filename");
 3626:            return 'forbidden';
 3627:     } elsif ($remoteurl eq 'directory') {
 3628:            return 'ok';
 3629:     } else {
 3630:         my $author=$filename;
 3631:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 3632:         my ($udom,$uname)=split(/\//,$author);
 3633:         my $home=homeserver($uname,$udom);
 3634:         unless ($home eq $perlvar{'lonHostID'}) {
 3635:            my @parts=split(/\//,$filename);
 3636:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
 3637:            if ($path ne "$londocroot/res") {
 3638:                &logthis("Malconfiguration for replication: $filename");
 3639: 	       return 'bad_request';
 3640:            }
 3641:            my $count;
 3642:            for ($count=5;$count<$#parts;$count++) {
 3643:                $path.="/$parts[$count]";
 3644:                if ((-e $path)!=1) {
 3645: 		   mkdir($path,0777);
 3646:                }
 3647:            }
 3648:            my $request=new HTTP::Request('GET',"$remoteurl");
 3649:            my $response;
 3650:            if ($remoteurl =~ m{/raw/}) {
 3651:                $response=&LONCAPA::LWPReq::makerequest($home,$request,$transname,\%perlvar,'',0,1);
 3652:            } else {
 3653:                $response=&LONCAPA::LWPReq::makerequest($home,$request,$transname,\%perlvar,'',1);
 3654:            }
 3655:            if ($response->is_error()) {
 3656: 	       unlink($transname);
 3657:                my $message=$response->status_line;
 3658:                &logthis("<font color=\"blue\">WARNING:"
 3659:                        ." LWP get: $message: $filename</font>");
 3660:                return 'unavailable';
 3661:            } else {
 3662: 	       if ($remoteurl!~/\.meta$/) {
 3663:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
 3664:                   my $mresponse;
 3665:                   if ($remoteurl =~ m{/raw/}) {
 3666:                       $mresponse = &LONCAPA::LWPReq::makerequest($home,$mrequest,$filename.'.meta',\%perlvar,'',0,1);
 3667:                   } else {
 3668:                       $mresponse = &LONCAPA::LWPReq::makerequest($home,$mrequest,$filename.'.meta',\%perlvar,'',1);
 3669:                   }
 3670:                   if ($mresponse->is_error()) {
 3671: 		      unlink($filename.'.meta');
 3672:                       &logthis(
 3673:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
 3674:                   }
 3675: 	       }
 3676:                rename($transname,$filename);
 3677:                return 'ok';
 3678:            }
 3679:        }
 3680:     }
 3681: }
 3682: 
 3683: # ------------------------------------------------- Unsubscribe from a resource
 3684: 
 3685: sub unsubscribe {
 3686:     my ($fname) = @_;
 3687:     my $answer;
 3688:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return $answer; }
 3689:     $fname=~s/[\n\r]//g;
 3690:     my $author=$fname;
 3691:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 3692:     my ($udom,$uname)=split(/\//,$author);
 3693:     my $home=homeserver($uname,$udom);
 3694:     if ($home eq 'no_host') {
 3695:         $answer = 'no_host';
 3696:     } elsif (grep { $_ eq $home } &current_machine_ids()) {
 3697:         $answer = 'home';
 3698:     } else {
 3699:         my $defdom = $perlvar{'lonDefDomain'};
 3700:         if (&will_trust('content',$defdom,$udom)) {
 3701:             $answer = reply("unsub:$fname",$home);
 3702:         } else {
 3703:             $answer = 'untrusted';
 3704:         }
 3705:     }
 3706:     return $answer;
 3707: }
 3708: 
 3709: # ------------------------------------------------ Get server side include body
 3710: sub ssi_body {
 3711:     my ($filelink,%form)=@_;
 3712:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
 3713:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
 3714:     }
 3715:     my $output='';
 3716:     my $response;
 3717:     if ($filelink=~/^https?\:/) {
 3718:        ($output,$response)=&externalssi($filelink);
 3719:     } else {
 3720:        $filelink .= $filelink=~/\?/ ? '&' : '?';
 3721:        $filelink .= 'inhibitmenu=yes';
 3722:        ($output,$response)=&ssi($filelink,%form);
 3723:     }
 3724:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
 3725:     $output=~s/^.*?\<body[^\>]*\>//si;
 3726:     $output=~s/\<\/body\s*\>.*?$//si;
 3727:     if (wantarray) {
 3728:         return ($output, $response);
 3729:     } else {
 3730:         return $output;
 3731:     }
 3732: }
 3733: 
 3734: # --------------------------------------------------------- Server Side Include
 3735: 
 3736: sub absolute_url {
 3737:     my ($host_name,$unalias,$keep_proto) = @_;
 3738:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
 3739:     if ($host_name eq '') {
 3740: 	$host_name = $ENV{'SERVER_NAME'};
 3741:     }
 3742:     if ($unalias) {
 3743:         my $alias = &get_proxy_alias();
 3744:         if ($alias eq $host_name) {
 3745:             my $lonhost = $perlvar{'lonHostID'};
 3746:             my $hostname = &hostname($lonhost);
 3747:             my $lcproto; 
 3748:             if (($keep_proto) || ($hostname eq '')) {
 3749:                 $lcproto = $protocol;
 3750:             } else {
 3751:                 $lcproto = $protocol{$lonhost};
 3752:                 $lcproto = 'http' if ($lcproto ne 'https');
 3753:                 $lcproto .= '://';
 3754:             }
 3755:             unless ($hostname eq '') {
 3756:                 return $lcproto.$hostname;
 3757:             }
 3758:         }
 3759:     }
 3760:     return $protocol.$host_name;
 3761: }
 3762: 
 3763: #
 3764: #   Server side include.
 3765: # Parameters:
 3766: #  fn     Possibly encrypted resource name/id.
 3767: #  form   Hash that describes how the rendering should be done
 3768: #         and other things.
 3769: # Returns:
 3770: #   Scalar context: The content of the response.
 3771: #   Array context:  2 element list of the content and the full response object.
 3772: #     
 3773: sub ssi {
 3774: 
 3775:     my ($fn,%form)=@_;
 3776:     my ($host,$request,$response);
 3777:     $host = &absolute_url('',1);
 3778: 
 3779:     $form{'no_update_last_known'}=1;
 3780:     &Apache::lonenc::check_encrypt(\$fn);
 3781:     if (%form) {
 3782:       $request=new HTTP::Request('POST',$host.$fn);
 3783:       $request->content(join('&',map { 
 3784:             my $name = escape($_);
 3785:             "$name=" . ( ref($form{$_}) eq 'ARRAY' 
 3786:             ? join("&$name=", map {escape($_) } @{$form{$_}}) 
 3787:             : &escape($form{$_}) );    
 3788:         } keys(%form)));
 3789:     } else {
 3790:       $request=new HTTP::Request('GET',$host.$fn);
 3791:     }
 3792: 
 3793:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
 3794:     my $lonhost = $perlvar{'lonHostID'};
 3795:     my $islocal;
 3796:     if (($env{'request.course.id'}) &&
 3797:         ($form{'grade_courseid'} eq $env{'request.course.id'}) &&
 3798:         ($form{'grade_username'} ne '') && ($form{'grade_domain'} ne '') &&
 3799:         ($form{'grade_symb'} ne '') &&
 3800:         (&allowed('mgr',$env{'request.course.id'}.
 3801:                         ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:'')))) {
 3802:         $islocal = 1;
 3803:     }
 3804:     $response= &LONCAPA::LWPReq::makerequest($lonhost,$request,'',\%perlvar,
 3805:                                              '','','',$islocal);
 3806: 
 3807:     if (wantarray) {
 3808: 	return ($response->content, $response);
 3809:     } else {
 3810: 	return $response->content;
 3811:     }
 3812: }
 3813: 
 3814: sub externalssi {
 3815:     my ($url)=@_;
 3816:     my $request=new HTTP::Request('GET',$url);
 3817:     my $response = &LONCAPA::LWPReq::makerequest('',$request,'',\%perlvar);
 3818:     if (wantarray) {
 3819:         return ($response->content, $response);
 3820:     } else {
 3821:         return $response->content;
 3822:     }
 3823: }
 3824: 
 3825: 
 3826: # If the local copy of a replicated resource is outdated, trigger a  
 3827: # connection from the homeserver to flush the delayed queue. If no update 
 3828: # happens, remove local copies of outdated resource (and corresponding
 3829: # metadata file).
 3830: 
 3831: sub remove_stale_resfile {
 3832:     my ($url) = @_;
 3833:     my $removed;
 3834:     if ($url=~m{^/res/($match_domain)/($match_username)/}) {
 3835:         my $audom = $1;
 3836:         my $auname = $2;
 3837:         unless (($url =~ /\.\d+\.\w+$/) || ($url =~ m{^/res/lib/templates/})) {
 3838:             my $homeserver = &homeserver($auname,$audom);
 3839:             unless (($homeserver eq 'no_host') ||
 3840:                     (grep { $_ eq $homeserver } &current_machine_ids())) {
 3841:                 my $fname = &filelocation('',$url);
 3842:                 if (-e $fname) {
 3843:                     my $hostname = &hostname($homeserver);
 3844:                     if ($hostname) {
 3845:                         my $protocol = $protocol{$homeserver};
 3846:                         $protocol = 'http' if ($protocol ne 'https');
 3847:                         my $uri = &declutter($url);
 3848:                         my $request=new HTTP::Request('HEAD',$protocol.'://'.$hostname.'/raw/'.$uri);
 3849:                         my $response = &LONCAPA::LWPReq::makerequest($homeserver,$request,'',\%perlvar,5,0,1);
 3850:                         if ($response->is_success()) {
 3851:                             my $remmodtime = &HTTP::Date::str2time( $response->header('Last-modified') );
 3852:                             my $locmodtime = (stat($fname))[9];
 3853:                             if ($locmodtime < $remmodtime) {
 3854:                                 my $stale;
 3855:                                 my $answer = &reply('pong',$homeserver);
 3856:                                 if ($answer eq $homeserver.':'.$perlvar{'lonHostID'}) {
 3857:                                     sleep(0.2);
 3858:                                     $locmodtime = (stat($fname))[9];
 3859:                                     if ($locmodtime < $remmodtime) {
 3860:                                         my $posstransfer = $fname.'.in.transfer';
 3861:                                         if ((-e $posstransfer) && ($remmodtime < (stat($posstransfer))[9])) {
 3862:                                             $removed = 1;
 3863:                                         } else {
 3864:                                             $stale = 1;
 3865:                                         }
 3866:                                     } else {
 3867:                                         $removed = 1;
 3868:                                     }
 3869:                                 } else {
 3870:                                     $stale = 1;
 3871:                                 }
 3872:                                 if ($stale) {
 3873:                                     if (unlink($fname)) {
 3874:                                         if ($uri!~/\.meta$/) {
 3875:                                             if (-e $fname.'.meta') {
 3876:                                                 unlink($fname.'.meta');
 3877:                                             }
 3878:                                         }
 3879:                                         my $unsubresult = &unsubscribe($fname);
 3880:                                         unless ($unsubresult eq 'ok') {
 3881:                                             &logthis("no unsub of $fname from $homeserver, reason: $unsubresult");
 3882:                                         }
 3883:                                         $removed = 1;
 3884:                                     }
 3885:                                 }
 3886:                             }
 3887:                         }
 3888:                     }
 3889:                 }
 3890:             }
 3891:         }
 3892:     }
 3893:     return $removed;
 3894: }
 3895: 
 3896: # -------------------------------- Allow a /uploaded/ URI to be vouched for
 3897: 
 3898: sub allowuploaded {
 3899:     my ($srcurl,$url)=@_;
 3900:     $url=&clutter(&declutter($url));
 3901:     my $dir=$url;
 3902:     $dir=~s/\/[^\/]+$//;
 3903:     my %httpref=();
 3904:     my $httpurl=&hreflocation('',$url);
 3905:     $httpref{'httpref.'.$httpurl}=$srcurl;
 3906:     &Apache::lonnet::appenv(\%httpref);
 3907: }
 3908: 
 3909: #
 3910: # Determine if the current user should be able to edit a particular resource,
 3911: # when viewing in course context.
 3912: # (a) When viewing resource used to determine if "Edit" item is included in 
 3913: #     Functions.
 3914: # (b) When displaying folder contents in course editor, used to determine if
 3915: #     "Edit" link will be displayed alongside resource.
 3916: #
 3917: #  input: six args -- filename (decluttered), course number, course domain,
 3918: #                   url, symb (if registered) and group (if this is a group
 3919: #                   item -- e.g., bulletin board, group page etc.).
 3920: #  output: array of five scalars -- 
 3921: #          $cfile -- url for file editing if editable on current server
 3922: #          $home -- homeserver of resource (i.e., for author if published,
 3923: #                                           or course if uploaded.).
 3924: #          $switchserver --  1 if server switch will be needed.
 3925: #          $forceedit -- 1 if icon/link should be to go to edit mode 
 3926: #          $forceview -- 1 if icon/link should be to go to view mode
 3927: #
 3928: 
 3929: sub can_edit_resource {
 3930:     my ($file,$cnum,$cdom,$resurl,$symb,$group) = @_;
 3931:     my ($cfile,$home,$switchserver,$forceedit,$forceview,$uploaded,$incourse);
 3932: #
 3933: # For aboutme pages user can only edit his/her own.
 3934: #
 3935:     if ($resurl =~ m{^/?adm/($match_domain)/($match_username)/aboutme$}) {
 3936:         my ($sdom,$sname) = ($1,$2);
 3937:         if (($sdom eq $env{'user.domain'}) && ($sname eq $env{'user.name'})) {
 3938:             $home = $env{'user.home'};
 3939:             $cfile = $resurl;
 3940:             if ($env{'form.forceedit'}) {
 3941:                 $forceview = 1;
 3942:             } else {
 3943:                 $forceedit = 1;
 3944:             }
 3945:             return ($cfile,$home,$switchserver,$forceedit,$forceview);
 3946:         } else {
 3947:             return;
 3948:         }
 3949:     }
 3950: 
 3951: #
 3952: # For /adm/viewcoauthors can only edit if author or co-author who is manager.
 3953: #
 3954: 
 3955:     if (($resurl eq '/adm/viewcoauthors') && ($cnum ne '') && ($cdom ne '')) {
 3956:         if (((&allowed('cca',"$cdom/$cnum")) ||
 3957:              (&allowed('caa',"$cdom/$cnum"))) ||
 3958:              ((&allowed('vca',"$cdom/$cnum") ||
 3959:                &allowed('vaa',"$cdom/$cnum")) &&
 3960:               ($env{"environment.internal.manager./$cdom/$cnum"}))) {
 3961:             $home = $env{'user.home'};
 3962:             $cfile = $resurl;
 3963:             if ($env{'form.forceedit'}) {
 3964:                 $forceview = 1;
 3965:             } else {
 3966:                 $forceedit = 1;
 3967:             }
 3968:             return ($cfile,$home,$switchserver,$forceedit,$forceview);
 3969:         } else {
 3970:             return;
 3971:         }
 3972:     }
 3973: 
 3974:     if ($env{'request.course.id'}) {
 3975:         my $crsedit = &allowed('mdc',$env{'request.course.id'});
 3976:         if ($group ne '') {
 3977: # if this is a group homepage or group bulletin board, check group privs
 3978:             my $allowed = 0;
 3979:             if ($resurl =~ m{^/?adm/$cdom/$cnum/$group/smppg$}) {
 3980:                 if ((&allowed('mdg',$env{'request.course.id'}.
 3981:                               ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
 3982:                         (&allowed('mgh',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
 3983:                     $allowed = 1;
 3984:                 }
 3985:             } elsif ($resurl =~ m{^/?adm/$cdom/$cnum/\d+/bulletinboard$}) {
 3986:                 if ((&allowed('mdg',$env{'request.course.id'}.($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
 3987:                         (&allowed('cgb',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
 3988:                     $allowed = 1;
 3989:                 }
 3990:             }
 3991:             if ($allowed) {
 3992:                 $home=&homeserver($cnum,$cdom);
 3993:                 if ($env{'form.forceedit'}) {
 3994:                     $forceview = 1;
 3995:                 } else {
 3996:                     $forceedit = 1;
 3997:                 }
 3998:                 $cfile = $resurl;
 3999:             } else {
 4000:                 return;
 4001:             }
 4002:         } else {
 4003:             if ($resurl =~ m{^/?adm/viewclasslist$}) {
 4004:                 unless (&allowed('opa',$env{'request.course.id'})) {
 4005:                     return;
 4006:                 }
 4007:             } elsif (!$crsedit) {
 4008:                 if ($env{'request.role'} =~ m{^st\./$cdom/$cnum}) {
 4009: #
 4010: # No edit allowed where CC has switched to student role.
 4011: #
 4012:                     return;
 4013:                 } elsif (($resurl !~ m{^/res/$match_domain/$match_username/}) ||
 4014:                          ($resurl =~ m{^/res/lib/templates/})) {
 4015:                     return;
 4016:                 }
 4017:             }
 4018:         }
 4019:     }
 4020: 
 4021:     if ($file ne '') {
 4022:         if (($cnum =~ /$match_courseid/) && ($cdom =~ /$match_domain/)) {
 4023:             if (&is_course_upload($file,$cnum,$cdom)) {
 4024:                 $uploaded = 1;
 4025:                 $incourse = 1;
 4026:                 if ($file =~/\.(htm|html|css|js|txt)$/) {
 4027:                     $cfile = &hreflocation('',$file);
 4028:                     if ($env{'form.forceedit'}) {
 4029:                         $forceview = 1;
 4030:                     } else {
 4031:                         $forceedit = 1;
 4032:                     }
 4033:                 }
 4034:             } elsif ($resurl =~ m{^/public/$cdom/$cnum/syllabus}) {
 4035:                 $incourse = 1;
 4036:                 if ($env{'form.forceedit'}) {
 4037:                     $forceview = 1;
 4038:                 } else {
 4039:                     $forceedit = 1;
 4040:                 }
 4041:                 $cfile = $resurl;
 4042:             } elsif (($resurl ne '') && (&is_on_map($resurl))) {
 4043:                 if ($resurl =~ m{^/adm/$match_domain/$match_username/\d+/smppg|bulletinboard$}) {
 4044:                     $incourse = 1;
 4045:                     if ($env{'form.forceedit'}) {
 4046:                         $forceview = 1;
 4047:                     } else {
 4048:                         $forceedit = 1;
 4049:                     }
 4050:                     $cfile = $resurl;
 4051:                 } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem') {
 4052:                     $incourse = 1;
 4053:                     $cfile = $resurl.'/smpedit';
 4054:                 } elsif ($resurl =~ m{^/adm/wrapper/ext/}) {
 4055:                     $incourse = 1;
 4056:                     if ($env{'form.forceedit'}) {
 4057:                         $forceview = 1;
 4058:                     } else {
 4059:                         $forceedit = 1;
 4060:                     }
 4061:                     $cfile = $resurl;
 4062:                 } elsif (($resurl =~ m{^/ext/}) && ($symb ne '')) {
 4063:                     my ($map,$id,$res) = &decode_symb($symb);
 4064:                     if ($map =~ /\.page$/) {
 4065:                         $incourse = 1;
 4066:                         if ($env{'form.forceedit'}) {
 4067:                             $forceview = 1;
 4068:                             $cfile = $map;
 4069:                         } else {
 4070:                             $forceedit = 1;
 4071:                             $cfile =  '/adm/wrapper'.$resurl;
 4072:                         }
 4073:                     }
 4074:                 } elsif ($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/ext\.tool$}) {
 4075:                     $incourse = 1;
 4076:                     if ($env{'form.forceedit'}) {
 4077:                         $forceview = 1;
 4078:                     } else {
 4079:                         $forceedit = 1;
 4080:                     }
 4081:                     $cfile = $resurl;
 4082:                 } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
 4083:                     $incourse = 1;
 4084:                     if ($env{'form.forceedit'}) {
 4085:                         $forceview = 1;
 4086:                     } else {
 4087:                         $forceedit = 1;
 4088:                     }
 4089:                     $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
 4090:                 }
 4091:             } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem/smpedit') {
 4092:                 my $template = '/res/lib/templates/simpleproblem.problem';
 4093:                 if (&is_on_map($template)) { 
 4094:                     $incourse = 1;
 4095:                     $forceview = 1;
 4096:                     $cfile = $template;
 4097:                 }
 4098:             } elsif (($resurl =~ m{^/adm/wrapper/ext/}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
 4099:                 $incourse = 1;
 4100:                 if ($env{'form.forceedit'}) {
 4101:                     $forceview = 1;
 4102:                 } else {
 4103:                     $forceedit = 1;
 4104:                 }
 4105:                 $cfile = $resurl;
 4106:             } elsif (($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/ext\.tool$}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
 4107:                 $incourse = 1;
 4108:                 if ($env{'form.forceedit'}) {
 4109:                     $forceview = 1;
 4110:                 } else {
 4111:                     $forceedit = 1;
 4112:                 }
 4113:                 $cfile = $resurl;
 4114:             } elsif (($resurl eq '/adm/extresedit') && ($symb || $env{'form.folderpath'})) {
 4115:                 $incourse = 1;
 4116:                 $forceview = 1;
 4117:                 if ($symb) {
 4118:                     my ($map,$id,$res)=&decode_symb($symb);
 4119:                     $env{'request.symb'} = $symb;
 4120:                     $cfile = &clutter($res);
 4121:                 } else {
 4122:                     $cfile = $env{'form.suppurl'};
 4123:                     my $escfile = &unescape($cfile);
 4124:                     if ($escfile =~ m{^/adm/$cdom/$cnum/\d+/ext\.tool$}) {
 4125:                         $cfile = '/adm/wrapper'.$escfile;
 4126:                     } else {
 4127:                         $escfile =~ s{^http://}{};
 4128:                         $cfile = &escape("/adm/wrapper/ext/$escfile");
 4129:                     }
 4130:                 }
 4131:             } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
 4132:                 if ($env{'form.forceedit'}) {
 4133:                     $forceview = 1;
 4134:                 } else {
 4135:                     $forceedit = 1;
 4136:                 }
 4137:                 $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
 4138:             }
 4139:         }
 4140:         if ($uploaded || $incourse) {
 4141:             $home=&homeserver($cnum,$cdom);
 4142:         } elsif ($file !~ m{/$}) {
 4143:             $file=~s{^(priv/$match_domain/$match_username)}{/$1};
 4144:             $file=~s{^($match_domain/$match_username)}{/priv/$1};
 4145:             # Check that the user has permission to edit this resource
 4146:             my $setpriv = 1;
 4147:             my ($cfuname,$cfudom)=&constructaccess($file,$setpriv);
 4148:             if (defined($cfudom)) {
 4149:                 $home=&homeserver($cfuname,$cfudom);
 4150:                 $cfile=$file;
 4151:             }
 4152:         }
 4153:         if (($cfile ne '') && (!$incourse || $uploaded) && 
 4154:             (($home ne '') && ($home ne 'no_host'))) {
 4155:             my @ids=&current_machine_ids();
 4156:             unless (grep(/^\Q$home\E$/,@ids)) {
 4157:                 $switchserver=1;
 4158:             }
 4159:         }
 4160:     }
 4161:     return ($cfile,$home,$switchserver,$forceedit,$forceview);
 4162: }
 4163: 
 4164: sub is_course_upload {
 4165:     my ($file,$cnum,$cdom) = @_;
 4166:     my $uploadpath = &LONCAPA::propath($cdom,$cnum);
 4167:     $uploadpath =~ s{^\/}{};
 4168:     if (($file =~ m{^\Q$uploadpath\E/userfiles/(docs|supplemental)/}) ||
 4169:         ($file =~ m{^userfiles/\Q$cdom\E/\Q$cnum\E/(docs|supplemental)/})) {
 4170:         return 1;
 4171:     }
 4172:     return;
 4173: }
 4174: 
 4175: sub in_course {
 4176:     my ($udom,$uname,$cdom,$cnum,$type,$hideprivileged) = @_;
 4177:     if ($hideprivileged) {
 4178:         my $skipuser;
 4179:         my %coursehash = &coursedescription($cdom.'_'.$cnum);
 4180:         my @possdoms = ($cdom);  
 4181:         if ($coursehash{'checkforpriv'}) { 
 4182:             push(@possdoms,split(/,/,$coursehash{'checkforpriv'})); 
 4183:         }
 4184:         if (&privileged($uname,$udom,\@possdoms)) {
 4185:             $skipuser = 1;
 4186:             if ($coursehash{'nothideprivileged'}) {
 4187:                 foreach my $item (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 4188:                     my $user;
 4189:                     if ($item =~ /:/) {
 4190:                         $user = $item;
 4191:                     } else {
 4192:                         $user = join(':',split(/[\@]/,$item));
 4193:                     }
 4194:                     if ($user eq $uname.':'.$udom) {
 4195:                         undef($skipuser);
 4196:                         last;
 4197:                     }
 4198:                 }
 4199:             }
 4200:             if ($skipuser) {
 4201:                 return 0;
 4202:             }
 4203:         }
 4204:     }
 4205:     $type ||= 'any';
 4206:     if (!defined($cdom) || !defined($cnum)) {
 4207:         my $cid  = $env{'request.course.id'};
 4208:         $cdom = $env{'course.'.$cid.'.domain'};
 4209:         $cnum = $env{'course.'.$cid.'.num'};
 4210:     }
 4211:     my $typesref;
 4212:     if (($type eq 'any') || ($type eq 'all')) {
 4213:         $typesref = ['active','previous','future'];
 4214:     } elsif ($type eq 'previous' || $type eq 'future') {
 4215:         $typesref = [$type];
 4216:     }
 4217:     my %roles = &get_my_roles($uname,$udom,'userroles',
 4218:                               $typesref,undef,[$cdom]);
 4219:     my ($tmp) = keys(%roles);
 4220:     return 0 if ($tmp =~ /^(con_lost|error|no_such_host)/i);
 4221:     my @course_roles = grep(/^\Q$cnum\E:\Q$cdom\E:/, keys(%roles));
 4222:     if (@course_roles > 0) {
 4223:         return 1;
 4224:     }
 4225:     return 0;
 4226: }
 4227: 
 4228: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
 4229: # input: action, courseID, current domain, intended
 4230: #        path to file, source of file, instruction to parse file for objects,
 4231: #        ref to hash for embedded objects,
 4232: #        ref to hash for codebase of java objects.
 4233: #        reference to scalar to accommodate mime type determined
 4234: #          from File::MMagic if $parser = parse.
 4235: #
 4236: # output: url to file (if action was uploaddoc), 
 4237: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
 4238: #
 4239: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
 4240: # course.
 4241: #
 4242: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 4243: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
 4244: #          course's home server.
 4245: #
 4246: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
 4247: #          be copied from $source (current location) to 
 4248: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 4249: #         and will then be copied to
 4250: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
 4251: #         course's home server.
 4252: #
 4253: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 4254: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
 4255: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 4256: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
 4257: #         in course's home server.
 4258: #
 4259: 
 4260: sub process_coursefile {
 4261:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
 4262:         $mimetype)=@_;
 4263:     my $fetchresult;
 4264:     my $home=&homeserver($docuname,$docudom);
 4265:     if ($action eq 'propagate') {
 4266:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 4267: 			     $home);
 4268:     } else {
 4269:         my $fpath = '';
 4270:         my $fname = $file;
 4271:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 4272:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 4273:         my $filepath = &build_filepath($fpath);
 4274:         if ($action eq 'copy') {
 4275:             if ($source eq '') {
 4276:                 $fetchresult = 'no source file';
 4277:                 return $fetchresult;
 4278:             } else {
 4279:                 my $destination = $filepath.'/'.$fname;
 4280:                 rename($source,$destination);
 4281:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 4282:                                  $home);
 4283:             }
 4284:         } elsif ($action eq 'uploaddoc') {
 4285:             open(my $fh,'>',$filepath.'/'.$fname);
 4286:             print $fh $env{'form.'.$source};
 4287:             close($fh);
 4288:             if ($parser eq 'parse') {
 4289:                 my $mm = new File::MMagic;
 4290:                 my $type = $mm->checktype_filename($filepath.'/'.$fname);
 4291:                 if ($type eq 'text/html') {
 4292:                     my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
 4293:                     unless ($parse_result eq 'ok') {
 4294:                         &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
 4295:                     }
 4296:                 }
 4297:                 if (ref($mimetype)) {
 4298:                     $$mimetype = $type;
 4299:                 } 
 4300:             }
 4301:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 4302:                                  $home);
 4303:             if ($fetchresult eq 'ok') {
 4304:                 return '/uploaded/'.$fpath.'/'.$fname;
 4305:             } else {
 4306:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 4307:                         ' to host '.$home.': '.$fetchresult);
 4308:                 return '/adm/notfound.html';
 4309:             }
 4310:         }
 4311:     }
 4312:     unless ( $fetchresult eq 'ok') {
 4313:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 4314:              ' to host '.$home.': '.$fetchresult);
 4315:     }
 4316:     return $fetchresult;
 4317: }
 4318: 
 4319: sub build_filepath {
 4320:     my ($fpath) = @_;
 4321:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
 4322:     unless ($fpath eq '') {
 4323:         my @parts=split('/',$fpath);
 4324:         foreach my $part (@parts) {
 4325:             $filepath.= '/'.$part;
 4326:             if ((-e $filepath)!=1) {
 4327:                 mkdir($filepath,0777);
 4328:             }
 4329:         }
 4330:     }
 4331:     return $filepath;
 4332: }
 4333: 
 4334: sub store_edited_file {
 4335:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
 4336:     my $file = $primary_url;
 4337:     $file =~ s#^/uploaded/$docudom/$docuname/##;
 4338:     my $fpath = '';
 4339:     my $fname = $file;
 4340:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 4341:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 4342:     my $filepath = &build_filepath($fpath);
 4343:     open(my $fh,'>',$filepath.'/'.$fname);
 4344:     print $fh $content;
 4345:     close($fh);
 4346:     my $home=&homeserver($docuname,$docudom);
 4347:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 4348: 			  $home);
 4349:     if ($$fetchresult eq 'ok') {
 4350:         return '/uploaded/'.$fpath.'/'.$fname;
 4351:     } else {
 4352:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 4353: 		 ' to host '.$home.': '.$$fetchresult);
 4354:         return '/adm/notfound.html';
 4355:     }
 4356: }
 4357: 
 4358: sub clean_filename {
 4359:     my ($fname,$args)=@_;
 4360: # Replace Windows backslashes by forward slashes
 4361:     $fname=~s/\\/\//g;
 4362:     if (!$args->{'keep_path'}) {
 4363:         # Get rid of everything but the actual filename
 4364: 	$fname=~s/^.*\/([^\/]+)$/$1/;
 4365:     }
 4366: # Replace spaces by underscores
 4367:     $fname=~s/\s+/\_/g;
 4368: # Transliterate non-ascii text to ascii
 4369:     my $lang = &Apache::lonlocal::current_language();
 4370:     $fname = &LONCAPA::transliterate::fname_to_ascii($fname,$lang);
 4371: # Replace all other weird characters by nothing
 4372:     $fname=~s{[^/\w\.\-]}{}g;
 4373: # Replace all .\d. sequences with _\d. so they no longer look like version
 4374: # numbers
 4375:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
 4376: # Replace three or more adjacent underscores with one for consistency 
 4377: # with loncfile::filename_check() so complete url can be extracted by
 4378: # lonnet::decode_symb()
 4379:     $fname=~s/_{3,}/_/g;
 4380:     return $fname;
 4381: }
 4382: 
 4383: # This Function checks if an Image's dimensions exceed either $resizewidth (width) 
 4384: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an 
 4385: # image with the same aspect ratio as the original, but with dimensions which do 
 4386: # not exceed $resizewidth and $resizeheight.
 4387:  
 4388: sub resizeImage {
 4389:     my ($img_path,$resizewidth,$resizeheight) = @_;
 4390:     my $ima = Image::Magick->new;
 4391:     my $resized;
 4392:     if (-e $img_path) {
 4393:         $ima->Read($img_path);
 4394:         if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
 4395:             my $width = $ima->Get('width');
 4396:             my $height = $ima->Get('height');
 4397:             if ($width > $resizewidth) {
 4398: 	        my $factor = $width/$resizewidth;
 4399:                 my $newheight = $height/$factor;
 4400:                 $ima->Scale(width=>$resizewidth,height=>$newheight);
 4401:                 $resized = 1;
 4402:             }
 4403:         }
 4404:         if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
 4405:             my $width = $ima->Get('width');
 4406:             my $height = $ima->Get('height');
 4407:             if ($height > $resizeheight) {
 4408:                 my $factor = $height/$resizeheight;
 4409:                 my $newwidth = $width/$factor;
 4410:                 $ima->Scale(width=>$newwidth,height=>$resizeheight);
 4411:                 $resized = 1;
 4412:             }
 4413:         }
 4414:         if ($resized) {
 4415:             $ima->Write($img_path);
 4416:         }
 4417:     }
 4418:     return;
 4419: }
 4420: 
 4421: # --------------- Take an uploaded file and put it into the userfiles directory
 4422: # input: $formname - the contents of the file are in $env{"form.$formname"}
 4423: #                    the desired filename is in $env{"form.$formname.filename"}
 4424: #        $context - possible values: coursedoc, existingfile, overwrite, 
 4425: #                                    canceloverwrite, scantron, toollogo  or ''.
 4426: #                   if 'coursedoc': upload to the current course
 4427: #                   if 'existingfile': write file to tmp/overwrites directory 
 4428: #                   if 'canceloverwrite': delete file written to tmp/overwrites directory
 4429: #                   $context is passed as argument to &finishuserfileupload
 4430: #        $subdir - directory in userfile to store the file into
 4431: #        $parser - instruction to parse file for objects ($parser = parse) or
 4432: #                  if context is 'scantron', $parser is hashref of csv column mapping
 4433: #                  (e.g.,{ PaperID => 0, LastName => 1, FirstName => 2, ID => 3, 
 4434: #                          Section => 4, CODE => 5, FirstQuestion => 9 }).
 4435: #        $allfiles - reference to hash for embedded objects
 4436: #        $codebase - reference to hash for codebase of java objects
 4437: #        $destuname - username for permanent storage of uploaded file
 4438: #        $destudom - domain for permanaent storage of uploaded file
 4439: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
 4440: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
 4441: #        $resizewidth - width (pixels) to which to resize uploaded image
 4442: #        $resizeheight - height (pixels) to which to resize uploaded image
 4443: #        $mimetype - reference to scalar to accommodate mime type determined
 4444: #                    from File::MMagic.
 4445: # 
 4446: # output: url of file in userspace, or error: <message> 
 4447: #             or /adm/notfound.html if failure to upload occurse
 4448: 
 4449: sub userfileupload {
 4450:     my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
 4451:         $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
 4452:     if (!defined($subdir)) { $subdir='unknown'; }
 4453:     my $fname=$env{'form.'.$formname.'.filename'};
 4454:     $fname=&clean_filename($fname);
 4455:     # See if there is anything left
 4456:     unless ($fname) { return 'error: no uploaded file'; }
 4457:     # If filename now begins with a . prepend unix timestamp _ milliseconds
 4458:     if ($fname =~ /^\./) {
 4459:         my ($s,$usec) = &gettimeofday();
 4460:         while (length($usec) < 6) {
 4461:             $usec = '0'.$usec;
 4462:         }
 4463:         $fname = $s.'_'.substr($usec,0,3).$fname;
 4464:     }
 4465:     # Files uploaded to help request form, or uploaded to "create course" page are handled differently
 4466:     if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
 4467:         (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
 4468:          ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
 4469:         my $now = time;
 4470:         my $filepath;
 4471:         if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
 4472:              $filepath = 'tmp/helprequests/'.$now;
 4473:         } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
 4474:              $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
 4475:                          '_'.$env{'user.domain'}.'/pending';
 4476:         } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
 4477:             my ($docuname,$docudom);
 4478:             if ($destudom =~ /^$match_domain$/) {
 4479:                 $docudom = $destudom;
 4480:             } else {
 4481:                 $docudom = $env{'user.domain'};
 4482:             }
 4483:             if ($destuname =~ /^$match_username$/) {
 4484:                 $docuname = $destuname;
 4485:             } else {
 4486:                 $docuname = $env{'user.name'};
 4487:             }
 4488:             if (exists($env{'form.group'})) {
 4489:                 $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 4490:                 $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 4491:             }
 4492:             $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
 4493:             if ($context eq 'canceloverwrite') {
 4494:                 my $tempfile =  $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
 4495:                 if (-e  $tempfile) {
 4496:                     my @info = stat($tempfile);
 4497:                     if ($info[9] eq $env{'form.timestamp'}) {
 4498:                         unlink($tempfile);
 4499:                     }
 4500:                 }
 4501:                 return;
 4502:             }
 4503:         }
 4504:         # Create the directory if not present
 4505:         my @parts=split(/\//,$filepath);
 4506:         my $fullpath = $perlvar{'lonDaemons'};
 4507:         for (my $i=0;$i<@parts;$i++) {
 4508:             $fullpath .= '/'.$parts[$i];
 4509:             if ((-e $fullpath)!=1) {
 4510:                 mkdir($fullpath,0777);
 4511:             }
 4512:         }
 4513:         open(my $fh,'>',$fullpath.'/'.$fname);
 4514:         print $fh $env{'form.'.$formname};
 4515:         close($fh);
 4516:         if ($context eq 'existingfile') {
 4517:             my @info = stat($fullpath.'/'.$fname);
 4518:             return ($fullpath.'/'.$fname,$info[9]);
 4519:         } else {
 4520:             return $fullpath.'/'.$fname;
 4521:         }
 4522:     }
 4523:     if ($subdir eq 'scantron') {
 4524:         $fname = 'scantron_orig_'.$fname;
 4525:     } else {
 4526:         $fname="$subdir/$fname";
 4527:     }
 4528:     if ($context eq 'coursedoc') {
 4529: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 4530: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 4531:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
 4532:             return &finishuserfileupload($docuname,$docudom,
 4533: 					 $formname,$fname,$parser,$allfiles,
 4534: 					 $codebase,$thumbwidth,$thumbheight,
 4535:                                          $resizewidth,$resizeheight,$context,$mimetype);
 4536:         } else {
 4537:             if ($env{'form.folder'}) {
 4538:                 $fname=$env{'form.folder'}.'/'.$fname;
 4539:             }
 4540:             return &process_coursefile('uploaddoc',$docuname,$docudom,
 4541: 				       $fname,$formname,$parser,
 4542: 				       $allfiles,$codebase,$mimetype);
 4543:         }
 4544:     } elsif (defined($destuname)) {
 4545:         my $docuname=$destuname;
 4546:         my $docudom=$destudom;
 4547: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
 4548: 				     $parser,$allfiles,$codebase,
 4549:                                      $thumbwidth,$thumbheight,
 4550:                                      $resizewidth,$resizeheight,$context,$mimetype);
 4551:     } else {
 4552:         my $docuname=$env{'user.name'};
 4553:         my $docudom=$env{'user.domain'};
 4554:         if ((exists($env{'form.group'})) || ($context eq 'syllabus')) {
 4555:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 4556:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 4557:         }
 4558: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
 4559: 				     $parser,$allfiles,$codebase,
 4560:                                      $thumbwidth,$thumbheight,
 4561:                                      $resizewidth,$resizeheight,$context,$mimetype);
 4562:     }
 4563: }
 4564: 
 4565: sub finishuserfileupload {
 4566:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
 4567:         $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
 4568:     my $path=$docudom.'/'.$docuname.'/';
 4569:     my $filepath=$perlvar{'lonDocRoot'};
 4570:   
 4571:     my ($fnamepath,$file,$fetchthumb);
 4572:     $file=$fname;
 4573:     if ($fname=~m|/|) {
 4574:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
 4575: 	$path.=$fnamepath.'/';
 4576:     }
 4577:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
 4578:     my $count;
 4579:     for ($count=4;$count<=$#parts;$count++) {
 4580:         $filepath.="/$parts[$count]";
 4581:         if ((-e $filepath)!=1) {
 4582: 	    mkdir($filepath,0777);
 4583:         }
 4584:     }
 4585: 
 4586: # Save the file
 4587:     {
 4588: 	if (!open(FH,'>',$filepath.'/'.$file)) {
 4589: 	    &logthis('Failed to create '.$filepath.'/'.$file);
 4590: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
 4591: 	    return '/adm/notfound.html';
 4592: 	}
 4593:         if ($context eq 'overwrite') {
 4594:             my $source =  LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
 4595:             my $target = $filepath.'/'.$file;
 4596:             if (-e $source) {
 4597:                 my @info = stat($source);
 4598:                 if ($info[9] eq $env{'form.timestamp'}) {   
 4599:                     unless (&File::Copy::move($source,$target)) {
 4600:                         &logthis('Failed to overwrite '.$filepath.'/'.$file);
 4601:                         return "Moving from $source failed";
 4602:                     }
 4603:                 } else {
 4604:                     return "Temporary file: $source had unexpected date/time for last modification";
 4605:                 }
 4606:             } else {
 4607:                 return "Temporary file: $source missing";
 4608:             }
 4609:         } elsif (!print FH ($env{'form.'.$formname})) {
 4610: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
 4611: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
 4612: 	    return '/adm/notfound.html';
 4613: 	}
 4614: 	close(FH);
 4615:         if ($resizewidth && $resizeheight) {
 4616:             my $mm = new File::MMagic;
 4617:             my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
 4618:             if ($mime_type =~ m{^image/}) {
 4619: 	        &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
 4620:             }  
 4621: 	}
 4622:     }
 4623:     if (($context eq 'coursedoc') || ($parser eq 'parse')) {
 4624:         if (ref($mimetype)) {
 4625:             if ($$mimetype eq '') {
 4626:                 my $mm = new File::MMagic;
 4627:                 my $type = $mm->checktype_filename($filepath.'/'.$file);
 4628:                 $$mimetype = $type;
 4629:             }
 4630:         }
 4631:     }
 4632:     if (($context ne 'scantron') && ($parser eq 'parse')) {
 4633:         if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
 4634:             my $parse_result = &extract_embedded_items($filepath.'/'.$file,
 4635:                                                        $allfiles,$codebase);
 4636:             unless ($parse_result eq 'ok') {
 4637:                 &logthis('Failed to parse '.$filepath.$file.
 4638: 	   	         ' for embedded media: '.$parse_result); 
 4639:             }
 4640:         }
 4641:     } elsif (($context eq 'scantron') && (ref($parser) eq 'HASH')) {
 4642:         my $format = $env{'form.scantron_format'};
 4643:         &bubblesheet_converter($docudom,$filepath.'/'.$file,$parser,$format);
 4644:     }
 4645:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
 4646:         my $input = $filepath.'/'.$file;
 4647:         my $output = $filepath.'/'.'tn-'.$file;
 4648:         my $makethumb; 
 4649:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
 4650:         if ($context eq 'toollogo') {
 4651:             my ($fullwidth,$fullheight) = &check_dimensions($input);
 4652:             if ($fullwidth ne '' && $fullheight ne '') {
 4653:                 if ($fullwidth > $thumbwidth && $fullheight > $thumbheight) {
 4654:                     $makethumb = 1;
 4655:                 }
 4656:             }
 4657:         } else {
 4658:             $makethumb = 1;
 4659:         }
 4660:         if ($makethumb) {
 4661:             my @args = ('convert','-sample',$thumbsize,$input,$output);
 4662:             system({$args[0]} @args);
 4663:             if (-e $filepath.'/'.'tn-'.$file) {
 4664:                 $fetchthumb  = 1; 
 4665:             }
 4666:         }
 4667:     }
 4668:  
 4669: # Notify homeserver to grep it
 4670: #
 4671:     my $docuhome=&homeserver($docuname,$docudom);	
 4672:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
 4673:     if ($fetchresult eq 'ok') {
 4674:         if ($fetchthumb) {
 4675:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
 4676:             if ($thumbresult ne 'ok') {
 4677:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
 4678:                          $docuhome.': '.$thumbresult);
 4679:             }
 4680:         }
 4681: #
 4682: # Return the URL to it
 4683:         return '/uploaded/'.$path.$file;
 4684:     } else {
 4685:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
 4686: 		 ': '.$fetchresult);
 4687:         return '/adm/notfound.html';
 4688:     }
 4689: }
 4690: 
 4691: sub extract_embedded_items {
 4692:     my ($fullpath,$allfiles,$codebase,$content) = @_;
 4693:     my @state = ();
 4694:     my (%lastids,%related,%shockwave,%flashvars);
 4695:     my %javafiles = (
 4696:                       codebase => '',
 4697:                       code => '',
 4698:                       archive => ''
 4699:                     );
 4700:     my %mediafiles = (
 4701:                       src => '',
 4702:                       movie => '',
 4703:                      );
 4704:     my $p;
 4705:     if ($content) {
 4706:         $p = HTML::LCParser->new($content);
 4707:     } else {
 4708:         $p = HTML::LCParser->new($fullpath);
 4709:     }
 4710:     while (my $t=$p->get_token()) {
 4711: 	if ($t->[0] eq 'S') {
 4712: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
 4713: 	    push(@state, $tagname);
 4714:             if (lc($tagname) eq 'allow') {
 4715:                 &add_filetype($allfiles,$attr->{'src'},'src');
 4716:             }
 4717: 	    if (lc($tagname) eq 'img') {
 4718: 		&add_filetype($allfiles,$attr->{'src'},'src');
 4719: 	    }
 4720: 	    if (lc($tagname) eq 'a') {
 4721:                 unless (($attr->{'href'} =~ /^#/) || ($attr->{'href'} eq '')) {
 4722:                     &add_filetype($allfiles,$attr->{'href'},'href');
 4723:                 }
 4724: 	    }
 4725:             if (lc($tagname) eq 'script') {
 4726:                 my $src;
 4727:                 if ($attr->{'archive'} =~ /\.jar$/i) {
 4728:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
 4729:                 } else {
 4730:                     if ($attr->{'src'} ne '') {
 4731:                         $src = $attr->{'src'};
 4732:                         &add_filetype($allfiles,$src,'src');
 4733:                     }
 4734:                 }
 4735:                 my $text = $p->get_trimmed_text();
 4736:                 if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
 4737:                     my @swfargs = split(/,/,$1);
 4738:                     foreach my $item (@swfargs) {
 4739:                         $item =~ s/["']//g;
 4740:                         $item =~ s/^\s+//;
 4741:                         $item =~ s/\s+$//;
 4742:                     }
 4743:                     if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
 4744:                         if (ref($related{$swfargs[0]}) eq 'ARRAY') {
 4745:                             push(@{$related{$swfargs[0]}},$swfargs[2]);
 4746:                         } else {
 4747:                             $related{$swfargs[0]} = [$swfargs[2]];
 4748:                         }
 4749:                     }
 4750:                 }
 4751:             }
 4752:             if (lc($tagname) eq 'link') {
 4753:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
 4754:                     &add_filetype($allfiles,$attr->{'href'},'href');
 4755:                 }
 4756:             }
 4757: 	    if (lc($tagname) eq 'object' ||
 4758: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
 4759: 		foreach my $item (keys(%javafiles)) {
 4760: 		    $javafiles{$item} = '';
 4761: 		}
 4762:                 if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
 4763:                     $lastids{lc($tagname)} = $attr->{'id'};
 4764:                 }
 4765: 	    }
 4766: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
 4767: 		my $name = lc($attr->{'name'});
 4768: 		foreach my $item (keys(%javafiles)) {
 4769: 		    if ($name eq $item) {
 4770: 			$javafiles{$item} = $attr->{'value'};
 4771: 			last;
 4772: 		    }
 4773: 		}
 4774:                 my $pathfrom;
 4775: 		foreach my $item (keys(%mediafiles)) {
 4776: 		    if ($name eq $item) {
 4777:                         $pathfrom = $attr->{'value'};
 4778:                         $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
 4779: 			&add_filetype($allfiles,$pathfrom,$name);
 4780: 			last;
 4781: 		    }
 4782: 		}
 4783:                 if ($name eq 'flashvars') {
 4784:                     $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
 4785:                 }
 4786:                 if ($pathfrom ne '') {
 4787:                     &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
 4788:                                          $pathfrom);
 4789:                 }
 4790: 	    }
 4791: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
 4792: 		foreach my $item (keys(%javafiles)) {
 4793: 		    if ($attr->{$item}) {
 4794: 			$javafiles{$item} = $attr->{$item};
 4795: 			last;
 4796: 		    }
 4797: 		}
 4798: 		foreach my $item (keys(%mediafiles)) {
 4799: 		    if ($attr->{$item}) {
 4800: 			&add_filetype($allfiles,$attr->{$item},$item);
 4801: 			last;
 4802: 		    }
 4803: 		}
 4804:                 if (lc($tagname) eq 'embed') {
 4805:                     if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
 4806:                         &embedded_dependency($allfiles,\%related,$attr->{'name'},
 4807:                                              $attr->{'src'});
 4808:                     }
 4809:                 }
 4810: 	    }
 4811:             if (lc($tagname) eq 'iframe') {
 4812:                 my $src = $attr->{'src'} ;
 4813:                 if (($src ne '') && ($src !~ m{^(/|https?://)})) {
 4814:                     &add_filetype($allfiles,$src,'src');
 4815:                 } elsif ($src =~ m{^/}) {
 4816:                     if ($env{'request.course.id'}) {
 4817:                         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 4818:                         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 4819:                         my $url = &hreflocation('',$fullpath);
 4820:                         if ($url =~ m{^/uploaded/$cdom/$cnum/docs/(\w+/\d+)/}) {
 4821:                             my $relpath = $1;
 4822:                             if ($src =~ m{^/uploaded/$cdom/$cnum/docs/\Q$relpath\E/(.+)$}) {
 4823:                                 &add_filetype($allfiles,$1,'src');
 4824:                             }
 4825:                         }
 4826:                     }
 4827:                 }
 4828:             }
 4829:             if ($t->[4] =~ m{/>$}) {
 4830:                 pop(@state);
 4831:             }
 4832: 	} elsif ($t->[0] eq 'E') {
 4833: 	    my ($tagname) = ($t->[1]);
 4834: 	    if ($javafiles{'codebase'} ne '') {
 4835: 		$javafiles{'codebase'} .= '/';
 4836: 	    }  
 4837: 	    if (lc($tagname) eq 'applet' ||
 4838: 		lc($tagname) eq 'object' ||
 4839: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
 4840: 		) {
 4841: 		foreach my $item (keys(%javafiles)) {
 4842: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
 4843: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
 4844: 			&add_filetype($allfiles,$file,$item);
 4845: 		    }
 4846: 		}
 4847: 	    } 
 4848: 	    pop @state;
 4849: 	}
 4850:     }
 4851:     foreach my $id (sort(keys(%flashvars))) {
 4852:         if ($shockwave{$id} ne '') {
 4853:             my @pairs = split(/\&/,$flashvars{$id});
 4854:             foreach my $pair (@pairs) {
 4855:                 my ($key,$value) = split(/\=/,$pair);
 4856:                 if ($key eq 'thumb') {
 4857:                     &add_filetype($allfiles,$value,$key);
 4858:                 } elsif ($key eq 'content') {
 4859:                     my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
 4860:                     my ($ext) = ($value =~ /\.([^.]+)$/);
 4861:                     if ($ext ne '') {
 4862:                         &add_filetype($allfiles,$path.$value,$ext);
 4863:                     }
 4864:                 }
 4865:             }
 4866:         }
 4867:     }
 4868:     return 'ok';
 4869: }
 4870: 
 4871: sub add_filetype {
 4872:     my ($allfiles,$file,$type)=@_;
 4873:     if (exists($allfiles->{$file})) {
 4874: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
 4875: 	    push(@{$allfiles->{$file}}, &escape($type));
 4876: 	}
 4877:     } else {
 4878: 	@{$allfiles->{$file}} = (&escape($type));
 4879:     }
 4880: }
 4881: 
 4882: sub embedded_dependency {
 4883:     my ($allfiles,$related,$identifier,$pathfrom) = @_;
 4884:     if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
 4885:         if (($identifier ne '') &&
 4886:             (ref($related->{$identifier}) eq 'ARRAY') &&
 4887:             ($pathfrom ne '')) {
 4888:             my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
 4889:             foreach my $dep (@{$related->{$identifier}}) {
 4890:                 &add_filetype($allfiles,$path.$dep,'object');
 4891:             }
 4892:         }
 4893:     }
 4894:     return;
 4895: }
 4896: 
 4897: sub check_dimensions {
 4898:     my ($inputfile) = @_;
 4899:     my ($fullwidth,$fullheight);
 4900:     if (($inputfile =~ m|^[/\w.\-]+$|) && (-e $inputfile)) {
 4901:         my $mm = new File::MMagic;
 4902:         my $mime_type = $mm->checktype_filename($inputfile);
 4903:         if ($mime_type =~ m{^image/}) {
 4904:             if (open(PIPE,"identify $inputfile 2>&1 |")) {
 4905:                 my $imageinfo = <PIPE>;
 4906:                 if (!close(PIPE)) {
 4907:                     &Apache::lonnet::logthis("Failed to close PIPE opened to retrieve image information for $inputfile");
 4908:                 }
 4909:                 chomp($imageinfo);
 4910:                 my ($fullsize) =
 4911:                     ($imageinfo =~ /^\Q$inputfile\E\s+\w+\s+(\d+x\d+)/);
 4912:                 if ($fullsize) {
 4913:                     ($fullwidth,$fullheight) = split(/x/,$fullsize);
 4914:                 }
 4915:             }
 4916:         }
 4917:     }
 4918:     return ($fullwidth,$fullheight);
 4919: }
 4920: 
 4921: sub bubblesheet_converter {
 4922:     my ($cdom,$fullpath,$config,$format) = @_;
 4923:     if ((&domain($cdom) ne '') &&
 4924:         ($fullpath =~ m{^\Q$perlvar{'lonDocRoot'}/userfiles/$cdom/\E$match_courseid/scantron_orig}) &&
 4925:         (-e $fullpath) && (ref($config) eq 'HASH') && ($format ne '')) {
 4926:         my (%csvcols,%csvoptions);
 4927:         if (ref($config->{'fields'}) eq 'HASH') {  
 4928:             %csvcols = %{$config->{'fields'}};
 4929:         }
 4930:         if (ref($config->{'options'}) eq 'HASH') {
 4931:             %csvoptions = %{$config->{'options'}};
 4932:         }
 4933:         my %csvbynum = reverse(%csvcols);
 4934:         my %scantronconf = &get_scantron_config($format,$cdom);
 4935:         if (keys(%scantronconf)) {
 4936:             my %bynum = (
 4937:                           $scantronconf{CODEstart} => 'CODEstart',
 4938:                           $scantronconf{IDstart}   => 'IDstart',
 4939:                           $scantronconf{PaperID}   => 'PaperID',
 4940:                           $scantronconf{FirstName} => 'FirstName',
 4941:                           $scantronconf{LastName}  => 'LastName',
 4942:                           $scantronconf{Qstart}    => 'Qstart',
 4943:                         );
 4944:             my @ordered;
 4945:             foreach my $item (sort { $a <=> $b } keys(%bynum)) {
 4946:                 push(@ordered,$bynum{$item});
 4947:             }
 4948:             my %mapstart = (
 4949:                               CODEstart => 'CODE',
 4950:                               IDstart   => 'ID',
 4951:                               PaperID   => 'PaperID',
 4952:                               FirstName => 'FirstName',
 4953:                               LastName  => 'LastName',
 4954:                               Qstart    => 'FirstQuestion',
 4955:                            );
 4956:             my %maplength = (
 4957:                               CODEstart => 'CODElength',
 4958:                               IDstart   => 'IDlength',
 4959:                               PaperID   => 'PaperIDlength',
 4960:                               FirstName => 'FirstNamelength',
 4961:                               LastName  => 'LastNamelength',
 4962:             );
 4963:             if (open(my $fh,'<',$fullpath)) {
 4964:                 my $output;
 4965:                 my %lettdig = &letter_to_digits();
 4966:                 my %diglett = reverse(%lettdig);
 4967:                 my $numletts = scalar(keys(%lettdig));
 4968:                 my $num = 0;
 4969:                 while (my $line=<$fh>) {
 4970:                     $num ++;
 4971:                     next if (($num == 1) && ($csvoptions{'hdr'} == 1));
 4972:                     $line =~ s{[\r\n]+$}{};
 4973:                     my %found;
 4974:                     my @values = split(/,/,$line,-1);
 4975:                     my ($qstart,$record);
 4976:                     for (my $i=0; $i<@values; $i++) {
 4977:                         if ((($qstart ne '') && ($i > $qstart)) ||
 4978:                             ($csvbynum{$i} eq 'FirstQuestion')) {
 4979:                             if ($values[$i] eq '') {
 4980:                                 $values[$i] = $scantronconf{'Qoff'};
 4981:                             } elsif ($scantronconf{'Qon'} eq 'number') {
 4982:                                 if ($values[$i] =~ /^[A-Ja-j]$/) {
 4983:                                     $values[$i] = $lettdig{uc($values[$i])};
 4984:                                 }
 4985:                             } elsif ($scantronconf{'Qon'} eq 'letter') {
 4986:                                 if ($values[$i] =~ /^[0-9]$/) {
 4987:                                     $values[$i] = $diglett{$values[$i]};
 4988:                                 }
 4989:                             } else {
 4990:                                 if ($values[$i] =~ /^[0-9A-Ja-j]$/) {
 4991:                                     my $digit;
 4992:                                     if ($values[$i] =~ /^[A-Ja-j]$/) {
 4993:                                         $digit = $lettdig{uc($values[$i])}-1;
 4994:                                         if ($values[$i] eq 'J') {
 4995:                                             $digit += $numletts;
 4996:                                         }
 4997:                                     } elsif ($values[$i] =~ /^[0-9]$/) {
 4998:                                         $digit = $values[$i]-1;
 4999:                                         if ($values[$i] eq '0') {
 5000:                                             $digit += $numletts;
 5001:                                         }
 5002:                                     }
 5003:                                     my $qval='';
 5004:                                     for (my $j=0; $j<$scantronconf{'Qlength'}; $j++) {
 5005:                                         if ($j == $digit) {
 5006:                                             $qval .= $scantronconf{'Qon'};
 5007:                                         } else {
 5008:                                             $qval .= $scantronconf{'Qoff'};
 5009:                                         }
 5010:                                     }
 5011:                                     $values[$i] = $qval;
 5012:                                 }
 5013:                             }
 5014:                             if (length($values[$i]) > $scantronconf{'Qlength'}) {
 5015:                                 $values[$i] = substr($values[$i],0,$scantronconf{'Qlength'});
 5016:                             }
 5017:                             my $numblank = $scantronconf{'Qlength'} - length($values[$i]);
 5018:                             if ($numblank > 0) {
 5019:                                  $values[$i] .= ($scantronconf{'Qoff'} x $numblank);
 5020:                             }
 5021:                             if ($csvbynum{$i} eq 'FirstQuestion') {
 5022:                                 $qstart = $i;
 5023:                                 $found{$csvbynum{$i}} = $values[$i];
 5024:                             } else {
 5025:                                 $found{'FirstQuestion'} .= $values[$i];
 5026:                             }
 5027:                         } elsif (exists($csvbynum{$i})) {
 5028:                             if ($csvoptions{'rem'}) {
 5029:                                 $values[$i] =~ s/^\s+//;
 5030:                             }
 5031:                             if (($csvbynum{$i} eq 'PaperID') && ($csvoptions{'pad'})) {
 5032:                                 while (length($values[$i]) < $scantronconf{$maplength{$csvbynum{$i}}}) {
 5033:                                     $values[$i] = '0'.$values[$i];
 5034:                                 }
 5035:                             }
 5036:                             $found{$csvbynum{$i}} = $values[$i];
 5037:                         }
 5038:                     }
 5039:                     foreach my $item (@ordered) {
 5040:                         my $currlength = 1+length($record);
 5041:                         my $numspaces = $scantronconf{$item} - $currlength;
 5042:                         if ($numspaces > 0) {
 5043:                             $record .= (' ' x $numspaces);
 5044:                         }
 5045:                         if (($mapstart{$item} ne '') && (exists($found{$mapstart{$item}}))) {
 5046:                             unless ($item eq 'Qstart') {
 5047:                                 if (length($found{$mapstart{$item}}) > $scantronconf{$maplength{$item}}) {
 5048:                                     $found{$mapstart{$item}} = substr($found{$mapstart{$item}},0,$scantronconf{$maplength{$item}});
 5049:                                 }
 5050:                             }
 5051:                             $record .= $found{$mapstart{$item}};
 5052:                         }
 5053:                     }
 5054:                     $output .= "$record\n";
 5055:                 }
 5056:                 close($fh);
 5057:                 if ($output) {
 5058:                     if (open(my $fh,'>',$fullpath)) {
 5059:                         print $fh $output;
 5060:                         close($fh);
 5061:                     }
 5062:                 }
 5063:             }
 5064:         }
 5065:         return;
 5066:     }
 5067: }
 5068: 
 5069: sub letter_to_digits {
 5070:     my %lettdig = (
 5071:                     A => 1,
 5072:                     B => 2,
 5073:                     C => 3,
 5074:                     D => 4,
 5075:                     E => 5,
 5076:                     F => 6,
 5077:                     G => 7,
 5078:                     H => 8,
 5079:                     I => 9,
 5080:                     J => 0,
 5081:                   );
 5082:     return %lettdig;
 5083: }
 5084: 
 5085: sub get_scantron_config {
 5086:     my ($which,$cdom) = @_;
 5087:     my @lines = &get_scantronformat_file($cdom);
 5088:     my %config;
 5089:     #FIXME probably should move to XML it has already gotten a bit much now
 5090:     foreach my $line (@lines) {
 5091:         my ($name,$descrip)=split(/:/,$line);
 5092:         if ($name ne $which ) { next; }
 5093:         chomp($line);
 5094:         my @config=split(/:/,$line);
 5095:         $config{'name'}=$config[0];
 5096:         $config{'description'}=$config[1];
 5097:         $config{'CODElocation'}=$config[2];
 5098:         $config{'CODEstart'}=$config[3];
 5099:         $config{'CODElength'}=$config[4];
 5100:         $config{'IDstart'}=$config[5];
 5101:         $config{'IDlength'}=$config[6];
 5102:         $config{'Qstart'}=$config[7];
 5103:         $config{'Qlength'}=$config[8];
 5104:         $config{'Qoff'}=$config[9];
 5105:         $config{'Qon'}=$config[10];
 5106:         $config{'PaperID'}=$config[11];
 5107:         $config{'PaperIDlength'}=$config[12];
 5108:         $config{'FirstName'}=$config[13];
 5109:         $config{'FirstNamelength'}=$config[14];
 5110:         $config{'LastName'}=$config[15];
 5111:         $config{'LastNamelength'}=$config[16];
 5112:         $config{'BubblesPerRow'}=$config[17];
 5113:         last;
 5114:     }
 5115:     return %config;
 5116: }
 5117: 
 5118: sub get_scantronformat_file {
 5119:     my ($cdom) = @_;
 5120:     if ($cdom eq '') {
 5121:         $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
 5122:     }
 5123:     my %domconfig = &get_dom('configuration',['scantron'],$cdom);
 5124:     my $gottab = 0;
 5125:     my @lines;
 5126:     if (ref($domconfig{'scantron'}) eq 'HASH') {
 5127:         if ($domconfig{'scantron'}{'scantronformat'} ne '') {
 5128:             my $formatfile = &getfile($perlvar{'lonDocRoot'}.$domconfig{'scantron'}{'scantronformat'});
 5129:             if ($formatfile ne '-1') {
 5130:                 @lines = split("\n",$formatfile,-1);
 5131:                 $gottab = 1;
 5132:             }
 5133:         }
 5134:     }
 5135:     if (!$gottab) {
 5136:         my $confname = $cdom.'-domainconfig';
 5137:         my $default = $perlvar{'lonDocRoot'}.'/res/'.$cdom.'/'.$confname.'/default.tab';
 5138:         my $formatfile = &getfile($default);
 5139:         if ($formatfile ne '-1') {
 5140:             @lines = split("\n",$formatfile,-1);
 5141:             $gottab = 1;
 5142:         }
 5143:     }
 5144:     if (!$gottab) {
 5145:         my @domains = &current_machine_domains();
 5146:         if (grep(/^\Q$cdom\E$/,@domains)) {
 5147:             if (open(my $fh,'<',$perlvar{'lonTabDir'}.'/scantronformat.tab')) {
 5148:                 @lines = <$fh>;
 5149:                 close($fh);
 5150:             }
 5151:         } else {
 5152:             if (open(my $fh,'<',$perlvar{'lonTabDir'}.'/default_scantronformat.tab')) {
 5153:                 @lines = <$fh>;
 5154:                 close($fh);
 5155:             }
 5156:         }
 5157:         chomp(@lines);
 5158:     }
 5159:     return @lines;
 5160: }
 5161: 
 5162: sub removeuploadedurl {
 5163:     my ($url)=@_;	
 5164:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);    
 5165:     return &removeuserfile($uname,$udom,$fname);
 5166: }
 5167: 
 5168: sub removeuserfile {
 5169:     my ($docuname,$docudom,$fname)=@_;
 5170:     my $home=&homeserver($docuname,$docudom);    
 5171:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
 5172:     if ($result eq 'ok') {	
 5173:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
 5174:             my $metafile = $fname.'.meta';
 5175:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
 5176: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
 5177:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];	   
 5178:             my $sqlresult = 
 5179:                 &update_portfolio_table($docuname,$docudom,$file,
 5180:                                         'portfolio_metadata',$group,
 5181:                                         'delete');
 5182:         }
 5183:     }
 5184:     return $result;
 5185: }
 5186: 
 5187: sub mkdiruserfile {
 5188:     my ($docuname,$docudom,$dir)=@_;
 5189:     my $home=&homeserver($docuname,$docudom);
 5190:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
 5191: }
 5192: 
 5193: sub renameuserfile {
 5194:     my ($docuname,$docudom,$old,$new)=@_;
 5195:     my $home=&homeserver($docuname,$docudom);
 5196:     my $result = &reply("renameuserfile:$docudom:$docuname:".
 5197:                         &escape("$old").':'.&escape("$new"),$home);
 5198:     if ($result eq 'ok') {
 5199:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
 5200:             my $oldmeta = $old.'.meta';
 5201:             my $newmeta = $new.'.meta';
 5202:             my $metaresult = 
 5203:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
 5204: 	    my $url = "/uploaded/$docudom/$docuname/$old";
 5205:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
 5206:             my $sqlresult = 
 5207:                 &update_portfolio_table($docuname,$docudom,$file,
 5208:                                         'portfolio_metadata',$group,
 5209:                                         'delete');
 5210:         }
 5211:     }
 5212:     return $result;
 5213: }
 5214: 
 5215: # ------------------------------------------------------------------------- Log
 5216: 
 5217: sub log {
 5218:     my ($dom,$nam,$hom,$what)=@_;
 5219:     return critical("log:$dom:$nam:$what",$hom);
 5220: }
 5221: 
 5222: # ------------------------------------------------------------------ Course Log
 5223: #
 5224: # This routine flushes several buffers of non-mission-critical nature
 5225: #
 5226: 
 5227: sub flushcourselogs {
 5228:     &logthis('Flushing log buffers');
 5229: #
 5230: # course logs
 5231: # This is a log of all transactions in a course, which can be used
 5232: # for data mining purposes
 5233: #
 5234: # It also collects the courseid database, which lists last transaction
 5235: # times and course titles for all courseids
 5236: #
 5237:     my %courseidbuffer=();
 5238:     foreach my $crsid (keys(%courselogs)) {
 5239:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
 5240: 		          &escape($courselogs{$crsid}),
 5241: 		          $coursehombuf{$crsid}) eq 'ok') {
 5242: 	    delete $courselogs{$crsid};
 5243:         } else {
 5244:             &logthis('Failed to flush log buffer for '.$crsid);
 5245:             if (length($courselogs{$crsid})>40000) {
 5246:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
 5247:                         " exceeded maximum size, deleting.</font>");
 5248:                delete $courselogs{$crsid};
 5249:             }
 5250:         }
 5251:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
 5252:             'description' => $coursedescrbuf{$crsid},
 5253:             'inst_code'    => $courseinstcodebuf{$crsid},
 5254:             'type'        => $coursetypebuf{$crsid},
 5255:             'owner'       => $courseownerbuf{$crsid},
 5256:         };
 5257:     }
 5258: #
 5259: # Write course id database (reverse lookup) to homeserver of courses 
 5260: # Is used in pickcourse
 5261: #
 5262:     foreach my $crs_home (keys(%courseidbuffer)) {
 5263:         my $response = &courseidput(&host_domain($crs_home),
 5264:                                     $courseidbuffer{$crs_home},
 5265:                                     $crs_home,'timeonly');
 5266:     }
 5267: #
 5268: # File accesses
 5269: # Writes to the dynamic metadata of resources to get hit counts, etc.
 5270: #
 5271:     foreach my $entry (keys(%accesshash)) {
 5272:         if ($entry =~ /___count$/) {
 5273:             my ($dom,$name);
 5274:             ($dom,$name,undef)=
 5275: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
 5276:             if (! defined($dom) || $dom eq '' || 
 5277:                 ! defined($name) || $name eq '') {
 5278:                 my $cid = $env{'request.course.id'};
 5279: #
 5280: # FIXME 11/29/2021
 5281: # Typo in rev. 1.458 (2003/12/09)??
 5282: # These should likely by $env{'course.'.$cid.'.domain'} and $env{'course.'.$cid.'.num'}
 5283: #
 5284: # While these remain as $env{'request.'.$cid.'.domain'} and $env{'request.'.$cid.'.num'}
 5285: # $dom and $name will always be null, so the &inc() call will default to storing this data
 5286: # in a nohist_accesscount.db file for the user rather than the course.
 5287: #
 5288: # That said there is a lot of noise in the data being stored.
 5289: # So counts for prtspool/  and adm/ etc. are recorded.
 5290: #
 5291: # A review of which items ending '___count' are written to %accesshash should likely be 
 5292: # made before deciding whether to set these to 'course.' instead of 'request.'
 5293: #
 5294: # Under the current scheme each user receives a nohist_accesscount.db file listing 
 5295: # accesses for things which are not published resources, regardless of course, and
 5296: # there is not a nohist_accesscount.db file in a course, which might log accesses from
 5297: # anyone in the course for things which are not published resources.
 5298: #
 5299: # For an author, nohist_accesscount.db ends up having records for other items
 5300: # mixed up with the legitimate access counts for the author's published resources.
 5301: #
 5302:                 $dom  = $env{'request.'.$cid.'.domain'};
 5303:                 $name = $env{'request.'.$cid.'.num'};
 5304:             }
 5305:             my $value = $accesshash{$entry};
 5306:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
 5307:             my %temphash=($url => $value);
 5308:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
 5309:             if ($result eq 'ok') {
 5310:                 delete $accesshash{$entry};
 5311:             }
 5312:         } else {
 5313:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
 5314:             if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
 5315:             my %temphash=($entry => $accesshash{$entry});
 5316:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
 5317:                 delete $accesshash{$entry};
 5318:             }
 5319:         }
 5320:     }
 5321: #
 5322: # Roles
 5323: # Reverse lookup of user roles for course faculty/staff and co-authorship
 5324: #
 5325:     foreach my $entry (keys(%userrolehash)) {
 5326:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
 5327: 	    split(/\:/,$entry);
 5328:         if (&put('nohist_userroles',
 5329:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
 5330:                 $rudom,$runame) eq 'ok') {
 5331: 	    delete $userrolehash{$entry};
 5332:         }
 5333:     }
 5334: #
 5335: # Reverse lookup of domain roles (dc, ad, li, sc, dh, da, au)
 5336: #
 5337:     my %domrolebuffer = ();
 5338:     foreach my $entry (keys(%domainrolehash)) {
 5339:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
 5340:         if ($domrolebuffer{$rudom}) {
 5341:             $domrolebuffer{$rudom}.='&'.&escape($entry).
 5342:                       '='.&escape($domainrolehash{$entry});
 5343:         } else {
 5344:             $domrolebuffer{$rudom}.=&escape($entry).
 5345:                       '='.&escape($domainrolehash{$entry});
 5346:         }
 5347:         delete $domainrolehash{$entry};
 5348:     }
 5349:     foreach my $dom (keys(%domrolebuffer)) {
 5350: 	my %servers;
 5351: 	if (defined(&domain($dom,'primary'))) {
 5352: 	    my $primary=&domain($dom,'primary');
 5353: 	    my $hostname=&hostname($primary);
 5354: 	    $servers{$primary} = $hostname;
 5355: 	} else { 
 5356: 	    %servers = &get_servers($dom,'library');
 5357: 	}
 5358: 	foreach my $tryserver (keys(%servers)) {
 5359: 	    if (&reply('domroleput:'.$dom.':'.
 5360: 		       $domrolebuffer{$dom},$tryserver) eq 'ok') {
 5361: 		last;
 5362: 	    } else {  
 5363: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
 5364: 	    }
 5365:         }
 5366:     }
 5367:     $dumpcount++;
 5368: }
 5369: 
 5370: sub courselog {
 5371:     my $what=shift;
 5372:     $what=time.':'.$what;
 5373:     unless ($env{'request.course.id'}) { return ''; }
 5374:     $coursedombuf{$env{'request.course.id'}}=
 5375:        $env{'course.'.$env{'request.course.id'}.'.domain'};
 5376:     $coursenumbuf{$env{'request.course.id'}}=
 5377:        $env{'course.'.$env{'request.course.id'}.'.num'};
 5378:     $coursehombuf{$env{'request.course.id'}}=
 5379:        $env{'course.'.$env{'request.course.id'}.'.home'};
 5380:     $coursedescrbuf{$env{'request.course.id'}}=
 5381:        $env{'course.'.$env{'request.course.id'}.'.description'};
 5382:     $courseinstcodebuf{$env{'request.course.id'}}=
 5383:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
 5384:     $courseownerbuf{$env{'request.course.id'}}=
 5385:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
 5386:     $coursetypebuf{$env{'request.course.id'}}=
 5387:        $env{'course.'.$env{'request.course.id'}.'.type'};
 5388:     if (defined $courselogs{$env{'request.course.id'}}) {
 5389: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
 5390:     } else {
 5391: 	$courselogs{$env{'request.course.id'}}.=$what;
 5392:     }
 5393:     if (length($courselogs{$env{'request.course.id'}})>4048) {
 5394: 	&flushcourselogs();
 5395:     }
 5396: }
 5397: 
 5398: sub courseacclog {
 5399:     my $fnsymb=shift;
 5400:     unless ($env{'request.course.id'}) { return ''; }
 5401:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
 5402:     if ($fnsymb=~/$LONCAPA::assess_re/) {
 5403:         $what.=':POST';
 5404:         # FIXME: Probably ought to escape things....
 5405: 	foreach my $key (keys(%env)) {
 5406:             if ($key=~/^form\.(.*)/) {
 5407:                 my $formitem = $1;
 5408:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
 5409:                     $what.=':'.$formitem.'='.$env{$key};
 5410:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
 5411:                     if ($formitem eq 'proctorpassword') {
 5412:                         $what.=':'.$formitem.'=' . '*' x length($env{$key});
 5413:                     } else {
 5414:                         $what.=':'.$formitem.'='.$env{$key};
 5415:                     }
 5416:                 }
 5417:             }
 5418:         }
 5419:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
 5420:         # FIXME: We should not be depending on a form parameter that someone
 5421:         # editing lonsearchcat.pm might change in the future.
 5422:         if ($env{'form.phase'} eq 'course_search') {
 5423:             $what.= ':POST';
 5424:             # FIXME: Probably ought to escape things....
 5425:             foreach my $element ('courseexp','crsfulltext','crsrelated',
 5426:                                  'crsdiscuss') {
 5427:                 $what.=':'.$element.'='.$env{'form.'.$element};
 5428:             }
 5429:         }
 5430:     }
 5431:     &courselog($what);
 5432: }
 5433: 
 5434: sub countacc {
 5435:     my $url=&declutter(shift);
 5436:     return if (! defined($url) || $url eq '');
 5437:     unless ($env{'request.course.id'}) { return ''; }
 5438: #
 5439: # Mark that this url was used in this course
 5440: #
 5441:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
 5442: #
 5443: # Increase the access count for this resource in this child process
 5444: #
 5445:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
 5446:     $accesshash{$key}++;
 5447: }
 5448: 
 5449: sub linklog {
 5450:     my ($from,$to)=@_;
 5451:     $from=&declutter($from);
 5452:     $to=&declutter($to);
 5453:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
 5454:     $accesshash{$to.'___'.$from.'___goto'}=1;
 5455: }
 5456: 
 5457: sub statslog {
 5458:     my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
 5459:     if ($users<2) { return; }
 5460:     my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
 5461:             'course'       => $env{'request.course.id'},
 5462:             'sections'     => '"all"',
 5463:             'num_students' => $users,
 5464:             'part'         => $part,
 5465:             'symb'         => $symb,
 5466:             'mean_tries'   => $av_attempts,
 5467:             'deg_of_diff'  => $degdiff});
 5468:     foreach my $key (keys(%dynstore)) {
 5469:         $accesshash{$key}=$dynstore{$key};
 5470:     }
 5471: }
 5472:   
 5473: sub userrolelog {
 5474:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
 5475:     if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
 5476:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 5477:        $userrolehash
 5478:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 5479:                     =$tend.':'.$tstart;
 5480:     }
 5481:     if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
 5482:        $userrolehash
 5483:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
 5484:                     =$tend.':'.$tstart;
 5485:     }
 5486:     if ($trole =~ /^(dc|ad|li|au|dg|sc|dh|da)/ ) {
 5487:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 5488:        $domainrolehash
 5489:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 5490:                     = $tend.':'.$tstart;
 5491:     }
 5492: }
 5493: 
 5494: sub courserolelog {
 5495:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,
 5496:         $context,$othdomby,$requester)=@_;
 5497:     if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
 5498:         my $cdom = $1;
 5499:         my $cnum = $2;
 5500:         my $sec = $3;
 5501:         my $namespace = 'rolelog';
 5502:         my %storehash = (
 5503:                            role    => $trole,
 5504:                            start   => $tstart,
 5505:                            end     => $tend,
 5506:                            selfenroll => $selfenroll,
 5507:                            context    => $context,
 5508:                         );
 5509:         if ($othdomby) {
 5510:             if ($othdomby eq 'othdombydc') {
 5511:                 $storehash{'approval'} = 'domain';
 5512:             } elsif ($othdomby eq 'othdombyuser') {
 5513:                 $storehash{'approval'} = 'user'; 
 5514:             }
 5515:             if ($requester ne '') {
 5516:                 $storehash{'requester'} = $requester;
 5517:             }
 5518:         }
 5519:         if ($trole eq 'gr') {
 5520:             $namespace = 'groupslog';
 5521:             $storehash{'group'} = $sec;
 5522:         } else {
 5523:             $storehash{'section'} = $sec;
 5524:             my ($curruserdomstr,$newuserdomstr);
 5525:             if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.userdomains'})) {
 5526:                 $curruserdomstr = $env{'course.'.$env{'request.course.id'}.'.internal.userdomains'};
 5527:             } else {
 5528:                 my %courseinfo = &coursedescription($cdom.'/'.$cnum);
 5529:                 $curruserdomstr = $courseinfo{'internal.userdomains'};
 5530:             }
 5531:             if ($curruserdomstr ne '') {
 5532:                 my @udoms = split(/,/,$curruserdomstr);
 5533:                 unless (grep(/^\Q$domain\E/,@udoms)) {
 5534:                     push(@udoms,$domain);
 5535:                     $newuserdomstr = join(',',sort(@udoms));
 5536:                 }
 5537:             } else {
 5538:                 $newuserdomstr = $domain;
 5539:             }
 5540:             if ($newuserdomstr ne '') {
 5541:                 my $putresult = &put('environment',{ 'internal.userdomains' => $newuserdomstr },
 5542:                                      $cdom,$cnum);
 5543:                 if ($putresult eq 'ok') {
 5544:                     unless (($selfenroll) || ($context eq 'selfenroll')) { 
 5545:                         if (($context eq 'createcourse') || ($context eq 'requestcourses') ||
 5546:                             ($context eq 'automated') || ($context eq 'domain')) {
 5547:                             $env{'course.'.$cdom.'_'.$cnum.'.internal.userdomains'} = $newuserdomstr;
 5548:                         } elsif ($env{'request.course.id'} eq $cdom.'_'.$cnum) {
 5549:                             &appenv({'course.'.$cdom.'_'.$cnum.'.internal.userdomains' => $newuserdomstr});
 5550:                         }
 5551:                     }
 5552:                 }
 5553:             }
 5554:         }
 5555:         &write_log('course',$namespace,\%storehash,$delflag,$username,
 5556:                    $domain,$cnum,$cdom);
 5557:         if (($trole ne 'st') || ($sec ne '')) {
 5558:             &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
 5559:         }
 5560:     }
 5561:     return;
 5562: }
 5563: 
 5564: sub domainrolelog {
 5565:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,
 5566:         $context,$othdomby,$requester)=@_;
 5567:     if ($area =~ m{^/($match_domain)/$}) {
 5568:         my $cdom = $1;
 5569:         my $domconfiguser = &get_domainconfiguser($cdom);
 5570:         my $namespace = 'rolelog';
 5571:         my %storehash = (
 5572:                            role    => $trole,
 5573:                            start   => $tstart,
 5574:                            end     => $tend,
 5575:                            context => $context,
 5576:                         );
 5577:         if ($othdomby) {
 5578:             if ($othdomby eq 'othdombydc') {
 5579:                 $storehash{'approval'} = 'domain';
 5580:             } elsif ($othdomby eq 'othdombyuser') {
 5581:                 $storehash{'approval'} = 'user';
 5582:             }
 5583:             if ($requester ne '') {
 5584:                 $storehash{'requester'} = $requester;
 5585:             }
 5586:         }
 5587:         &write_log('domain',$namespace,\%storehash,$delflag,$username,
 5588:                    $domain,$domconfiguser,$cdom);
 5589:     }
 5590:     return;
 5591: 
 5592: }
 5593: 
 5594: sub coauthorrolelog {
 5595:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,
 5596:         $context,$othdomby,$requester)=@_;
 5597:     if ($area =~ m{^/($match_domain)/($match_username)$}) {
 5598:         my $audom = $1;
 5599:         my $auname = $2;
 5600:         my $namespace = 'rolelog';
 5601:         my %storehash = (
 5602:                            role    => $trole,
 5603:                            start   => $tstart,
 5604:                            end     => $tend,
 5605:                            context => $context,
 5606:                         );
 5607:         if ($othdomby) {
 5608:             if ($othdomby eq 'othdombydc') {
 5609:                 $storehash{'approval'} = 'domain';
 5610:             } elsif ($othdomby eq 'othdombyuser') {
 5611:                 $storehash{'approval'} = 'user';
 5612:             }
 5613:             if ($requester ne '') {
 5614:                 $storehash{'requester'} = $requester;
 5615:             }
 5616:         }
 5617:         &write_log('author',$namespace,\%storehash,$delflag,$username,
 5618:                    $domain,$auname,$audom);
 5619:     }
 5620:     return;
 5621: }
 5622: 
 5623: sub get_course_adv_roles {
 5624:     my ($cid,$codes) = @_;
 5625:     $cid=$env{'request.course.id'} unless (defined($cid));
 5626:     my %coursehash=&coursedescription($cid);
 5627:     my $crstype = &Apache::loncommon::course_type($cid);
 5628:     my %nothide=();
 5629:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 5630:         if ($user !~ /:/) {
 5631: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
 5632:         } else {
 5633:             $nothide{$user}=1;
 5634:         }
 5635:     }
 5636:     my @possdoms = ($coursehash{'domain'});
 5637:     if ($coursehash{'checkforpriv'}) {
 5638:         push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
 5639:     }
 5640:     my %returnhash=();
 5641:     my %dumphash=
 5642:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
 5643:     my $now=time;
 5644:     my %privileged;
 5645:     foreach my $entry (keys(%dumphash)) {
 5646: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
 5647:         if (($tstart) && ($tstart<0)) { next; }
 5648:         if (($tend) && ($tend<$now)) { next; }
 5649:         if (($tstart) && ($now<$tstart)) { next; }
 5650:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
 5651: 	if ($username eq '' || $domain eq '') { next; }
 5652:         if ((&privileged($username,$domain,\@possdoms)) &&
 5653:             (!$nothide{$username.':'.$domain})) { next; }
 5654: 	if ($role eq 'cr') { next; }
 5655:         if ($codes) {
 5656:             if ($section) { $role .= ':'.$section; }
 5657:             if ($returnhash{$role}) {
 5658:                 $returnhash{$role}.=','.$username.':'.$domain;
 5659:             } else {
 5660:                 $returnhash{$role}=$username.':'.$domain;
 5661:             }
 5662:         } else {
 5663:             my $key=&plaintext($role,$crstype);
 5664:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
 5665:             if ($returnhash{$key}) {
 5666: 	        $returnhash{$key}.=','.$username.':'.$domain;
 5667:             } else {
 5668:                 $returnhash{$key}=$username.':'.$domain;
 5669:             }
 5670:         }
 5671:     }
 5672:     return %returnhash;
 5673: }
 5674: 
 5675: sub get_my_roles {
 5676:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
 5677:     unless (defined($uname)) { $uname=$env{'user.name'}; }
 5678:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
 5679:     my (%dumphash,%nothide);
 5680:     if ($context eq 'userroles') {
 5681:         %dumphash = &dump('roles',$udom,$uname);
 5682:     } else {
 5683:         %dumphash = &dump('nohist_userroles',$udom,$uname);
 5684:         if ($hidepriv) {
 5685:             my %coursehash=&coursedescription($udom.'_'.$uname);
 5686:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 5687:                 if ($user !~ /:/) {
 5688:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
 5689:                 } else {
 5690:                     $nothide{$user} = 1;
 5691:                 }
 5692:             }
 5693:         }
 5694:     }
 5695:     my %returnhash=();
 5696:     my $now=time;
 5697:     my %privileged;
 5698:     foreach my $entry (keys(%dumphash)) {
 5699:         my ($role,$tend,$tstart);
 5700:         if ($context eq 'userroles') {
 5701:             next if ($entry =~ /^rolesdef/);
 5702: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
 5703:         } else {
 5704:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
 5705:         }
 5706:         if (($tstart) && ($tstart<0)) { next; }
 5707:         my $status = 'active';
 5708:         if (($tend) && ($tend<=$now)) {
 5709:             $status = 'previous';
 5710:         } 
 5711:         if (($tstart) && ($now<$tstart)) {
 5712:             $status = 'future';
 5713:         }
 5714:         if (ref($types) eq 'ARRAY') {
 5715:             if (!grep(/^\Q$status\E$/,@{$types})) {
 5716:                 next;
 5717:             } 
 5718:         } else {
 5719:             if ($status ne 'active') {
 5720:                 next;
 5721:             }
 5722:         }
 5723:         my ($rolecode,$username,$domain,$section,$area);
 5724:         if ($context eq 'userroles') {
 5725:             ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
 5726:             (undef,$domain,$username,$section) = split(/\//,$area);
 5727:         } else {
 5728:             ($role,$username,$domain,$section) = split(/\:/,$entry);
 5729:         }
 5730:         if (ref($roledoms) eq 'ARRAY') {
 5731:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
 5732:                 next;
 5733:             }
 5734:         }
 5735:         if (ref($roles) eq 'ARRAY') {
 5736:             if (!grep(/^\Q$role\E$/,@{$roles})) {
 5737:                 if ($role =~ /^cr\//) {
 5738:                     if (!grep(/^cr$/,@{$roles})) {
 5739:                         next;
 5740:                     }
 5741:                 } elsif ($role =~ /^gr\//) {
 5742:                     if (!grep(/^gr$/,@{$roles})) {
 5743:                         next;
 5744:                     }
 5745:                 } else {
 5746:                     next;
 5747:                 }
 5748:             }
 5749:         }
 5750:         if ($hidepriv) {
 5751:             my @privroles = ('dc','su');
 5752:             if ($context eq 'userroles') {
 5753:                 next if (grep(/^\Q$role\E$/,@privroles));
 5754:             } else {
 5755:                 my $possdoms = [$domain];
 5756:                 if (ref($roledoms) eq 'ARRAY') {
 5757:                    push(@{$possdoms},@{$roledoms}); 
 5758:                 }
 5759:                 if (&privileged($username,$domain,$possdoms,\@privroles)) {
 5760:                     if (!$nothide{$username.':'.$domain}) {
 5761:                         next;
 5762:                     }
 5763:                 }
 5764:             }
 5765:         }
 5766:         if ($withsec) {
 5767:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
 5768:                 $tstart.':'.$tend;
 5769:         } else {
 5770:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
 5771:         }
 5772:     }
 5773:     return %returnhash;
 5774: }
 5775: 
 5776: sub get_all_adhocroles {
 5777:     my ($dom) = @_;
 5778:     my @roles_by_num = ();
 5779:     my %domdefaults = &get_domain_defaults($dom);
 5780:     my (%description,%access_in_dom,%access_info);
 5781:     if (ref($domdefaults{'adhocroles'}) eq 'HASH') {
 5782:         my $count = 0;
 5783:         my %domcurrent = %{$domdefaults{'adhocroles'}};
 5784:         my %ordered;
 5785:         foreach my $role (sort(keys(%domcurrent))) {
 5786:             my ($order,$desc,$access_in_dom);
 5787:             if (ref($domcurrent{$role}) eq 'HASH') {
 5788:                 $order = $domcurrent{$role}{'order'};
 5789:                 $desc = $domcurrent{$role}{'desc'};
 5790:                 $access_in_dom{$role} = $domcurrent{$role}{'access'};
 5791:                 $access_info{$role} = $domcurrent{$role}{$access_in_dom{$role}};
 5792:             }
 5793:             if ($order eq '') {
 5794:                 $order = $count;
 5795:             }
 5796:             $ordered{$order} = $role;
 5797:             if ($desc ne '') {
 5798:                 $description{$role} = $desc;
 5799:             } else {
 5800:                 $description{$role}= $role;
 5801:             }
 5802:             $count++;
 5803:         }
 5804:         foreach my $item (sort {$a <=> $b } (keys(%ordered))) {
 5805:             push(@roles_by_num,$ordered{$item});
 5806:         }
 5807:     }
 5808:     return (\@roles_by_num,\%description,\%access_in_dom,\%access_info);
 5809: }
 5810: 
 5811: sub get_my_adhocroles {
 5812:     my ($cid,$checkreg) = @_;
 5813:     my ($cdom,$cnum,%info,@possroles,$description,$roles_by_num);
 5814:     if ($env{'request.course.id'} eq $cid) {
 5815:         $cdom = $env{'course.'.$cid.'.domain'};
 5816:         $cnum = $env{'course.'.$cid.'.num'};
 5817:         $info{'internal.coursecode'} = $env{'course.'.$cid.'.internal.coursecode'};
 5818:     } elsif ($cid =~ /^($match_domain)_($match_courseid)$/) {
 5819:         $cdom = $1;
 5820:         $cnum = $2;
 5821:         %info = &get('environment',['internal.coursecode'],
 5822:                      $cdom,$cnum);
 5823:     }
 5824:     if (($info{'internal.coursecode'} ne '') && ($checkreg)) {
 5825:         my $user = $env{'user.name'}.':'.$env{'user.domain'};
 5826:         my %rosterhash = &get('classlist',[$user],$cdom,$cnum);
 5827:         if ($rosterhash{$user} ne '') {
 5828:             my $type = (split(/:/,$rosterhash{$user}))[5];
 5829:             return ([],{}) if ($type eq 'auto');
 5830:         }
 5831:     }
 5832:     if (($cdom ne '') && ($cnum ne ''))  {
 5833:         if (($env{"user.role.dh./$cdom/"}) || ($env{"user.role.da./$cdom/"})) {
 5834:             my $then=$env{'user.login.time'};
 5835:             my $update=$env{'user.update.time'};
 5836:             if (!$update) {
 5837:                 $update = $then;
 5838:             }
 5839:             my @liveroles;
 5840:             foreach my $role ('dh','da') {
 5841:                 if ($env{"user.role.$role./$cdom/"}) {
 5842:                     my ($tstart,$tend)=split(/\./,$env{"user.role.$role./$cdom/"});
 5843:                     my $limit = $update;
 5844:                     if ($env{'request.role'} eq "$role./$cdom/") {
 5845:                         $limit = $then;
 5846:                     }
 5847:                     my $activerole = 1;
 5848:                     if ($tstart && $tstart>$limit) { $activerole = 0; }
 5849:                     if ($tend   && $tend  <$limit) { $activerole = 0; }
 5850:                     if ($activerole) {
 5851:                         push(@liveroles,$role);
 5852:                     }
 5853:                 }
 5854:             }
 5855:             if (@liveroles) {
 5856:                 if (&homeserver($cnum,$cdom) ne 'no_host') {
 5857:                     my ($accessref,$accessinfo,%access_in_dom);
 5858:                     ($roles_by_num,$description,$accessref,$accessinfo) = &get_all_adhocroles($cdom);
 5859:                     if (ref($roles_by_num) eq 'ARRAY') {
 5860:                         if (@{$roles_by_num}) {
 5861:                             my %settings;
 5862:                             if ($env{'request.course.id'} eq $cid) {
 5863:                                 foreach my $envkey (keys(%env)) {
 5864:                                     if ($envkey =~ /^\Qcourse.$cid.\E(internal\.adhoc.+)$/) {
 5865:                                         $settings{$1} = $env{$envkey};
 5866:                                     }
 5867:                                 }
 5868:                             } else {
 5869:                                 %settings = &dump('environment',$cdom,$cnum,'internal\.adhoc');
 5870:                             }
 5871:                             my %setincrs;
 5872:                             if ($settings{'internal.adhocaccess'}) {
 5873:                                 map { $setincrs{$_} = 1; } split(/,/,$settings{'internal.adhocaccess'});
 5874:                             }
 5875:                             my @statuses;
 5876:                             if ($env{'environment.inststatus'}) {
 5877:                                 @statuses = split(/,/,$env{'environment.inststatus'});
 5878:                             }
 5879:                             my $user = $env{'user.name'}.':'.$env{'user.domain'};
 5880:                             if (ref($accessref) eq 'HASH') {
 5881:                                 %access_in_dom = %{$accessref};
 5882:                             }
 5883:                             foreach my $role (@{$roles_by_num}) {
 5884:                                 my ($curraccess,@okstatus,@personnel);
 5885:                                 if ($setincrs{$role}) {
 5886:                                     ($curraccess,my $rest) = split(/=/,$settings{'internal.adhoc.'.$role});
 5887:                                     if ($curraccess eq 'status') {
 5888:                                         @okstatus = split(/\&/,$rest);
 5889:                                     } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
 5890:                                         @personnel = split(/\&/,$rest);
 5891:                                     }
 5892:                                 } else {
 5893:                                     $curraccess = $access_in_dom{$role};
 5894:                                     if (ref($accessinfo) eq 'HASH') {
 5895:                                         if ($curraccess eq 'status') {
 5896:                                             if (ref($accessinfo->{$role}) eq 'ARRAY') {
 5897:                                                 @okstatus = @{$accessinfo->{$role}};
 5898:                                             }
 5899:                                         } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
 5900:                                             if (ref($accessinfo->{$role}) eq 'ARRAY') {
 5901:                                                 @personnel = @{$accessinfo->{$role}};
 5902:                                             }
 5903:                                         }
 5904:                                     }
 5905:                                 }
 5906:                                 if ($curraccess eq 'none') {
 5907:                                     next;
 5908:                                 } elsif ($curraccess eq 'all') {
 5909:                                     push(@possroles,$role);
 5910:                                 } elsif ($curraccess eq 'dh') {
 5911:                                     if (grep(/^dh$/,@liveroles)) {
 5912:                                         push(@possroles,$role);
 5913:                                     } else {
 5914:                                         next;
 5915:                                     }
 5916:                                 } elsif ($curraccess eq 'da') {
 5917:                                     if (grep(/^da$/,@liveroles)) {
 5918:                                         push(@possroles,$role);
 5919:                                     } else {
 5920:                                         next;
 5921:                                     }
 5922:                                 } elsif ($curraccess eq 'status') {
 5923:                                     if (@okstatus) {
 5924:                                         if (!@statuses) {
 5925:                                             if (grep(/^default$/,@okstatus)) {
 5926:                                                 push(@possroles,$role);
 5927:                                             }
 5928:                                         } else {
 5929:                                             foreach my $status (@okstatus) {
 5930:                                                 if (grep(/^\Q$status\E$/,@statuses)) {
 5931:                                                     push(@possroles,$role);
 5932:                                                     last;
 5933:                                                 }
 5934:                                             }
 5935:                                         }
 5936:                                     }
 5937:                                 } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
 5938:                                     if (grep(/^\Q$user\E$/,@personnel)) {
 5939:                                         if ($curraccess eq 'exc') {
 5940:                                             push(@possroles,$role);
 5941:                                         }
 5942:                                     } elsif ($curraccess eq 'inc') {
 5943:                                         push(@possroles,$role);
 5944:                                     }
 5945:                                 }
 5946:                             }
 5947:                         }
 5948:                     }
 5949:                 }
 5950:             }
 5951:         }
 5952:     }
 5953:     unless (ref($description) eq 'HASH') {
 5954:         if (ref($roles_by_num) eq 'ARRAY') {
 5955:             my %desc;
 5956:             map { $desc{$_} = $_; } (@{$roles_by_num});
 5957:             $description = \%desc;
 5958:         } else {
 5959:             $description = {};
 5960:         }
 5961:     }
 5962:     return (\@possroles,$description);
 5963: }
 5964: 
 5965: # ----------------------------------------------------- Frontpage Announcements
 5966: #
 5967: #
 5968: 
 5969: sub postannounce {
 5970:     my ($server,$text)=@_;
 5971:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
 5972:     unless ($text=~/\w/) { $text=''; }
 5973:     return &reply('setannounce:'.&escape($text),$server);
 5974: }
 5975: 
 5976: sub getannounce {
 5977: 
 5978:     if (open(my $fh,"<",$perlvar{'lonDocRoot'}.'/announcement.txt')) {
 5979: 	my $announcement='';
 5980: 	while (my $line = <$fh>) { $announcement .= $line; }
 5981: 	close($fh);
 5982: 	if ($announcement=~/\w/) { 
 5983: 	    return 
 5984:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
 5985:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
 5986: 	} else {
 5987: 	    return '';
 5988: 	}
 5989:     } else {
 5990: 	return '';
 5991:     }
 5992: }
 5993: 
 5994: # ---------------------------------------------------------- Course ID routines
 5995: # Deal with domain's nohist_courseid.db files
 5996: #
 5997: 
 5998: sub courseidput {
 5999:     my ($domain,$storehash,$coursehome,$caller) = @_;
 6000:     return unless (ref($storehash) eq 'HASH');
 6001:     my $outcome;
 6002:     if ($caller eq 'timeonly') {
 6003:         my $cids = '';
 6004:         foreach my $item (keys(%$storehash)) {
 6005:             $cids.=&escape($item).'&';
 6006:         }
 6007:         $cids=~s/\&$//;
 6008:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
 6009:                           $coursehome);       
 6010:     } else {
 6011:         my $items = '';
 6012:         foreach my $item (keys(%$storehash)) {
 6013:             $items.= &escape($item).'='.
 6014:                      &freeze_escape($$storehash{$item}).'&';
 6015:         }
 6016:         $items=~s/\&$//;
 6017:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
 6018:                           $coursehome);
 6019:     }
 6020:     if ($outcome eq 'unknown_cmd') {
 6021:         my $what;
 6022:         foreach my $cid (keys(%$storehash)) {
 6023:             $what .= &escape($cid).'=';
 6024:             foreach my $item ('description','inst_code','owner','type') {
 6025:                 $what .= &escape($storehash->{$cid}{$item}).':';
 6026:             }
 6027:             $what =~ s/\:$/&/;
 6028:         }
 6029:         $what =~ s/\&$//;  
 6030:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
 6031:     } else {
 6032:         return $outcome;
 6033:     }
 6034: }
 6035: 
 6036: sub courseiddump {
 6037:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
 6038:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
 6039:         $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
 6040:         $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner,
 6041:         $hasuniquecode,$reqcrsdom,$reqinstcode)=@_;
 6042:     my $as_hash = 1;
 6043:     my %returnhash;
 6044:     if (!$domfilter) { $domfilter=''; }
 6045:     my %libserv = &all_library();
 6046:     foreach my $tryserver (keys(%libserv)) {
 6047:         if ( (  $hostidflag == 1 
 6048: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
 6049: 	     || (!defined($hostidflag)) ) {
 6050: 
 6051: 	    if (($domfilter eq '') ||
 6052: 		(&host_domain($tryserver) eq $domfilter)) {
 6053:                 my $rep;
 6054:                 if (grep { $_ eq $tryserver } current_machine_ids()) {
 6055:                     $rep = LONCAPA::Lond::dump_course_id_handler(
 6056:                         join(":", (&host_domain($tryserver), $sincefilter, 
 6057:                                 &escape($descfilter), &escape($instcodefilter), 
 6058:                                 &escape($ownerfilter), &escape($coursefilter),
 6059:                                 &escape($typefilter), &escape($regexp_ok), 
 6060:                                 $as_hash, &escape($selfenrollonly), 
 6061:                                 &escape($catfilter), $showhidden, $caller, 
 6062:                                 &escape($cloner), &escape($cc_clone), $cloneonly, 
 6063:                                 &escape($createdbefore), &escape($createdafter), 
 6064:                                 &escape($creationcontext),$domcloner,$hasuniquecode,
 6065:                                 $reqcrsdom,&escape($reqinstcode))));
 6066:                 } else {
 6067:                     $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
 6068:                              $sincefilter.':'.&escape($descfilter).':'.
 6069:                              &escape($instcodefilter).':'.&escape($ownerfilter).
 6070:                              ':'.&escape($coursefilter).':'.&escape($typefilter).
 6071:                              ':'.&escape($regexp_ok).':'.$as_hash.':'.
 6072:                              &escape($selfenrollonly).':'.&escape($catfilter).':'.
 6073:                              $showhidden.':'.$caller.':'.&escape($cloner).':'.
 6074:                              &escape($cc_clone).':'.$cloneonly.':'.
 6075:                              &escape($createdbefore).':'.&escape($createdafter).':'.
 6076:                              &escape($creationcontext).':'.$domcloner.':'.$hasuniquecode.
 6077:                              ':'.$reqcrsdom.':'.&escape($reqinstcode),$tryserver);
 6078:                 }
 6079:                      
 6080:                 my @pairs=split(/\&/,$rep);
 6081:                 foreach my $item (@pairs) {
 6082:                     my ($key,$value)=split(/\=/,$item,2);
 6083:                     $key = &unescape($key);
 6084:                     next if ($key =~ /^error: 2 /);
 6085:                     my $result = &thaw_unescape($value);
 6086:                     if (ref($result) eq 'HASH') {
 6087:                         $returnhash{$key}=$result;
 6088:                     } else {
 6089:                         my @responses = split(/:/,$value);
 6090:                         my @items = ('description','inst_code','owner','type');
 6091:                         for (my $i=0; $i<@responses; $i++) {
 6092:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
 6093:                         }
 6094:                     }
 6095:                 }
 6096:             }
 6097:         }
 6098:     }
 6099:     return %returnhash;
 6100: }
 6101: 
 6102: sub courselastaccess {
 6103:     my ($cdom,$cnum,$hostidref) = @_;
 6104:     my %returnhash;
 6105:     if ($cdom && $cnum) {
 6106:         my $chome = &homeserver($cnum,$cdom);
 6107:         if ($chome ne 'no_host') {
 6108:             my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
 6109:             &extract_lastaccess(\%returnhash,$rep);
 6110:         }
 6111:     } else {
 6112:         if (!$cdom) { $cdom=''; }
 6113:         my %libserv = &all_library();
 6114:         foreach my $tryserver (keys(%libserv)) {
 6115:             if (ref($hostidref) eq 'ARRAY') {
 6116:                 next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
 6117:             } 
 6118:             if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
 6119:                 my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
 6120:                 &extract_lastaccess(\%returnhash,$rep);
 6121:             }
 6122:         }
 6123:     }
 6124:     return %returnhash;
 6125: }
 6126: 
 6127: sub extract_lastaccess {
 6128:     my ($returnhash,$rep) = @_;
 6129:     if (ref($returnhash) eq 'HASH') {
 6130:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' || 
 6131:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
 6132:                  $rep eq '') {
 6133:             my @pairs=split(/\&/,$rep);
 6134:             foreach my $item (@pairs) {
 6135:                 my ($key,$value)=split(/\=/,$item,2);
 6136:                 $key = &unescape($key);
 6137:                 next if ($key =~ /^error: 2 /);
 6138:                 $returnhash->{$key} = &thaw_unescape($value);
 6139:             }
 6140:         }
 6141:     }
 6142:     return;
 6143: }
 6144: 
 6145: # ---------------------------------------------------------- DC e-mail
 6146: 
 6147: sub dcmailput {
 6148:     my ($domain,$msgid,$message,$server)=@_;
 6149:     my $status = &critical(
 6150:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
 6151:        &escape($message),$server);
 6152:     return $status;
 6153: }
 6154: 
 6155: sub dcmaildump {
 6156:     my ($dom,$startdate,$enddate,$senders) = @_;
 6157:     my %returnhash=();
 6158: 
 6159:     if (defined(&domain($dom,'primary'))) {
 6160:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
 6161:                                                          &escape($enddate).':';
 6162: 	my @esc_senders=map { &escape($_)} @$senders;
 6163: 	$cmd.=&escape(join('&',@esc_senders));
 6164: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
 6165:             my ($key,$value) = split(/\=/,$line,2);
 6166:             if (($key) && ($value)) {
 6167:                 $returnhash{&unescape($key)} = &unescape($value);
 6168:             }
 6169:         }
 6170:     }
 6171:     return %returnhash;
 6172: }
 6173: # ---------------------------------------------------------- Domain roles
 6174: 
 6175: sub get_domain_roles {
 6176:     my ($dom,$roles,$startdate,$enddate)=@_;
 6177:     if ((!defined($startdate)) || ($startdate eq '')) {
 6178:         $startdate = '.';
 6179:     }
 6180:     if ((!defined($enddate)) || ($enddate eq '')) {
 6181:         $enddate = '.';
 6182:     }
 6183:     my $rolelist;
 6184:     if (ref($roles) eq 'ARRAY') {
 6185:         $rolelist = join('&',@{$roles});
 6186:     }
 6187:     my %personnel = ();
 6188: 
 6189:     my %servers = &get_servers($dom,'library');
 6190:     foreach my $tryserver (keys(%servers)) {
 6191: 	%{$personnel{$tryserver}}=();
 6192: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
 6193: 					    &escape($startdate).':'.
 6194: 					    &escape($enddate).':'.
 6195: 					    &escape($rolelist), $tryserver))) {
 6196: 	    my ($key,$value) = split(/\=/,$line,2);
 6197: 	    if (($key) && ($value)) {
 6198: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
 6199: 	    }
 6200: 	}
 6201:     }
 6202:     return %personnel;
 6203: }
 6204: 
 6205: sub get_active_domroles {
 6206:     my ($dom,$roles) = @_;
 6207:     return () unless (ref($roles) eq 'ARRAY');
 6208:     my $now = time;
 6209:     my %dompersonnel = &get_domain_roles($dom,$roles,$now,$now);
 6210:     my %domroles;
 6211:     foreach my $server (keys(%dompersonnel)) {
 6212:         foreach my $user (sort(keys(%{$dompersonnel{$server}}))) {
 6213:             my ($trole,$uname,$udom,$runame,$rudom,$rsec) = split(/:/,$user);
 6214:             $domroles{$uname.':'.$udom} = $dompersonnel{$server}{$user};
 6215:         }
 6216:     }
 6217:     return %domroles;
 6218: }
 6219: 
 6220: # ----------------------------------------------------------- Interval timing 
 6221: 
 6222: {
 6223: # Caches needed for speedup of navmaps
 6224: # We don't want to cache this for very long at all (5 seconds at most)
 6225: # 
 6226: # The user for whom we cache
 6227: my $cachedkey='';
 6228: # The cached times for this user
 6229: my %cachedtimes=();
 6230: # When this was last done
 6231: my $cachedtime='';
 6232: 
 6233: sub load_all_first_access {
 6234:     my ($uname,$udom,$ignorecache)=@_;
 6235:     if (($cachedkey eq $uname.':'.$udom) &&
 6236:         (abs($cachedtime-time)<5) && (!$env{'form.markaccess'}) &&
 6237:         (!$ignorecache)) {
 6238:         return;
 6239:     }
 6240:     $cachedtime=time;
 6241:     $cachedkey=$uname.':'.$udom;
 6242:     %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
 6243: }
 6244: 
 6245: sub get_first_access {
 6246:     my ($type,$argsymb,$argmap,$ignorecache)=@_;
 6247:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 6248:     if ($argsymb) { $symb=$argsymb; }
 6249:     my ($map,$id,$res)=&decode_symb($symb);
 6250:     if ($argmap) { $map = $argmap; }
 6251:     if ($type eq 'course') {
 6252: 	$res='course';
 6253:     } elsif ($type eq 'map') {
 6254: 	$res=&symbread($map);
 6255:     } else {
 6256: 	$res=$symb;
 6257:     }
 6258:     &load_all_first_access($uname,$udom,$ignorecache);
 6259:     return $cachedtimes{"$courseid\0$res"};
 6260: }
 6261: 
 6262: sub set_first_access {
 6263:     my ($type,$interval)=@_;
 6264:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 6265:     my ($map,$id,$res)=&decode_symb($symb);
 6266:     if ($type eq 'course') {
 6267: 	$res='course';
 6268:     } elsif ($type eq 'map') {
 6269: 	$res=&symbread($map);
 6270:     } else {
 6271: 	$res=$symb;
 6272:     }
 6273:     $cachedkey='';
 6274:     my $firstaccess=&get_first_access($type,$symb,$map);
 6275:     if ($firstaccess) {
 6276:         &logthis("First access time already set ($firstaccess) when attempting ".
 6277:                  "to set new value (type: $type, extent: $res) for $uname:$udom ".
 6278:                  "in $courseid");
 6279:         return 'already_set';
 6280:     } else {
 6281:         my $start = time;
 6282: 	my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
 6283:                           $udom,$uname);
 6284:         if ($putres eq 'ok') {
 6285:             &put('timerinterval',{"$courseid\0$res"=>$interval},
 6286:                  $udom,$uname); 
 6287:             &appenv(
 6288:                      {
 6289:                         'course.'.$courseid.'.firstaccess.'.$res   => $start,
 6290:                         'course.'.$courseid.'.timerinterval.'.$res => $interval,
 6291:                      }
 6292:                   );
 6293:             if (($cachedtime) && (abs($start-$cachedtime) < 5)) {
 6294:                 $cachedtimes{"$courseid\0$res"} = $start;
 6295:             }
 6296:         } elsif ($putres ne 'refused') {
 6297:             &logthis("Result: $putres when attempting to set first access time ".
 6298:                      "(type: $type, extent: $res) for $uname:$udom in $courseid");
 6299:         }
 6300:         return $putres;
 6301:     }
 6302:     return 'already_set';
 6303: }
 6304: }
 6305: 
 6306: # --------------------------------------------- Set Expire Date for Spreadsheet
 6307: 
 6308: sub expirespread {
 6309:     my ($uname,$udom,$stype,$usymb)=@_;
 6310:     my $cid=$env{'request.course.id'}; 
 6311:     if ($cid) {
 6312:        my $now=time;
 6313:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
 6314:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
 6315:                             $env{'course.'.$cid.'.num'}.
 6316: 	        	    ':nohist_expirationdates:'.
 6317:                             &escape($key).'='.$now,
 6318:                             $env{'course.'.$cid.'.home'})
 6319:     }
 6320:     return 'ok';
 6321: }
 6322: 
 6323: # ----------------------------------------------------- Devalidate Spreadsheets
 6324: 
 6325: sub devalidate {
 6326:     my ($symb,$uname,$udom)=@_;
 6327:     my $cid=$env{'request.course.id'}; 
 6328:     if ($cid) {
 6329:         # delete the stored spreadsheets for
 6330:         # - the student level sheet of this user in course's homespace
 6331:         # - the assessment level sheet for this resource 
 6332:         #   for this user in user's homespace
 6333: 	# - current conditional state info
 6334: 	my $key=$uname.':'.$udom.':';
 6335:         my $status=
 6336: 	    &del('nohist_calculatedsheets',
 6337: 		 [$key.'studentcalc:'],
 6338: 		 $env{'course.'.$cid.'.domain'},
 6339: 		 $env{'course.'.$cid.'.num'})
 6340: 		.' '.
 6341: 	    &del('nohist_calculatedsheets_'.$cid,
 6342: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
 6343:         unless ($status eq 'ok ok') {
 6344:            &logthis('Could not devalidate spreadsheet '.
 6345:                     $uname.' at '.$udom.' for '.
 6346: 		    $symb.': '.$status);
 6347:         }
 6348: 	&delenv('user.state.'.$cid);
 6349:     }
 6350: }
 6351: 
 6352: sub get_scalar {
 6353:     my ($string,$end) = @_;
 6354:     my $value;
 6355:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
 6356: 	$value = $1;
 6357:     } elsif ($$string =~ s/^([^&]*?)&//) {
 6358: 	$value = $1;
 6359:     }
 6360:     return &unescape($value);
 6361: }
 6362: 
 6363: sub array2str {
 6364:   my (@array) = @_;
 6365:   my $result=&arrayref2str(\@array);
 6366:   $result=~s/^__ARRAY_REF__//;
 6367:   $result=~s/__END_ARRAY_REF__$//;
 6368:   return $result;
 6369: }
 6370: 
 6371: sub arrayref2str {
 6372:   my ($arrayref) = @_;
 6373:   my $result='__ARRAY_REF__';
 6374:   foreach my $elem (@$arrayref) {
 6375:     if(ref($elem) eq 'ARRAY') {
 6376:       $result.=&arrayref2str($elem).'&';
 6377:     } elsif(ref($elem) eq 'HASH') {
 6378:       $result.=&hashref2str($elem).'&';
 6379:     } elsif(ref($elem)) {
 6380:       #print("Got a ref of ".(ref($elem))." skipping.");
 6381:     } else {
 6382:       $result.=&escape($elem).'&';
 6383:     }
 6384:   }
 6385:   $result=~s/\&$//;
 6386:   $result .= '__END_ARRAY_REF__';
 6387:   return $result;
 6388: }
 6389: 
 6390: sub hash2str {
 6391:   my (%hash) = @_;
 6392:   my $result=&hashref2str(\%hash);
 6393:   $result=~s/^__HASH_REF__//;
 6394:   $result=~s/__END_HASH_REF__$//;
 6395:   return $result;
 6396: }
 6397: 
 6398: sub hashref2str {
 6399:   my ($hashref)=@_;
 6400:   my $result='__HASH_REF__';
 6401:   foreach my $key (sort(keys(%$hashref))) {
 6402:     if (ref($key) eq 'ARRAY') {
 6403:       $result.=&arrayref2str($key).'=';
 6404:     } elsif (ref($key) eq 'HASH') {
 6405:       $result.=&hashref2str($key).'=';
 6406:     } elsif (ref($key)) {
 6407:       $result.='=';
 6408:       #print("Got a ref of ".(ref($key))." skipping.");
 6409:     } else {
 6410: 	if (defined($key)) {$result.=&escape($key).'=';} else { last; }
 6411:     }
 6412: 
 6413:     if(ref($hashref->{$key}) eq 'ARRAY') {
 6414:       $result.=&arrayref2str($hashref->{$key}).'&';
 6415:     } elsif(ref($hashref->{$key}) eq 'HASH') {
 6416:       $result.=&hashref2str($hashref->{$key}).'&';
 6417:     } elsif(ref($hashref->{$key})) {
 6418:        $result.='&';
 6419:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
 6420:     } else {
 6421:       $result.=&escape($hashref->{$key}).'&';
 6422:     }
 6423:   }
 6424:   $result=~s/\&$//;
 6425:   $result .= '__END_HASH_REF__';
 6426:   return $result;
 6427: }
 6428: 
 6429: sub str2hash {
 6430:     my ($string)=@_;
 6431:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
 6432:     return %$hash;
 6433: }
 6434: 
 6435: sub str2hashref {
 6436:   my ($string) = @_;
 6437: 
 6438:   my %hash;
 6439: 
 6440:   if($string !~ /^__HASH_REF__/) {
 6441:       if (! ($string eq '' || !defined($string))) {
 6442: 	  $hash{'error'}='Not hash reference';
 6443:       }
 6444:       return (\%hash, $string);
 6445:   }
 6446: 
 6447:   $string =~ s/^__HASH_REF__//;
 6448: 
 6449:   while($string !~ /^__END_HASH_REF__/) {
 6450:       #key
 6451:       my $key='';
 6452:       if($string =~ /^__HASH_REF__/) {
 6453:           ($key, $string)=&str2hashref($string);
 6454:           if(defined($key->{'error'})) {
 6455:               $hash{'error'}='Bad data';
 6456:               return (\%hash, $string);
 6457:           }
 6458:       } elsif($string =~ /^__ARRAY_REF__/) {
 6459:           ($key, $string)=&str2arrayref($string);
 6460:           if($key->[0] eq 'Array reference error') {
 6461:               $hash{'error'}='Bad data';
 6462:               return (\%hash, $string);
 6463:           }
 6464:       } else {
 6465:           $string =~ s/^(.*?)=//;
 6466: 	  $key=&unescape($1);
 6467:       }
 6468:       $string =~ s/^=//;
 6469: 
 6470:       #value
 6471:       my $value='';
 6472:       if($string =~ /^__HASH_REF__/) {
 6473:           ($value, $string)=&str2hashref($string);
 6474:           if(defined($value->{'error'})) {
 6475:               $hash{'error'}='Bad data';
 6476:               return (\%hash, $string);
 6477:           }
 6478:       } elsif($string =~ /^__ARRAY_REF__/) {
 6479:           ($value, $string)=&str2arrayref($string);
 6480:           if($value->[0] eq 'Array reference error') {
 6481:               $hash{'error'}='Bad data';
 6482:               return (\%hash, $string);
 6483:           }
 6484:       } else {
 6485: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
 6486:       }
 6487:       $string =~ s/^&//;
 6488: 
 6489:       $hash{$key}=$value;
 6490:   }
 6491: 
 6492:   $string =~ s/^__END_HASH_REF__//;
 6493: 
 6494:   return (\%hash, $string);
 6495: }
 6496: 
 6497: sub str2array {
 6498:     my ($string)=@_;
 6499:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
 6500:     return @$array;
 6501: }
 6502: 
 6503: sub str2arrayref {
 6504:   my ($string) = @_;
 6505:   my @array;
 6506: 
 6507:   if($string !~ /^__ARRAY_REF__/) {
 6508:       if (! ($string eq '' || !defined($string))) {
 6509: 	  $array[0]='Array reference error';
 6510:       }
 6511:       return (\@array, $string);
 6512:   }
 6513: 
 6514:   $string =~ s/^__ARRAY_REF__//;
 6515: 
 6516:   while($string !~ /^__END_ARRAY_REF__/) {
 6517:       my $value='';
 6518:       if($string =~ /^__HASH_REF__/) {
 6519:           ($value, $string)=&str2hashref($string);
 6520:           if(defined($value->{'error'})) {
 6521:               $array[0] ='Array reference error';
 6522:               return (\@array, $string);
 6523:           }
 6524:       } elsif($string =~ /^__ARRAY_REF__/) {
 6525:           ($value, $string)=&str2arrayref($string);
 6526:           if($value->[0] eq 'Array reference error') {
 6527:               $array[0] ='Array reference error';
 6528:               return (\@array, $string);
 6529:           }
 6530:       } else {
 6531: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
 6532:       }
 6533:       $string =~ s/^&//;
 6534: 
 6535:       push(@array, $value);
 6536:   }
 6537: 
 6538:   $string =~ s/^__END_ARRAY_REF__//;
 6539: 
 6540:   return (\@array, $string);
 6541: }
 6542: 
 6543: # -------------------------------------------------------------------Temp Store
 6544: 
 6545: sub tmpreset {
 6546:   my ($symb,$namespace,$domain,$stuname) = @_;
 6547:   if (!$symb) {
 6548:     $symb=&symbread();
 6549:     if (!$symb) { $symb= $env{'request.url'}; }
 6550:   }
 6551:   $symb=escape($symb);
 6552: 
 6553:   if (!$namespace) { $namespace=$env{'request.state'}; }
 6554:   $namespace=~s/\//\_/g;
 6555:   $namespace=~s/\W//g;
 6556: 
 6557:   if (!$domain) { $domain=$env{'user.domain'}; }
 6558:   if (!$stuname) { $stuname=$env{'user.name'}; }
 6559:   if ($domain eq 'public' && $stuname eq 'public') {
 6560:       $stuname=&get_requestor_ip();
 6561:   }
 6562:   my $path=LONCAPA::tempdir();
 6563:   my %hash;
 6564:   if (tie(%hash,'GDBM_File',
 6565: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 6566: 	  &GDBM_WRCREAT(),0640)) {
 6567:     foreach my $key (keys(%hash)) {
 6568:       if ($key=~ /:$symb/) {
 6569: 	delete($hash{$key});
 6570:       }
 6571:     }
 6572:   }
 6573: }
 6574: 
 6575: sub tmpstore {
 6576:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 6577: 
 6578:   if (!$symb) {
 6579:     $symb=&symbread();
 6580:     if (!$symb) { $symb= $env{'request.url'}; }
 6581:   }
 6582:   $symb=escape($symb);
 6583: 
 6584:   if (!$namespace) {
 6585:     # I don't think we would ever want to store this for a course.
 6586:     # it seems this will only be used if we don't have a course.
 6587:     #$namespace=$env{'request.course.id'};
 6588:     #if (!$namespace) {
 6589:       $namespace=$env{'request.state'};
 6590:     #}
 6591:   }
 6592:   $namespace=~s/\//\_/g;
 6593:   $namespace=~s/\W//g;
 6594:   if (!$domain) { $domain=$env{'user.domain'}; }
 6595:   if (!$stuname) { $stuname=$env{'user.name'}; }
 6596:   if ($domain eq 'public' && $stuname eq 'public') {
 6597:       $stuname=&get_requestor_ip();
 6598:   }
 6599:   my $now=time;
 6600:   my %hash;
 6601:   my $path=LONCAPA::tempdir();
 6602:   if (tie(%hash,'GDBM_File',
 6603: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 6604: 	  &GDBM_WRCREAT(),0640)) {
 6605:     $hash{"version:$symb"}++;
 6606:     my $version=$hash{"version:$symb"};
 6607:     my $allkeys=''; 
 6608:     foreach my $key (keys(%$storehash)) {
 6609:       $allkeys.=$key.':';
 6610:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
 6611:     }
 6612:     $hash{"$version:$symb:timestamp"}=$now;
 6613:     $allkeys.='timestamp';
 6614:     $hash{"$version:keys:$symb"}=$allkeys;
 6615:     if (untie(%hash)) {
 6616:       return 'ok';
 6617:     } else {
 6618:       return "error:$!";
 6619:     }
 6620:   } else {
 6621:     return "error:$!";
 6622:   }
 6623: }
 6624: 
 6625: # -----------------------------------------------------------------Temp Restore
 6626: 
 6627: sub tmprestore {
 6628:   my ($symb,$namespace,$domain,$stuname) = @_;
 6629: 
 6630:   if (!$symb) {
 6631:     $symb=&symbread();
 6632:     if (!$symb) { $symb= $env{'request.url'}; }
 6633:   }
 6634:   $symb=escape($symb);
 6635: 
 6636:   if (!$namespace) { $namespace=$env{'request.state'}; }
 6637: 
 6638:   if (!$domain) { $domain=$env{'user.domain'}; }
 6639:   if (!$stuname) { $stuname=$env{'user.name'}; }
 6640:   if ($domain eq 'public' && $stuname eq 'public') {
 6641:       $stuname=&get_requestor_ip();
 6642:   }
 6643:   my %returnhash;
 6644:   $namespace=~s/\//\_/g;
 6645:   $namespace=~s/\W//g;
 6646:   my %hash;
 6647:   my $path=LONCAPA::tempdir();
 6648:   if (tie(%hash,'GDBM_File',
 6649: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 6650: 	  &GDBM_READER(),0640)) {
 6651:     my $version=$hash{"version:$symb"};
 6652:     $returnhash{'version'}=$version;
 6653:     my $scope;
 6654:     for ($scope=1;$scope<=$version;$scope++) {
 6655:       my $vkeys=$hash{"$scope:keys:$symb"};
 6656:       my @keys=split(/:/,$vkeys);
 6657:       my $key;
 6658:       $returnhash{"$scope:keys"}=$vkeys;
 6659:       foreach $key (@keys) {
 6660: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 6661: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 6662:       }
 6663:     }
 6664:     if (!(untie(%hash))) {
 6665:       return "error:$!";
 6666:     }
 6667:   } else {
 6668:     return "error:$!";
 6669:   }
 6670:   return %returnhash;
 6671: }
 6672: 
 6673: # ----------------------------------------------------------------------- Store
 6674: 
 6675: sub store {
 6676:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
 6677:     my $home='';
 6678: 
 6679:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 6680: 
 6681:     $symb=&symbclean($symb);
 6682:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 6683: 
 6684:     if (!$domain) { $domain=$env{'user.domain'}; }
 6685:     if (!$stuname) { $stuname=$env{'user.name'}; }
 6686: 
 6687:     &devalidate($symb,$stuname,$domain);
 6688: 
 6689:     $symb=escape($symb);
 6690:     if (!$namespace) { 
 6691:        unless ($namespace=$env{'request.course.id'}) { 
 6692:           return ''; 
 6693:        } 
 6694:     }
 6695:     if (!$home) { $home=$env{'user.home'}; }
 6696: 
 6697:     $$storehash{'ip'}=&get_requestor_ip();
 6698:     $$storehash{'host'}=$perlvar{'lonHostID'};
 6699: 
 6700:     my $namevalue='';
 6701:     foreach my $key (keys(%$storehash)) {
 6702:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 6703:     }
 6704:     $namevalue=~s/\&$//;
 6705:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
 6706:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
 6707: }
 6708: 
 6709: # -------------------------------------------------------------- Critical Store
 6710: 
 6711: sub cstore {
 6712:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
 6713:     my $home='';
 6714: 
 6715:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 6716: 
 6717:     $symb=&symbclean($symb);
 6718:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 6719: 
 6720:     if (!$domain) { $domain=$env{'user.domain'}; }
 6721:     if (!$stuname) { $stuname=$env{'user.name'}; }
 6722: 
 6723:     &devalidate($symb,$stuname,$domain);
 6724: 
 6725:     $symb=escape($symb);
 6726:     if (!$namespace) { 
 6727:        unless ($namespace=$env{'request.course.id'}) { 
 6728:           return ''; 
 6729:        } 
 6730:     }
 6731:     if (!$home) { $home=$env{'user.home'}; }
 6732: 
 6733:     $$storehash{'ip'}=&get_requestor_ip();
 6734:     $$storehash{'host'}=$perlvar{'lonHostID'};
 6735: 
 6736:     my $namevalue='';
 6737:     foreach my $key (keys(%$storehash)) {
 6738:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 6739:     }
 6740:     $namevalue=~s/\&$//;
 6741:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
 6742:     return critical
 6743:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
 6744: }
 6745: 
 6746: # --------------------------------------------------------------------- Restore
 6747: 
 6748: sub restore {
 6749:     my ($symb,$namespace,$domain,$stuname) = @_;
 6750:     my $home='';
 6751: 
 6752:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 6753: 
 6754:     if (!$symb) {
 6755:         return if ($namespace eq 'courserequests');
 6756:         unless ($symb=escape(&symbread())) { return ''; }
 6757:     } else {
 6758:         unless ($namespace eq 'courserequests') {
 6759:             $symb=&escape(&symbclean($symb));
 6760:         }
 6761:     }
 6762:     if (!$namespace) { 
 6763:        unless ($namespace=$env{'request.course.id'}) { 
 6764:           return ''; 
 6765:        } 
 6766:     }
 6767:     if (!$domain) { $domain=$env{'user.domain'}; }
 6768:     if (!$stuname) { $stuname=$env{'user.name'}; }
 6769:     if (!$home) { $home=$env{'user.home'}; }
 6770:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
 6771: 
 6772:     my %returnhash=();
 6773:     foreach my $line (split(/\&/,$answer)) {
 6774: 	my ($name,$value)=split(/\=/,$line);
 6775:         $returnhash{&unescape($name)}=&thaw_unescape($value);
 6776:     }
 6777:     my $version;
 6778:     for ($version=1;$version<=$returnhash{'version'};$version++) {
 6779:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
 6780:           $returnhash{$item}=$returnhash{$version.':'.$item};
 6781:        }
 6782:     }
 6783:     return %returnhash;
 6784: }
 6785: 
 6786: # ---------------------------------------------------------- Course Description
 6787: #
 6788: #  
 6789: 
 6790: sub coursedescription {
 6791:     my ($courseid,$args)=@_;
 6792:     $courseid=~s/^\///;
 6793:     $courseid=~s/\_/\//g;
 6794:     my ($cdomain,$cnum)=split(/\//,$courseid);
 6795:     my $chome=&homeserver($cnum,$cdomain);
 6796:     my $normalid=$cdomain.'_'.$cnum;
 6797:     # need to always cache even if we get errors otherwise we keep 
 6798:     # trying and trying and trying to get the course description.
 6799:     my %envhash=();
 6800:     my %returnhash=();
 6801:     
 6802:     my $expiretime=600;
 6803:     if ($env{'request.course.id'} eq $normalid) {
 6804: 	$expiretime=120;
 6805:     }
 6806: 
 6807:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
 6808:     if (!$args->{'freshen_cache'}
 6809: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
 6810: 	foreach my $key (keys(%env)) {
 6811: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
 6812: 	    my ($setting) = $1;
 6813: 	    $returnhash{$setting} = $env{$key};
 6814: 	}
 6815: 	return %returnhash;
 6816:     }
 6817: 
 6818:     # get the data again
 6819: 
 6820:     if (!$args->{'one_time'}) {
 6821: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
 6822:     }
 6823: 
 6824:     if ($chome ne 'no_host') {
 6825:        %returnhash=&dump('environment',$cdomain,$cnum);
 6826:        if (!exists($returnhash{'con_lost'})) {
 6827: 	   my $username = $env{'user.name'}; # Defult username
 6828: 	   if(defined $args->{'user'}) {
 6829: 	       $username = $args->{'user'};
 6830: 	   }
 6831:            $returnhash{'home'}= $chome;
 6832: 	   $returnhash{'domain'} = $cdomain;
 6833: 	   $returnhash{'num'} = $cnum;
 6834:            if (!defined($returnhash{'type'})) {
 6835:                $returnhash{'type'} = 'Course';
 6836:            }
 6837:            while (my ($name,$value) = each %returnhash) {
 6838:                $envhash{'course.'.$normalid.'.'.$name}=$value;
 6839:            }
 6840:            $returnhash{'url'}=&clutter($returnhash{'url'});
 6841:            $returnhash{'fn'}=LONCAPA::tempdir() .
 6842: 	       $username.'_'.$cdomain.'_'.$cnum;
 6843:            $envhash{'course.'.$normalid.'.home'}=$chome;
 6844:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
 6845:            $envhash{'course.'.$normalid.'.num'}=$cnum;
 6846:        }
 6847:     }
 6848:     if (!$args->{'one_time'}) {
 6849: 	&appenv(\%envhash);
 6850:     }
 6851:     return %returnhash;
 6852: }
 6853: 
 6854: sub update_released_required {
 6855:     my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
 6856:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
 6857:         $cid = $env{'request.course.id'};
 6858:         $cdom = $env{'course.'.$cid.'.domain'};
 6859:         $cnum = $env{'course.'.$cid.'.num'};
 6860:         $chome = $env{'course.'.$cid.'.home'};
 6861:     }
 6862:     if ($needsrelease) {
 6863:         my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
 6864:         my $needsupdate;
 6865:         if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
 6866:             $needsupdate = 1;
 6867:         } else {
 6868:             my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
 6869:             my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
 6870:             if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
 6871:                 $needsupdate = 1;
 6872:             }
 6873:         }
 6874:         if ($needsupdate) {
 6875:             my %needshash = (
 6876:                              'internal.releaserequired' => $needsrelease,
 6877:                             );
 6878:             my $putresult = &put('environment',\%needshash,$cdom,$cnum);
 6879:             if ($putresult eq 'ok') {
 6880:                 &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
 6881:                 my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
 6882:                 if (ref($crsinfo{$cid}) eq 'HASH') {
 6883:                     $crsinfo{$cid}{'releaserequired'} = $needsrelease;
 6884:                     &courseidput($cdom,\%crsinfo,$chome,'notime');
 6885:                 }
 6886:             }
 6887:         }
 6888:     }
 6889:     return;
 6890: }
 6891: 
 6892: # -------------------------------------------------See if a user is privileged
 6893: 
 6894: sub privileged {
 6895:     my ($username,$domain,$possdomains,$possroles)=@_;
 6896:     my $now = time;
 6897:     my $roles;
 6898:     if (ref($possroles) eq 'ARRAY') {
 6899:         $roles = $possroles; 
 6900:     } else {
 6901:         $roles = ['dc','su'];
 6902:     }
 6903:     if (ref($possdomains) eq 'ARRAY') {
 6904:         my %privileged = &privileged_by_domain($possdomains,$roles);
 6905:         foreach my $dom (@{$possdomains}) {
 6906:             if (($username =~ /^$match_username$/) && ($domain =~ /^$match_domain$/) &&
 6907:                 (ref($privileged{$dom}) eq 'HASH')) {
 6908:                 foreach my $role (@{$roles}) {
 6909:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
 6910:                         if (exists($privileged{$dom}{$role}{$username.':'.$domain})) {
 6911:                             my ($end,$start) = split(/:/,$privileged{$dom}{$role}{$username.':'.$domain});
 6912:                             return 1 unless (($end && $end < $now) ||
 6913:                                              ($start && $start > $now));
 6914:                         }
 6915:                     }
 6916:                 }
 6917:             }
 6918:         }
 6919:     } else {
 6920:         my %rolesdump = &dump("roles", $domain, $username) or return 0;
 6921:         my $now = time;
 6922: 
 6923:         for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys(%rolesdump)}) {
 6924:             my ($trole, $tend, $tstart) = split(/_/, $role);
 6925:             if (grep(/^\Q$trole\E$/,@{$roles})) {
 6926:                 return 1 unless ($tend && $tend < $now) 
 6927:                         or ($tstart && $tstart > $now);
 6928:             }
 6929:         }
 6930:     }
 6931:     return 0;
 6932: }
 6933: 
 6934: sub privileged_by_domain {
 6935:     my ($domains,$roles) = @_;
 6936:     my %privileged = ();
 6937:     my $cachetime = 60*60*24;
 6938:     my $now = time;
 6939:     unless ((ref($domains) eq 'ARRAY') && (ref($roles) eq 'ARRAY')) {
 6940:         return %privileged;
 6941:     }
 6942:     foreach my $dom (@{$domains}) {
 6943:         next if (ref($privileged{$dom}) eq 'HASH');
 6944:         my $needroles;
 6945:         foreach my $role (@{$roles}) {
 6946:             my ($result,$cached)=&is_cached_new('priv_'.$role,$dom);
 6947:             if (defined($cached)) {
 6948:                 if (ref($result) eq 'HASH') {
 6949:                     $privileged{$dom}{$role} = $result;
 6950:                 }
 6951:             } else {
 6952:                 $needroles = 1;
 6953:             }
 6954:         }
 6955:         if ($needroles) {
 6956:             my %dompersonnel = &get_domain_roles($dom,$roles);
 6957:             $privileged{$dom} = {};
 6958:             foreach my $server (keys(%dompersonnel)) {
 6959:                 if (ref($dompersonnel{$server}) eq 'HASH') {
 6960:                     foreach my $item (keys(%{$dompersonnel{$server}})) {
 6961:                         my ($trole,$uname,$udom,$rest) = split(/:/,$item,4);
 6962:                         my ($end,$start) = split(/:/,$dompersonnel{$server}{$item});
 6963:                         next if ($end && $end < $now);
 6964:                         $privileged{$dom}{$trole}{$uname.':'.$udom} = 
 6965:                             $dompersonnel{$server}{$item};
 6966:                     }
 6967:                 }
 6968:             }
 6969:             if (ref($privileged{$dom}) eq 'HASH') {
 6970:                 foreach my $role (@{$roles}) {
 6971:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
 6972:                         &do_cache_new('priv_'.$role,$dom,$privileged{$dom}{$role},$cachetime);
 6973:                     } else {
 6974:                         my %hash = ();
 6975:                         &do_cache_new('priv_'.$role,$dom,\%hash,$cachetime);
 6976:                     }
 6977:                 }
 6978:             }
 6979:         }
 6980:     }
 6981:     return %privileged;
 6982: }
 6983: 
 6984: # -------------------------------------------------------- Get user privileges
 6985: 
 6986: sub rolesinit {
 6987:     my ($domain, $username) = @_;
 6988:     my %userroles = ('user.login.time' => time);
 6989:     my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
 6990: 
 6991:     # firstaccess and timerinterval are related to timed maps/resources. 
 6992:     # also, blocking can be triggered by an activating timer
 6993:     # it's saved in the user's %env.
 6994:     my %firstaccess = &dump('firstaccesstimes', $domain, $username);
 6995:     my %timerinterval = &dump('timerinterval', $domain, $username);
 6996:     my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
 6997:         %timerintchk, %timerintenv, %coauthorenv);
 6998: 
 6999:     foreach my $key (keys(%firstaccess)) {
 7000:         my ($cid, $rest) = split(/\0/, $key);
 7001:         $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
 7002:     }
 7003: 
 7004:     foreach my $key (keys(%timerinterval)) {
 7005:         my ($cid,$rest) = split(/\0/,$key);
 7006:         $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
 7007:     }
 7008: 
 7009:     my %allroles=();
 7010:     my %allgroups=();
 7011:     my %gotcoauconfig=();
 7012:     my %domdefaults=();
 7013: 
 7014:     for my $area (grep { ! /^rolesdef_/ } keys(%rolesdump)) {
 7015:         my $role = $rolesdump{$area};
 7016:         $area =~ s/\_\w\w$//;
 7017: 
 7018:         my ($trole, $tend, $tstart, $group_privs);
 7019: 
 7020:         if ($role =~ /^cr/) {
 7021:         # Custom role, defined by a user 
 7022:         # e.g., user.role.cr/msu/smith/mynewrole
 7023:             if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
 7024:                 $trole = $1;
 7025:                 ($tend, $tstart) = split('_', $2);
 7026:             } else {
 7027:                 $trole = $role;
 7028:             }
 7029:         } elsif ($role =~ m|^gr/|) {
 7030:         # Role of member in a group, defined within a course/community
 7031:         # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
 7032:             ($trole, $tend, $tstart) = split(/_/, $role);
 7033:             next if $tstart eq '-1';
 7034:             ($trole, $group_privs) = split(/\//, $trole);
 7035:             $group_privs = &unescape($group_privs);
 7036:         } else {
 7037:         # Just a normal role, defined in roles.tab
 7038:             ($trole, $tend, $tstart) = split(/_/,$role);
 7039:         }
 7040: 
 7041:         my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
 7042:                  $username);
 7043:         @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
 7044: 
 7045:         # role expired or not available yet?
 7046:         $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or 
 7047:             ($tstart != 0 && $tstart > $userroles{'user.login.time'});
 7048: 
 7049:         next if $area eq '' or $trole eq '';
 7050: 
 7051:         my $spec = "$trole.$area";
 7052:         my ($tdummy, $tdomain, $trest) = split(/\//, $area);
 7053: 
 7054:         if ($trole =~ /^cr\//) {
 7055:         # Custom role, defined by a user
 7056:             &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
 7057:         } elsif ($trole eq 'gr') {
 7058:         # Role of a member in a group, defined within a course/community
 7059:             &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
 7060:             next;
 7061:         } else {
 7062:         # Normal role, defined in roles.tab
 7063:             &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
 7064:             if (($trole eq 'ca') || ($trole eq 'aa')) {
 7065:                 (undef,my ($audom,$auname)) = split(/\//,$area);
 7066:                 unless ($gotcoauconfig{$area}) {
 7067:                     my @ca_settings = ('authoreditors','coauthorlist','coauthoroptin');
 7068:                     my %info = &userenvironment($audom,$auname,@ca_settings);
 7069:                     $gotcoauconfig{$area} = 1;
 7070:                     foreach my $item (@ca_settings) {
 7071:                         if (exists($info{$item})) {
 7072:                             my $name = $item;
 7073:                             if ($item eq 'authoreditors') {
 7074:                                 $name = 'editors';
 7075:                                 unless ($info{'authoreditors'}) {
 7076:                                     my %domdefs;
 7077:                                     if (ref($domdefaults{$audom}) eq 'HASH') {
 7078:                                         %domdefs = %{$domdefaults{$audom}};
 7079:                                     } else {
 7080:                                         %domdefs = &get_domain_defaults($audom);
 7081:                                         $domdefaults{$audom} = \%domdefs;
 7082:                                     }
 7083:                                     if ($domdefs{$name} ne '') {
 7084:                                         $info{'authoreditors'} = $domdefs{$name};
 7085:                                     } else {
 7086:                                         $info{'authoreditors'} = 'edit,xml';
 7087:                                     }
 7088:                                 }
 7089:                             }
 7090:                             $coauthorenv{"environment.internal.$name.$area"} = $info{$item};
 7091:                         }
 7092:                     }
 7093:                 }
 7094:             }
 7095:         }
 7096: 
 7097:         my $cid = $tdomain.'_'.$trest;
 7098:         unless ($firstaccchk{$cid}) {
 7099:             if (ref($coursetimerstarts{$cid}) eq 'HASH') {
 7100:                 foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
 7101:                     $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} = 
 7102:                         $coursetimerstarts{$cid}{$item}; 
 7103:                 }
 7104:             }
 7105:             $firstaccchk{$cid} = 1;
 7106:         }
 7107:         unless ($timerintchk{$cid}) {
 7108:             if (ref($coursetimerintervals{$cid}) eq 'HASH') {
 7109:                 foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
 7110:                     $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
 7111:                        $coursetimerintervals{$cid}{$item};
 7112:                 }
 7113:             }
 7114:             $timerintchk{$cid} = 1;
 7115:         }
 7116:     }
 7117: 
 7118:     @userroles{'user.author','user.adv','user.rar'} = &set_userprivs(\%userroles,
 7119:                                                           \%allroles, \%allgroups);
 7120:     $env{'user.adv'} = $userroles{'user.adv'};
 7121:     $env{'user.rar'} = $userroles{'user.rar'};
 7122: 
 7123:     return (\%userroles,\%firstaccenv,\%timerintenv,\%coauthorenv);
 7124: }
 7125: 
 7126: sub set_arearole {
 7127:     my ($trole,$area,$tstart,$tend,$domain,$username,$nolog) = @_;
 7128:     unless ($nolog) {
 7129: # log the associated role with the area
 7130:         &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
 7131:     }
 7132:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
 7133: }
 7134: 
 7135: sub custom_roleprivs {
 7136:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
 7137:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
 7138:     my $homsvr = &homeserver($rauthor,$rdomain);
 7139:     if (&hostname($homsvr) ne '') {
 7140:         my ($rdummy,$roledef)=
 7141:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
 7142:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
 7143:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
 7144:             if (defined($syspriv)) {
 7145:                 if ($trest =~ /^$match_community$/) {
 7146:                     $syspriv =~ s/bre\&S//; 
 7147:                 }
 7148:                 $$allroles{'cm./'}.=':'.$syspriv;
 7149:                 $$allroles{$spec.'./'}.=':'.$syspriv;
 7150:             }
 7151:             if ($tdomain ne '') {
 7152:                 if (defined($dompriv)) {
 7153:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
 7154:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
 7155:                 }
 7156:                 if (($trest ne '') && (defined($coursepriv))) {
 7157:                     if ($trole =~ m{^cr/$tdomain/$tdomain\Q-domainconfig\E/([^/]+)$}) {
 7158:                         my $rolename = $1;
 7159:                         $coursepriv = &course_adhocrole_privs($rolename,$tdomain,$trest,$coursepriv);
 7160:                     }
 7161:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
 7162:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
 7163:                 }
 7164:             }
 7165:         }
 7166:     }
 7167: }
 7168: 
 7169: sub course_adhocrole_privs {
 7170:     my ($rolename,$cdom,$cnum,$coursepriv) = @_;
 7171:     my %overrides = &get('environment',["internal.adhocpriv.$rolename"],$cdom,$cnum);
 7172:     if ($overrides{"internal.adhocpriv.$rolename"}) {
 7173:         my (%currprivs,%storeprivs);
 7174:         foreach my $item (split(/:/,$coursepriv)) {
 7175:             my ($priv,$restrict) = split(/\&/,$item);
 7176:             $currprivs{$priv} = $restrict;
 7177:         }
 7178:         my (%possadd,%possremove,%full);
 7179:         foreach my $item (split(/\:/,$Apache::lonnet::pr{'cr:c'})) {
 7180:             my ($priv,$restrict)=split(/\&/,$item);
 7181:             $full{$priv} = $restrict;
 7182:         }
 7183:         foreach my $item (split(/,/,$overrides{"internal.adhocpriv.$rolename"})) {
 7184:             next if ($item eq '');
 7185:             my ($rule,$rest) = split(/=/,$item);
 7186:             next unless (($rule eq 'off') || ($rule eq 'on'));
 7187:             foreach my $priv (split(/:/,$rest)) {
 7188:                 if ($priv ne '') {
 7189:                     if ($rule eq 'off') {
 7190:                         $possremove{$priv} = 1;
 7191:                     } else {
 7192:                         $possadd{$priv} = 1;
 7193:                     }
 7194:                 }
 7195:             }
 7196:         }
 7197:         foreach my $priv (sort(keys(%full))) {
 7198:             if (exists($currprivs{$priv})) {
 7199:                 unless (exists($possremove{$priv})) {
 7200:                     $storeprivs{$priv} = $currprivs{$priv};
 7201:                 }
 7202:             } elsif (exists($possadd{$priv})) {
 7203:                 $storeprivs{$priv} = $full{$priv};
 7204:             }
 7205:         }
 7206:         $coursepriv = ':'.join(':',map { $_.'&'.$storeprivs{$_}; } sort(keys(%storeprivs)));
 7207:     }
 7208:     return $coursepriv;
 7209: }
 7210: 
 7211: sub group_roleprivs {
 7212:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
 7213:     my $access = 1;
 7214:     my $now = time;
 7215:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
 7216:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
 7217:     if ($access) {
 7218:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
 7219:         $$allgroups{$course}{$group} .=':'.$group_privs;
 7220:     }
 7221: }
 7222: 
 7223: sub standard_roleprivs {
 7224:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
 7225:     if (defined($pr{$trole.':s'})) {
 7226:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
 7227:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
 7228:     }
 7229:     if ($tdomain ne '') {
 7230:         if (defined($pr{$trole.':d'})) {
 7231:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 7232:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 7233:         }
 7234:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
 7235:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
 7236:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
 7237:         }
 7238:     }
 7239: }
 7240: 
 7241: sub set_userprivs {
 7242:     my ($userroles,$allroles,$allgroups,$groups_roles) = @_; 
 7243:     my $author=0;
 7244:     my $adv=0;
 7245:     my $rar=0;
 7246:     my %grouproles = ();
 7247:     if (keys(%{$allgroups}) > 0) {
 7248:         my @groupkeys; 
 7249:         foreach my $role (keys(%{$allroles})) {
 7250:             push(@groupkeys,$role);
 7251:         }
 7252:         if (ref($groups_roles) eq 'HASH') {
 7253:             foreach my $key (keys(%{$groups_roles})) {
 7254:                 unless (grep(/^\Q$key\E$/,@groupkeys)) {
 7255:                     push(@groupkeys,$key);
 7256:                 }
 7257:             }
 7258:         }
 7259:         if (@groupkeys > 0) {
 7260:             foreach my $role (@groupkeys) {
 7261:                 my ($trole,$area,$sec,$extendedarea);
 7262:                 if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
 7263:                     $trole = $1;
 7264:                     $area = $2;
 7265:                     $sec = $3;
 7266:                     $extendedarea = $area.$sec;
 7267:                     if (exists($$allgroups{$area})) {
 7268:                         foreach my $group (keys(%{$$allgroups{$area}})) {
 7269:                             my $spec = $trole.'.'.$extendedarea;
 7270:                             $grouproles{$spec.'.'.$area.'/'.$group} = 
 7271:                                                 $$allgroups{$area}{$group};
 7272:                         }
 7273:                     }
 7274:                 }
 7275:             }
 7276:         }
 7277:     }
 7278:     foreach my $group (keys(%grouproles)) {
 7279:         $$allroles{$group} = $grouproles{$group};
 7280:     }
 7281:     foreach my $role (keys(%{$allroles})) {
 7282:         my %thesepriv;
 7283:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
 7284:         foreach my $item (split(/:/,$$allroles{$role})) {
 7285:             if ($item ne '') {
 7286:                 my ($privilege,$restrictions)=split(/&/,$item);
 7287:                 if ($restrictions eq '') {
 7288:                     $thesepriv{$privilege}='F';
 7289:                 } elsif ($thesepriv{$privilege} ne 'F') {
 7290:                     $thesepriv{$privilege}.=$restrictions;
 7291:                 }
 7292:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
 7293:                 if ($thesepriv{'rar'} eq 'F') { $rar=1; }
 7294:             }
 7295:         }
 7296:         my $thesestr='';
 7297:         foreach my $priv (sort(keys(%thesepriv))) {
 7298: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
 7299: 	}
 7300:         $userroles->{'user.priv.'.$role} = $thesestr;
 7301:     }
 7302:     return ($author,$adv,$rar);
 7303: }
 7304: 
 7305: sub role_status {
 7306:     my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
 7307:     if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
 7308:         my ($one,$two) = split(m{\./},$rolekey,2);
 7309:         (undef,undef,$$role) = split(/\./,$one,3);
 7310:         unless (!defined($$role) || $$role eq '') {
 7311:             $$where = '/'.$two;
 7312:             $$trolecode=$$role.'.'.$$where;
 7313:             ($$tstart,$$tend)=split(/\./,$env{$rolekey});
 7314:             $$tstatus='is';
 7315:             if ($$tstart && $$tstart>$update) {
 7316:                 $$tstatus='future';
 7317:                 if ($$tstart<$now) {
 7318:                     if ($$tstart && $$tstart>$refresh) {
 7319:                         if (($$where ne '') && ($$role ne '')) {
 7320:                             my (%allroles,%allgroups,$group_privs,
 7321:                                 %groups_roles,@rolecodes);
 7322:                             my %userroles = (
 7323:                                 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
 7324:                             );
 7325:                             @rolecodes = ('cm'); 
 7326:                             my $spec=$$role.'.'.$$where;
 7327:                             my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
 7328:                             if ($$role =~ /^cr\//) {
 7329:                                 &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
 7330:                                 push(@rolecodes,'cr');
 7331:                             } elsif ($$role eq 'gr') {
 7332:                                 push(@rolecodes,$$role);
 7333:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
 7334:                                                     $env{'user.name'});
 7335:                                 my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
 7336:                                 (undef,my $group_privs) = split(/\//,$trole);
 7337:                                 $group_privs = &unescape($group_privs);
 7338:                                 &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
 7339:                                 my %course_roles = &get_my_roles($env{'user.name'},$env{'user.domain'},'userroles',['active'],['cc','co','in','ta','ep','ad','st','cr'],[$tdomain],1);
 7340:                                 &get_groups_roles($tdomain,$trest,
 7341:                                                   \%course_roles,\@rolecodes,
 7342:                                                   \%groups_roles);
 7343:                             } else {
 7344:                                 push(@rolecodes,$$role);
 7345:                                 &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
 7346:                             }
 7347:                             my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%allroles,\%allgroups,
 7348:                                                                    \%groups_roles);
 7349:                             &appenv(\%userroles,\@rolecodes);
 7350:                             &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
 7351:                         }
 7352:                     }
 7353:                     $$tstatus = 'is';
 7354:                 }
 7355:             }
 7356:             if ($$tend) {
 7357:                 if ($$tend<$update) {
 7358:                     $$tstatus='expired';
 7359:                 } elsif ($$tend<$now) {
 7360:                     $$tstatus='will_not';
 7361:                 }
 7362:             }
 7363:         }
 7364:     }
 7365: }
 7366: 
 7367: sub get_groups_roles {
 7368:     my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
 7369:     return unless((ref($cdom_courseroles) eq 'HASH') && 
 7370:                   (ref($rolecodes) eq 'ARRAY') && 
 7371:                   (ref($groups_roles) eq 'HASH')); 
 7372:     if (keys(%{$cdom_courseroles}) > 0) {
 7373:         my ($cnum) = ($rest =~ /^($match_courseid)/);
 7374:         if ($cdom ne '' && $cnum ne '') {
 7375:             foreach my $key (keys(%{$cdom_courseroles})) {
 7376:                 if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
 7377:                     my $crsrole = $1;
 7378:                     my $crssec = $2;
 7379:                     if ($crsrole =~ /^cr/) {
 7380:                         unless (grep(/^cr$/,@{$rolecodes})) {
 7381:                             push(@{$rolecodes},'cr');
 7382:                         }
 7383:                     } else {
 7384:                         unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
 7385:                             push(@{$rolecodes},$crsrole);
 7386:                         }
 7387:                     }
 7388:                     my $rolekey = "$crsrole./$cdom/$cnum";
 7389:                     if ($crssec ne '') {
 7390:                         $rolekey .= "/$crssec";
 7391:                     }
 7392:                     $rolekey .= './';
 7393:                     $groups_roles->{$rolekey} = $rolecodes;
 7394:                 }
 7395:             }
 7396:         }
 7397:     }
 7398:     return;
 7399: }
 7400: 
 7401: sub delete_env_groupprivs {
 7402:     my ($where,$courseroles,$possroles) = @_;
 7403:     return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
 7404:     my ($dummy,$udom,$uname,$group) = split(/\//,$where);
 7405:     unless (ref($courseroles->{$udom}) eq 'HASH') {
 7406:         %{$courseroles->{$udom}} =
 7407:             &get_my_roles('','','userroles',['active'],
 7408:                           $possroles,[$udom],1);
 7409:     }
 7410:     if (ref($courseroles->{$udom}) eq 'HASH') {
 7411:         foreach my $item (keys(%{$courseroles->{$udom}})) {
 7412:             my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
 7413:             my $area = '/'.$cdom.'/'.$cnum;
 7414:             my $privkey = "user.priv.$crsrole.$area";
 7415:             if ($crssec ne '') {
 7416:                 $privkey .= '/'.$crssec;
 7417:             }
 7418:             $privkey .= ".$area/$group";
 7419:             &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
 7420:         }
 7421:     }
 7422:     return;
 7423: }
 7424: 
 7425: sub check_adhoc_privs {
 7426:     my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller,$sec) = @_;
 7427:     my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
 7428:     if ($sec) {
 7429:         $cckey .= '/'.$sec;
 7430:     } 
 7431:     my $setprivs;
 7432:     if ($env{$cckey}) {
 7433:         my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
 7434:         &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
 7435:         unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
 7436:             &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
 7437:             $setprivs = 1;
 7438:         }
 7439:     } else {
 7440:         &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
 7441:         $setprivs = 1;
 7442:     }
 7443:     return $setprivs;
 7444: }
 7445: 
 7446: sub set_adhoc_privileges {
 7447: # role can be cc, ca, or cr/<dom>/<dom>-domainconfig/role
 7448:     my ($dcdom,$pickedcourse,$role,$caller,$sec) = @_;
 7449:     my $area = '/'.$dcdom.'/'.$pickedcourse;
 7450:     if ($sec ne '') {
 7451:         $area .= '/'.$sec;
 7452:     }
 7453:     my $spec = $role.'.'.$area;
 7454:     my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
 7455:                                   $env{'user.name'},1);
 7456:     my %rolehash = ();
 7457:     if ($role =~ m{^\Qcr/$dcdom/$dcdom\E\-domainconfig/(\w+)$}) {
 7458:         my $rolename = $1;
 7459:         &custom_roleprivs(\%rolehash,$role,$dcdom,$pickedcourse,$spec,$area);
 7460:         my %domdef = &get_domain_defaults($dcdom);
 7461:         if (ref($domdef{'adhocroles'}) eq 'HASH') {
 7462:             if (ref($domdef{'adhocroles'}{$rolename}) eq 'HASH') {
 7463:                 &appenv({'request.role.desc' => $domdef{'adhocroles'}{$rolename}{'desc'},});
 7464:             }
 7465:         }
 7466:     } else {
 7467:         &standard_roleprivs(\%rolehash,$role,$dcdom,$spec,$pickedcourse,$area);
 7468:     }
 7469:     my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%rolehash);
 7470:     &appenv(\%userroles,[$role,'cm']);
 7471:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
 7472:     unless (($caller eq 'constructaccess' && $env{'request.course.id'}) ||
 7473:             ($caller eq 'tiny')) {
 7474:         &appenv( {'request.role'        => $spec,
 7475:                   'request.role.domain' => $dcdom,
 7476:                   'request.course.sec'  => $sec,
 7477:                  }
 7478:                );
 7479:         my $tadv=0;
 7480:         if (&allowed('adv') eq 'F') { $tadv=1; }
 7481:         &appenv({'request.role.adv'    => $tadv});
 7482:     }
 7483: }
 7484: 
 7485: # --------------------------------------------------------------- get interface
 7486: 
 7487: sub get {
 7488:    my ($namespace,$storearr,$udomain,$uname)=@_;
 7489:    my $items='';
 7490:    foreach my $item (@$storearr) {
 7491:        $items.=&escape($item).'&';
 7492:    }
 7493:    $items=~s/\&$//;
 7494:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 7495:    if (!$uname) { $uname=$env{'user.name'}; }
 7496:    my $uhome=&homeserver($uname,$udomain);
 7497: 
 7498:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
 7499:    my @pairs=split(/\&/,$rep);
 7500:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
 7501:      return @pairs;
 7502:    }
 7503:    my %returnhash=();
 7504:    my $i=0;
 7505:    foreach my $item (@$storearr) {
 7506:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 7507:       $i++;
 7508:    }
 7509:    return %returnhash;
 7510: }
 7511: 
 7512: # --------------------------------------------------------------- del interface
 7513: 
 7514: sub del {
 7515:    my ($namespace,$storearr,$udomain,$uname)=@_;
 7516:    my $items='';
 7517:    foreach my $item (@$storearr) {
 7518:        $items.=&escape($item).'&';
 7519:    }
 7520: 
 7521:    $items=~s/\&$//;
 7522:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 7523:    if (!$uname) { $uname=$env{'user.name'}; }
 7524:    my $uhome=&homeserver($uname,$udomain);
 7525:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
 7526: }
 7527: 
 7528: # -------------------------------------------------------------- dump interface
 7529: 
 7530: sub unserialize {
 7531:     my ($rep, $escapedkeys) = @_;
 7532: 
 7533:     return {} if $rep =~ /^error/;
 7534: 
 7535:     my %returnhash=();
 7536: 	foreach my $item (split(/\&/,$rep)) {
 7537: 	    my ($key, $value) = split(/=/, $item, 2);
 7538: 	    $key = unescape($key) unless $escapedkeys;
 7539: 	    next if $key =~ /^error: 2 /;
 7540: 	    $returnhash{$key} = &thaw_unescape($value);
 7541: 	}
 7542:     #return %returnhash;
 7543:     return \%returnhash;
 7544: }        
 7545: 
 7546: # see Lond::dump_with_regexp
 7547: # if $escapedkeys hash keys won't get unescaped.
 7548: sub dump {
 7549:     my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys,$encrypt)=@_;
 7550:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 7551:     if (!$uname) { $uname=$env{'user.name'}; }
 7552:     my $uhome=&homeserver($uname,$udomain);
 7553: 
 7554:     if ($regexp) {
 7555:         $regexp=&escape($regexp);
 7556:     } else {
 7557:         $regexp='.';
 7558:     }
 7559:     if (grep { $_ eq $uhome } current_machine_ids()) {
 7560:         # user is hosted on this machine
 7561:         my $reply = LONCAPA::Lond::dump_with_regexp(join(":", ($udomain,
 7562:                     $uname, $namespace, $regexp, $range)), $perlvar{'lonVersion'});
 7563:         return %{unserialize($reply, $escapedkeys)};
 7564:     }
 7565:     my $rep;
 7566:     if ($encrypt) {
 7567:         $rep=&reply("encrypt:edump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
 7568:     } else {
 7569:         $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
 7570:     }
 7571:     my @pairs=split(/\&/,$rep);
 7572:     my %returnhash=();
 7573:     if (!($rep =~ /^error/ )) {
 7574: 	foreach my $item (@pairs) {
 7575: 	    my ($key,$value)=split(/=/,$item,2);
 7576:         $key = unescape($key) unless $escapedkeys;
 7577:         #$key = &unescape($key);
 7578: 	    next if ($key =~ /^error: 2 /);
 7579: 	    $returnhash{$key}=&thaw_unescape($value);
 7580: 	}
 7581:     }
 7582:     return %returnhash;
 7583: }
 7584: 
 7585: 
 7586: # --------------------------------------------------------- dumpstore interface
 7587: 
 7588: sub dumpstore {
 7589:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
 7590:    # same as dump but keys must be escaped. They may contain colon separated
 7591:    # lists of values that may themself contain colons (e.g. symbs).
 7592:    return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
 7593: }
 7594: 
 7595: # -------------------------------------------------------------- keys interface
 7596: 
 7597: sub getkeys {
 7598:    my ($namespace,$udomain,$uname)=@_;
 7599:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 7600:    if (!$uname) { $uname=$env{'user.name'}; }
 7601:    my $uhome=&homeserver($uname,$udomain);
 7602:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
 7603:    my @keyarray=();
 7604:    foreach my $key (split(/\&/,$rep)) {
 7605:       next if ($key =~ /^error: 2 /);
 7606:       push(@keyarray,&unescape($key));
 7607:    }
 7608:    return @keyarray;
 7609: }
 7610: 
 7611: # --------------------------------------------------------------- currentdump
 7612: sub currentdump {
 7613:    my ($courseid,$sdom,$sname)=@_;
 7614:    $courseid = $env{'request.course.id'} if (! defined($courseid));
 7615:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
 7616:    $sname    = $env{'user.name'}         if (! defined($sname));
 7617:    my $uhome = &homeserver($sname,$sdom);
 7618:    my $rep;
 7619: 
 7620:    if (grep { $_ eq $uhome } current_machine_ids()) {
 7621:        $rep = LONCAPA::Lond::dump_profile_database(join(":", ($sdom, $sname, 
 7622:                    $courseid)));
 7623:    } else {
 7624:        $rep = reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
 7625:    }
 7626: 
 7627:    return if ($rep =~ /^(error:|no_such_host)/);
 7628:    #
 7629:    my %returnhash=();
 7630:    #
 7631:    if ($rep eq 'unknown_cmd') {
 7632:        # an old lond will not know currentdump
 7633:        # Do a dump and make it look like a currentdump
 7634:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
 7635:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
 7636:        my %hash = @tmp;
 7637:        @tmp=();
 7638:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
 7639:    } else {
 7640:        my @pairs=split(/\&/,$rep);
 7641:        foreach my $pair (@pairs) {
 7642:            my ($key,$value)=split(/=/,$pair,2);
 7643:            my ($symb,$param) = split(/:/,$key);
 7644:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
 7645:                                                         &thaw_unescape($value);
 7646:        }
 7647:    }
 7648:    return %returnhash;
 7649: }
 7650: 
 7651: sub convert_dump_to_currentdump{
 7652:     my %hash = %{shift()};
 7653:     my %returnhash;
 7654:     # Code ripped from lond, essentially.  The only difference
 7655:     # here is the unescaping done by lonnet::dump().  Conceivably
 7656:     # we might run in to problems with parameter names =~ /^v\./
 7657:     while (my ($key,$value) = each(%hash)) {
 7658:         my ($v,$symb,$param) = split(/:/,$key);
 7659: 	$symb  = &unescape($symb);
 7660: 	$param = &unescape($param);
 7661:         next if ($v eq 'version' || $symb eq 'keys');
 7662:         next if (exists($returnhash{$symb}) &&
 7663:                  exists($returnhash{$symb}->{$param}) &&
 7664:                  $returnhash{$symb}->{'v.'.$param} > $v);
 7665:         $returnhash{$symb}->{$param}=$value;
 7666:         $returnhash{$symb}->{'v.'.$param}=$v;
 7667:     }
 7668:     #
 7669:     # Remove all of the keys in the hashes which keep track of
 7670:     # the version of the parameter.
 7671:     while (my ($symb,$param_hash) = each(%returnhash)) {
 7672:         # use a foreach because we are going to delete from the hash.
 7673:         foreach my $key (keys(%$param_hash)) {
 7674:             delete($param_hash->{$key}) if ($key =~ /^v\./);
 7675:         }
 7676:     }
 7677:     return \%returnhash;
 7678: }
 7679: 
 7680: # ------------------------------------------------------ critical inc interface
 7681: 
 7682: sub cinc {
 7683:     return &inc(@_,'critical');
 7684: }
 7685: 
 7686: # --------------------------------------------------------------- inc interface
 7687: 
 7688: sub inc {
 7689:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
 7690:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 7691:     if (!$uname) { $uname=$env{'user.name'}; }
 7692:     my $uhome=&homeserver($uname,$udomain);
 7693:     my $items='';
 7694:     if (! ref($store)) {
 7695:         # got a single value, so use that instead
 7696:         $items = &escape($store).'=&';
 7697:     } elsif (ref($store) eq 'SCALAR') {
 7698:         $items = &escape($$store).'=&';        
 7699:     } elsif (ref($store) eq 'ARRAY') {
 7700:         $items = join('=&',map {&escape($_);} @{$store});
 7701:     } elsif (ref($store) eq 'HASH') {
 7702:         while (my($key,$value) = each(%{$store})) {
 7703:             $items.= &escape($key).'='.&escape($value).'&';
 7704:         }
 7705:     }
 7706:     $items=~s/\&$//;
 7707:     if ($critical) {
 7708: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
 7709:     } else {
 7710: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
 7711:     }
 7712: }
 7713: 
 7714: # --------------------------------------------------------------- put interface
 7715: 
 7716: sub put {
 7717:    my ($namespace,$storehash,$udomain,$uname,$encrypt)=@_;
 7718:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 7719:    if (!$uname) { $uname=$env{'user.name'}; }
 7720:    my $uhome=&homeserver($uname,$udomain);
 7721:    my $items='';
 7722:    foreach my $item (keys(%$storehash)) {
 7723:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 7724:    }
 7725:    $items=~s/\&$//;
 7726:    if ($encrypt) {
 7727:        return &reply("encrypt:put:$udomain:$uname:$namespace:$items",$uhome);
 7728:    } else {
 7729:        return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 7730:    }
 7731: }
 7732: 
 7733: # ------------------------------------------------------------ newput interface
 7734: 
 7735: sub newput {
 7736:    my ($namespace,$storehash,$udomain,$uname)=@_;
 7737:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 7738:    if (!$uname) { $uname=$env{'user.name'}; }
 7739:    my $uhome=&homeserver($uname,$udomain);
 7740:    my $items='';
 7741:    foreach my $key (keys(%$storehash)) {
 7742:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 7743:    }
 7744:    $items=~s/\&$//;
 7745:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
 7746: }
 7747: 
 7748: # ---------------------------------------------------------  putstore interface
 7749: 
 7750: sub putstore {
 7751:    my ($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog)=@_;
 7752:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 7753:    if (!$uname) { $uname=$env{'user.name'}; }
 7754:    my $uhome=&homeserver($uname,$udomain);
 7755:    my $items='';
 7756:    foreach my $key (keys(%$storehash)) {
 7757:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
 7758:    }
 7759:    $items=~s/\&$//;
 7760:    my $esc_symb=&escape($symb);
 7761:    my $esc_v=&escape($version);
 7762:    my $reply =
 7763:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
 7764: 	      $uhome);
 7765:    if (($tolog) && ($reply eq 'ok')) {
 7766:        my $namevalue='';
 7767:        foreach my $key (keys(%{$storehash})) {
 7768:            $namevalue.=&escape($key).'='.&freeze_escape($storehash->{$key}).'&';
 7769:        }
 7770:        my $ip = &get_requestor_ip();
 7771:        $namevalue .= 'ip='.&escape($ip).
 7772:                      '&host='.&escape($perlvar{'lonHostID'}).
 7773:                      '&version='.$esc_v.
 7774:                      '&by='.&escape($env{'user.name'}.':'.$env{'user.domain'});
 7775:        &courselog($symb.':'.$uname.':'.$udomain.':PUTSTORE:'.$namevalue);
 7776:    }
 7777:    if ($reply eq 'unknown_cmd') {
 7778:        # gfall back to way things use to be done
 7779:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
 7780: 			    $uname);
 7781:    }
 7782:    return $reply;
 7783: }
 7784: 
 7785: sub old_putstore {
 7786:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
 7787:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 7788:     if (!$uname) { $uname=$env{'user.name'}; }
 7789:     my $uhome=&homeserver($uname,$udomain);
 7790:     my %newstorehash;
 7791:     foreach my $item (keys(%$storehash)) {
 7792: 	my $key = $version.':'.&escape($symb).':'.$item;
 7793: 	$newstorehash{$key} = $storehash->{$item};
 7794:     }
 7795:     my $items='';
 7796:     my %allitems = ();
 7797:     foreach my $item (keys(%newstorehash)) {
 7798: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
 7799: 	    my $key = $1.':keys:'.$2;
 7800: 	    $allitems{$key} .= $3.':';
 7801: 	}
 7802: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
 7803:     }
 7804:     foreach my $item (keys(%allitems)) {
 7805: 	$allitems{$item} =~ s/\:$//;
 7806: 	$items.= $item.'='.$allitems{$item}.'&';
 7807:     }
 7808:     $items=~s/\&$//;
 7809:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 7810: }
 7811: 
 7812: # ------------------------------------------------------ critical put interface
 7813: 
 7814: sub cput {
 7815:    my ($namespace,$storehash,$udomain,$uname)=@_;
 7816:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 7817:    if (!$uname) { $uname=$env{'user.name'}; }
 7818:    my $uhome=&homeserver($uname,$udomain);
 7819:    my $items='';
 7820:    foreach my $item (keys(%$storehash)) {
 7821:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 7822:    }
 7823:    $items=~s/\&$//;
 7824:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
 7825: }
 7826: 
 7827: # -------------------------------------------------------------- eget interface
 7828: 
 7829: sub eget {
 7830:    my ($namespace,$storearr,$udomain,$uname)=@_;
 7831:    my $items='';
 7832:    foreach my $item (@$storearr) {
 7833:        $items.=&escape($item).'&';
 7834:    }
 7835:    $items=~s/\&$//;
 7836:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 7837:    if (!$uname) { $uname=$env{'user.name'}; }
 7838:    my $uhome=&homeserver($uname,$udomain);
 7839:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
 7840:    my @pairs=split(/\&/,$rep);
 7841:    my %returnhash=();
 7842:    my $i=0;
 7843:    foreach my $item (@$storearr) {
 7844:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 7845:       $i++;
 7846:    }
 7847:    return %returnhash;
 7848: }
 7849: 
 7850: # ------------------------------------------------------------ tmpput interface
 7851: sub tmpput {
 7852:     my ($storehash,$server,$context)=@_;
 7853:     my $items='';
 7854:     foreach my $item (keys(%$storehash)) {
 7855: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 7856:     }
 7857:     $items=~s/\&$//;
 7858:     if (defined($context)) {
 7859:         $items .= ':'.&escape($context);
 7860:     }
 7861:     return &reply("tmpput:$items",$server);
 7862: }
 7863: 
 7864: # ------------------------------------------------------------ tmpget interface
 7865: sub tmpget {
 7866:     my ($token,$server)=@_;
 7867:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 7868:     my $rep=&reply("tmpget:$token",$server);
 7869:     my %returnhash;
 7870:     if ($rep =~ /^(con_lost|error|no_such_host)/i) {
 7871:         return %returnhash;
 7872:     }
 7873:     foreach my $item (split(/\&/,$rep)) {
 7874: 	my ($key,$value)=split(/=/,$item);
 7875: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
 7876:     }
 7877:     return %returnhash;
 7878: }
 7879: 
 7880: # ------------------------------------------------------------ tmpdel interface
 7881: sub tmpdel {
 7882:     my ($token,$server)=@_;
 7883:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 7884:     return &reply("tmpdel:$token",$server);
 7885: }
 7886: 
 7887: # ------------------------------------------------------------ get_timebased_id 
 7888: 
 7889: sub get_timebased_id {
 7890:     my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
 7891:         $maxtries) = @_;
 7892:     my ($newid,$error,$dellock);
 7893:     unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {  
 7894:         return ('','ok','invalid call to get suffix');
 7895:     }
 7896: 
 7897: # set defaults for any optional args for which values were not supplied
 7898:     if ($who eq '') {
 7899:         $who = $env{'user.name'}.':'.$env{'user.domain'};
 7900:     }
 7901:     if (!$locktries) {
 7902:         $locktries = 3;
 7903:     }
 7904:     if (!$maxtries) {
 7905:         $maxtries = 10;
 7906:     }
 7907:     
 7908:     if (($cdom eq '') || ($cnum eq '')) {
 7909:         if ($env{'request.course.id'}) {
 7910:             $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 7911:             $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 7912:         }
 7913:         if (($cdom eq '') || ($cnum eq '')) {
 7914:             return ('','ok','call to get suffix not in course context');
 7915:         }
 7916:     }
 7917: 
 7918: # construct locking item
 7919:     my $lockhash = {
 7920:                       $prefix."\0".'locked_'.$keyid => $who,
 7921:                    };
 7922:     my $tries = 0;
 7923: 
 7924: # attempt to get lock on nohist_$namespace file
 7925:     my $gotlock = &newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
 7926:     while (($gotlock ne 'ok') && $tries <$locktries) {
 7927:         $tries ++;
 7928:         sleep 1;
 7929:         $gotlock = &newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
 7930:     }
 7931: 
 7932: # attempt to get unique identifier, based on current timestamp
 7933:     if ($gotlock eq 'ok') {
 7934:         my %inuse = &dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
 7935:         my $id = time;
 7936:         $newid = $id;
 7937:         if ($idtype eq 'addcode') {
 7938:             $newid .= &sixnum_code();
 7939:         }
 7940:         my $idtries = 0;
 7941:         while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
 7942:             if ($idtype eq 'concat') {
 7943:                 $newid = $id.$idtries;
 7944:             } elsif ($idtype eq 'addcode') {
 7945:                 $newid = $newid.&sixnum_code();
 7946:             } else {
 7947:                 $newid ++;
 7948:             }
 7949:             $idtries ++;
 7950:         }
 7951:         if (!exists($inuse{$prefix."\0".$newid})) {
 7952:             my %new_item =  (
 7953:                               $prefix."\0".$newid => $who,
 7954:                             );
 7955:             my $putresult = &put('nohist_'.$namespace,\%new_item,
 7956:                                                  $cdom,$cnum);
 7957:             if ($putresult ne 'ok') {
 7958:                 undef($newid);
 7959:                 $error = 'error saving new item: '.$putresult;
 7960:             }
 7961:         } else {
 7962:              undef($newid);
 7963:              $error = ('error: no unique suffix available for the new item ');
 7964:         }
 7965: #  remove lock
 7966:         my @del_lock = ($prefix."\0".'locked_'.$keyid);
 7967:         $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
 7968:     } else {
 7969:         $error = "error: could not obtain lockfile\n";
 7970:         $dellock = 'ok';
 7971:         if (($prefix eq 'paste') && ($namespace eq 'courseeditor') && ($keyid eq 'num')) {
 7972:             $dellock = 'nolock';
 7973:         }
 7974:     }
 7975:     return ($newid,$dellock,$error);
 7976: }
 7977: 
 7978: sub sixnum_code {
 7979:     my $code;
 7980:     for (0..6) {
 7981:         $code .= int( rand(9) );
 7982:     }
 7983:     return $code;
 7984: }
 7985: 
 7986: # -------------------------------------------------- portfolio access checking
 7987: 
 7988: sub portfolio_access {
 7989:     my ($requrl,$clientip) = @_;
 7990:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
 7991:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group,$clientip);
 7992:     if ($result) {
 7993:         my %setters;
 7994:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 7995:             my ($startblock,$endblock,$triggerblock,$by_ip,$blockdom) =
 7996:                 &Apache::loncommon::blockcheck(\%setters,'port',$clientip,$unum,$udom);
 7997:             if (($startblock && $endblock) || ($by_ip)) {
 7998:                 return 'B';
 7999:             }
 8000:         } else {
 8001:             my ($startblock,$endblock,$triggerblock,$by_ip,$blockdom) =
 8002:                 &Apache::loncommon::blockcheck(\%setters,'port',$clientip);
 8003:             if (($startblock && $endblock) || ($by_ip)) {
 8004:                 return 'B';
 8005:             }
 8006:         }
 8007:     }
 8008:     if ($result eq 'ok') {
 8009:        return 'F';
 8010:     } elsif ($result =~ /^[^:]+:guest_/) {
 8011:        return 'A';
 8012:     }
 8013:     return '';
 8014: }
 8015: 
 8016: sub get_portfolio_access {
 8017:     my ($udom,$unum,$file_name,$group,$clientip,$access_hash,$portaccessref) = @_;
 8018: 
 8019:     if (!ref($access_hash)) {
 8020: 	my $current_perms = &get_portfile_permissions($udom,$unum);
 8021: 	my %access_controls = &get_access_controls($current_perms,$group,
 8022: 						   $file_name);
 8023: 	$access_hash = $access_controls{$file_name};
 8024:     }
 8025: 
 8026:     my $portaccess;
 8027:     if (ref($portaccess) eq 'SCALAR') {
 8028:         $portaccess = $$portaccessref;
 8029:     } else {
 8030:         $portaccess = &usertools_access($unum,$udom,'portaccess',undef,'tools');
 8031:     }
 8032: 
 8033:     my ($public,$guest,@domains,@users,@courses,@groups,@ips,@userips);
 8034:     my $now = time;
 8035:     if (ref($access_hash) eq 'HASH') {
 8036:         foreach my $key (keys(%{$access_hash})) {
 8037:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
 8038:             next if (($scope ne 'ip') && ($portaccess == 0));
 8039:             if ($start > $now) {
 8040:                 next;
 8041:             }
 8042:             if ($end && $end<$now) {
 8043:                 next;
 8044:             }
 8045:             if ($scope eq 'public') {
 8046:                 $public = $key;
 8047:                 last;
 8048:             } elsif ($scope eq 'guest') {
 8049:                 $guest = $key;
 8050:             } elsif ($scope eq 'domains') {
 8051:                 push(@domains,$key);
 8052:             } elsif ($scope eq 'users') {
 8053:                 push(@users,$key);
 8054:             } elsif ($scope eq 'course') {
 8055:                 push(@courses,$key);
 8056:             } elsif ($scope eq 'group') {
 8057:                 push(@groups,$key);
 8058:             } elsif ($scope eq 'ip') {
 8059:                 push(@ips,$key);
 8060:             } elsif ($scope eq 'userip') {
 8061:                 push(@userips,$key);
 8062:             }
 8063:         }
 8064:         if ($public) {
 8065:             return 'ok';
 8066:         } elsif (@ips > 0) {
 8067:             my $allowed;
 8068:             foreach my $ipkey (@ips) {
 8069:                 if (ref($access_hash->{$ipkey}{'ip'}) eq 'ARRAY') {
 8070:                     if (&Apache::loncommon::check_ip_acc(join(',',@{$access_hash->{$ipkey}{'ip'}}),$clientip)) {
 8071:                         $allowed = 1;
 8072:                         last; 
 8073:                     }
 8074:                 }
 8075:             }
 8076:             if ($allowed) {
 8077:                 return 'ok';
 8078:             }
 8079:         } elsif (@userips > 0) {
 8080:             my $allowed;
 8081:             foreach my $useripkey (@userips) {
 8082:                 if (ref($access_hash->{$useripkey}{'ip'}) eq 'ARRAY') {
 8083:                     if (&Apache::loncommon::check_ip_acc(join(',',@{$access_hash->{$useripkey}{'ip'}}),$clientip)) {
 8084:                         $allowed = 1;
 8085:                         last;
 8086:                     }
 8087:                 }
 8088:             }
 8089:             if ($allowed) {
 8090:                 return 'ok';
 8091:             }
 8092:         }
 8093:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 8094:             if ($guest) {
 8095:                 return $guest;
 8096:             }
 8097:         } else {
 8098:             if (@domains > 0) {
 8099:                 foreach my $domkey (@domains) {
 8100:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
 8101:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
 8102:                             return 'ok';
 8103:                         }
 8104:                     }
 8105:                 }
 8106:             }
 8107:             if (@users > 0) {
 8108:                 foreach my $userkey (@users) {
 8109:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
 8110:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
 8111:                             if (ref($item) eq 'HASH') {
 8112:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
 8113:                                     ($item->{'udom'} eq $env{'user.domain'})) {
 8114:                                     return 'ok';
 8115:                                 }
 8116:                             }
 8117:                         }
 8118:                     } 
 8119:                 }
 8120:             }
 8121:             my %roleshash;
 8122:             my @courses_and_groups = @courses;
 8123:             push(@courses_and_groups,@groups); 
 8124:             if (@courses_and_groups > 0) {
 8125:                 my (%allgroups,%allroles); 
 8126:                 my ($start,$end,$role,$sec,$group);
 8127:                 foreach my $envkey (%env) {
 8128:                     if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
 8129:                         my $cid = $2.'_'.$3; 
 8130:                         if ($1 eq 'gr') {
 8131:                             $group = $4;
 8132:                             $allgroups{$cid}{$group} = $env{$envkey};
 8133:                         } else {
 8134:                             if ($4 eq '') {
 8135:                                 $sec = 'none';
 8136:                             } else {
 8137:                                 $sec = $4;
 8138:                             }
 8139:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
 8140:                         }
 8141:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
 8142:                         my $cid = $2.'_'.$3;
 8143:                         if ($4 eq '') {
 8144:                             $sec = 'none';
 8145:                         } else {
 8146:                             $sec = $4;
 8147:                         }
 8148:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
 8149:                     }
 8150:                 }
 8151:                 if (keys(%allroles) == 0) {
 8152:                     return;
 8153:                 }
 8154:                 foreach my $key (@courses_and_groups) {
 8155:                     my %content = %{$$access_hash{$key}};
 8156:                     my $cnum = $content{'number'};
 8157:                     my $cdom = $content{'domain'};
 8158:                     my $cid = $cdom.'_'.$cnum;
 8159:                     if (!exists($allroles{$cid})) {
 8160:                         next;
 8161:                     }    
 8162:                     foreach my $role_id (keys(%{$content{'roles'}})) {
 8163:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
 8164:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
 8165:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
 8166:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
 8167:                         foreach my $role (keys(%{$allroles{$cid}})) {
 8168:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
 8169:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
 8170:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
 8171:                                         if (grep/^all$/,@sections) {
 8172:                                             return 'ok';
 8173:                                         } else {
 8174:                                             if (grep/^$sec$/,@sections) {
 8175:                                                 return 'ok';
 8176:                                             }
 8177:                                         }
 8178:                                     }
 8179:                                 }
 8180:                                 if (keys(%{$allgroups{$cid}}) == 0) {
 8181:                                     if (grep/^none$/,@groups) {
 8182:                                         return 'ok';
 8183:                                     }
 8184:                                 } else {
 8185:                                     if (grep/^all$/,@groups) {
 8186:                                         return 'ok';
 8187:                                     } 
 8188:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
 8189:                                         if (grep/^$group$/,@groups) {
 8190:                                             return 'ok';
 8191:                                         }
 8192:                                     }
 8193:                                 } 
 8194:                             }
 8195:                         }
 8196:                     }
 8197:                 }
 8198:             }
 8199:             if ($guest) {
 8200:                 return $guest;
 8201:             }
 8202:         }
 8203:     }
 8204:     return;
 8205: }
 8206: 
 8207: sub course_group_datechecker {
 8208:     my ($dates,$now,$status) = @_;
 8209:     my ($start,$end) = split(/\./,$dates);
 8210:     if (!$start && !$end) {
 8211:         return 'ok';
 8212:     }
 8213:     if (grep/^active$/,@{$status}) {
 8214:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
 8215:             return 'ok';
 8216:         }
 8217:     }
 8218:     if (grep/^previous$/,@{$status}) {
 8219:         if ($end > $now ) {
 8220:             return 'ok';
 8221:         }
 8222:     }
 8223:     if (grep/^future$/,@{$status}) {
 8224:         if ($start > $now) {
 8225:             return 'ok';
 8226:         }
 8227:     }
 8228:     return; 
 8229: }
 8230: 
 8231: sub parse_portfolio_url {
 8232:     my ($url) = @_;
 8233: 
 8234:     my ($type,$udom,$unum,$group,$file_name);
 8235:     
 8236:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
 8237: 	$type = 1;
 8238:         $udom = $1;
 8239:         $unum = $2;
 8240:         $file_name = $3;
 8241:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
 8242: 	$type = 2;
 8243:         $udom = $1;
 8244:         $unum = $2;
 8245:         $group = $3;
 8246:         $file_name = $3.'/'.$4;
 8247:     }
 8248:     if (wantarray) {
 8249: 	return ($type,$udom,$unum,$file_name,$group);
 8250:     }
 8251:     return $type;
 8252: }
 8253: 
 8254: sub is_portfolio_url {
 8255:     my ($url) = @_;
 8256:     return scalar(&parse_portfolio_url($url));
 8257: }
 8258: 
 8259: sub is_portfolio_file {
 8260:     my ($file) = @_;
 8261:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
 8262:         return 1;
 8263:     }
 8264:     return;
 8265: }
 8266: 
 8267: sub is_coursetool_logo {
 8268:     my ($uri) = @_;
 8269:     if ($env{'request.course.id'}) {
 8270:         my $courseurl = &courseid_to_courseurl($env{'request.course.id'});
 8271:         if ($uri =~ m{^/*uploaded\Q$courseurl\E/toollogo/\d+/[^/]+$}) {
 8272:             return 1;
 8273:         }
 8274:     }
 8275:     return;
 8276: }
 8277: 
 8278: sub usertools_access {
 8279:     my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
 8280:     my ($access,%tools);
 8281:     if ($context eq '') {
 8282:         $context = 'tools';
 8283:     }
 8284:     if ($context eq 'requestcourses') {
 8285:         %tools = (
 8286:                       official   => 1,
 8287:                       unofficial => 1,
 8288:                       community  => 1,
 8289:                       textbook   => 1,
 8290:                       placement  => 1,
 8291:                       lti        => 1,
 8292:                  );
 8293:     } elsif ($context eq 'requestauthor') {
 8294:         %tools = (
 8295:                       requestauthor => 1,
 8296:                  );
 8297:     } elsif ($context eq 'authordefaults') {
 8298:         %tools = (
 8299:                       webdav    => 1,
 8300:                  );
 8301:     } else {
 8302:         %tools = (
 8303:                       aboutme   => 1,
 8304:                       blog      => 1,
 8305:                       portfolio => 1,
 8306:                       portaccess => 1,
 8307:                       timezone  => 1,
 8308:                  );
 8309:     }
 8310:     return if (!defined($tools{$tool}));
 8311: 
 8312:     if (($udom eq '') || ($uname eq '')) {
 8313:         $udom = $env{'user.domain'};
 8314:         $uname = $env{'user.name'};
 8315:     }
 8316: 
 8317:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 8318:         if ($action ne 'reload') {
 8319:             if ($context eq 'requestcourses') {
 8320:                 return $env{'environment.canrequest.'.$tool};
 8321:             } elsif ($context eq 'requestauthor') {
 8322:                 return $env{'environment.canrequest.author'};
 8323:             } elsif ($context eq 'authordefaults') {
 8324:                 if ($tool eq 'webdav') {
 8325:                     return $env{'environment.availabletools.'.$tool};
 8326:                 }
 8327:             } else {
 8328:                 return $env{'environment.availabletools.'.$tool};
 8329:             }
 8330:         }
 8331:     }
 8332: 
 8333:     my ($toolstatus,$inststatus,$envkey);
 8334:     if ($context eq 'requestauthor') {
 8335:         $envkey = $context;
 8336:     } elsif ($context eq 'authordefaults') {
 8337:         if ($tool eq 'webdav') {
 8338:             $envkey = 'tools.'.$tool;
 8339:         }
 8340:     } else {
 8341:         $envkey = $context.'.'.$tool;
 8342:     }
 8343: 
 8344:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
 8345:          ($action ne 'reload')) {
 8346:         $toolstatus = $env{'environment.'.$envkey};
 8347:         $inststatus = $env{'environment.inststatus'};
 8348:     } else {
 8349:         if (ref($userenvref) eq 'HASH') {
 8350:             $toolstatus = $userenvref->{$envkey};
 8351:             $inststatus = $userenvref->{'inststatus'};
 8352:         } else {
 8353:             my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
 8354:             $toolstatus = $userenv{$envkey};
 8355:             $inststatus = $userenv{'inststatus'};
 8356:         }
 8357:     }
 8358: 
 8359:     if ($toolstatus ne '') {
 8360:         if ($toolstatus) {
 8361:             $access = 1;
 8362:         } else {
 8363:             $access = 0;
 8364:         }
 8365:         return $access;
 8366:     }
 8367: 
 8368:     my ($is_adv,%domdef);
 8369:     if (ref($is_advref) eq 'HASH') {
 8370:         $is_adv = $is_advref->{'is_adv'};
 8371:     } else {
 8372:         $is_adv = &is_advanced_user($udom,$uname);
 8373:     }
 8374:     if (ref($domdefref) eq 'HASH') {
 8375:         %domdef = %{$domdefref};
 8376:     } else {
 8377:         %domdef = &get_domain_defaults($udom);
 8378:     }
 8379:     if (ref($domdef{$tool}) eq 'HASH') {
 8380:         if ($is_adv) {
 8381:             if ($domdef{$tool}{'_LC_adv'} ne '') {
 8382:                 if ($domdef{$tool}{'_LC_adv'}) { 
 8383:                     $access = 1;
 8384:                 } else {
 8385:                     $access = 0;
 8386:                 }
 8387:                 return $access;
 8388:             }
 8389:         }
 8390:         if ($inststatus ne '') {
 8391:             my ($hasaccess,$hasnoaccess);
 8392:             foreach my $affiliation (split(/:/,$inststatus)) {
 8393:                 if ($domdef{$tool}{$affiliation} ne '') { 
 8394:                     if ($domdef{$tool}{$affiliation}) {
 8395:                         $hasaccess = 1;
 8396:                     } else {
 8397:                         $hasnoaccess = 1;
 8398:                     }
 8399:                 }
 8400:             }
 8401:             if ($hasaccess || $hasnoaccess) {
 8402:                 if ($hasaccess) {
 8403:                     $access = 1;
 8404:                 } elsif ($hasnoaccess) {
 8405:                     $access = 0; 
 8406:                 }
 8407:                 return $access;
 8408:             }
 8409:         } else {
 8410:             if ($domdef{$tool}{'default'} ne '') {
 8411:                 if ($domdef{$tool}{'default'}) {
 8412:                     $access = 1;
 8413:                 } elsif ($domdef{$tool}{'default'} == 0) {
 8414:                     $access = 0;
 8415:                 }
 8416:                 return $access;
 8417:             }
 8418:         }
 8419:     } else {
 8420:         if (($context eq 'tools') && ($tool ne 'webdav')) {
 8421:             $access = 1;
 8422:         } else {
 8423:             $access = 0;
 8424:         }
 8425:         return $access;
 8426:     }
 8427: }
 8428: 
 8429: sub is_course_owner {
 8430:     my ($cdom,$cnum,$udom,$uname) = @_;
 8431:     if (($udom eq '') || ($uname eq '')) {
 8432:         $udom = $env{'user.domain'};
 8433:         $uname = $env{'user.name'};
 8434:     }
 8435:     unless (($udom eq '') || ($uname eq '')) {
 8436:         if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
 8437:             if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
 8438:                 return 1;
 8439:             } else {
 8440:                 my %courseinfo = &coursedescription($cdom.'/'.$cnum);
 8441:                 if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
 8442:                     return 1;
 8443:                 }
 8444:             }
 8445:         }
 8446:     }
 8447:     return;
 8448: }
 8449: 
 8450: sub is_advanced_user {
 8451:     my ($udom,$uname,$nocache) = @_;
 8452:     my ($is_adv,$is_author,$use_cache,$hashid);
 8453:     if ($udom ne '' && $uname ne '') {
 8454:         if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 8455:             if (wantarray) {
 8456:                 return ($env{'user.adv'},$env{'user.author'});
 8457:             } else {
 8458:                 return $env{'user.adv'};
 8459:             }
 8460:         } elsif (!$nocache) {
 8461:             $use_cache = 1;
 8462:             $hashid = "$udom:$uname";  
 8463:             my ($info,$cached)=&is_cached_new('isadvau',$hashid);
 8464:             if ($cached) {
 8465:                 ($is_adv,$is_author) = split(/:/,$info);
 8466:                 if (wantarray) {
 8467:                     return ($is_adv,$is_author);
 8468:                 }
 8469:                 return $is_adv; 
 8470:             }
 8471:         }
 8472:     }
 8473:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
 8474:     my %allroles;
 8475:     foreach my $role (keys(%roleshash)) {
 8476:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
 8477:         my $area = '/'.$tdomain.'/'.$trest;
 8478:         if ($sec ne '') {
 8479:             $area .= '/'.$sec;
 8480:         }
 8481:         if (($area ne '') && ($trole ne '')) {
 8482:             my $spec=$trole.'.'.$area;
 8483:             if ($trole =~ /^cr\//) {
 8484:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
 8485:             } elsif ($trole ne 'gr') {
 8486:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
 8487:             }
 8488:             if ($trole eq 'au') {
 8489:                 $is_author = 1;
 8490:             }
 8491:         }
 8492:     }
 8493:     foreach my $role (keys(%allroles)) {
 8494:         last if ($is_adv);
 8495:         foreach my $item (split(/:/,$allroles{$role})) {
 8496:             if ($item ne '') {
 8497:                 my ($privilege,$restrictions)=split(/&/,$item);
 8498:                 if ($privilege eq 'adv') {
 8499:                     $is_adv = 1;
 8500:                     last;
 8501:                 }
 8502:             }
 8503:         }
 8504:     }
 8505:     if ($use_cache) {
 8506:         my $cachetime = 600;
 8507:         &do_cache_new('isadvau',$hashid,$is_adv.':'.$is_author,$cachetime);
 8508:     }
 8509:     if (wantarray) {
 8510:         return ($is_adv,$is_author);
 8511:     }
 8512:     return $is_adv;
 8513: }
 8514: 
 8515: sub check_can_request {
 8516:     my ($dom,$can_request,$request_domains,$uname,$udom) = @_;
 8517:     my $canreq = 0;
 8518:     if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
 8519:         $uname = $env{'user.name'};
 8520:         $udom = $env{'user.domain'};
 8521:     }
 8522:     my ($types,$typename) = &Apache::loncommon::course_types();
 8523:     my @options = ('approval','validate','autolimit');
 8524:     my $optregex = join('|',@options);
 8525:     if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
 8526:         my %willtrust;
 8527:         foreach my $type (@{$types}) {
 8528:             if (&usertools_access($uname,$udom,$type,undef,
 8529:                                   'requestcourses')) {
 8530:                 $canreq ++;
 8531:                 if (ref($request_domains) eq 'HASH') {
 8532:                     push(@{$request_domains->{$type}},$udom);
 8533:                 }
 8534:                 if ($dom eq $udom) {
 8535:                     $can_request->{$type} = 1;
 8536:                 }
 8537:             }
 8538:             if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '') &&
 8539:                 ($env{'environment.reqcrsotherdom.'.$type} ne '')) {
 8540:                 my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
 8541:                 if (@curr > 0) {
 8542:                     foreach my $item (@curr) {
 8543:                         if (ref($request_domains) eq 'HASH') {
 8544:                             my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
 8545:                             if ($otherdom ne '') {
 8546:                                 unless (exists($willtrust{$otherdom})) {
 8547:                                     $willtrust{$otherdom} = &will_trust('reqcrs',$env{'user.domain'},$otherdom);
 8548:                                 }
 8549:                                 if ($willtrust{$otherdom}) {
 8550:                                     if (ref($request_domains->{$type}) eq 'ARRAY') {
 8551:                                         unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
 8552:                                             push(@{$request_domains->{$type}},$otherdom);
 8553:                                         }
 8554:                                     } else {
 8555:                                         push(@{$request_domains->{$type}},$otherdom);
 8556:                                     }
 8557:                                 }
 8558:                             }
 8559:                         }
 8560:                     }
 8561:                     unless ($dom eq $env{'user.domain'}) {
 8562:                         $canreq ++;
 8563:                         if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
 8564:                             $can_request->{$type} = 1;
 8565:                         }
 8566:                     }
 8567:                 }
 8568:             }
 8569:         }
 8570:     }
 8571:     return $canreq;
 8572: }
 8573: 
 8574: # ---------------------------------------------- Custom access rule evaluation
 8575: 
 8576: sub customaccess {
 8577:     my ($priv,$uri)=@_;
 8578:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
 8579:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
 8580:     $udom = &LONCAPA::clean_domain($udom);
 8581:     $ucrs = &LONCAPA::clean_username($ucrs);
 8582:     my $access=0;
 8583:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
 8584: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
 8585: 	if ($type eq 'user') {
 8586: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
 8587: 		my ($tdom,$tuname)=split(m{/},$scope);
 8588: 		if ($tdom) {
 8589: 		    if ($tdom ne $env{'user.domain'}) { next; }
 8590: 		}
 8591: 		if ($tuname) {
 8592: 		    if ($tuname ne $env{'user.name'}) { next; }
 8593: 		}
 8594: 		$access=($effect eq 'allow');
 8595: 		last;
 8596: 	    }
 8597: 	} else {
 8598: 	    if ($role) {
 8599: 		if ($role ne $urole) { next; }
 8600: 	    }
 8601: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
 8602: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
 8603: 		if ($tdom) {
 8604: 		    if ($tdom ne $udom) { next; }
 8605: 		}
 8606: 		if ($tcrs) {
 8607: 		    if ($tcrs ne $ucrs) { next; }
 8608: 		}
 8609: 		if ($tsec) {
 8610: 		    if ($tsec ne $usec) { next; }
 8611: 		}
 8612: 		$access=($effect eq 'allow');
 8613: 		last;
 8614: 	    }
 8615: 	    if ($realm eq '' && $role eq '') {
 8616: 		$access=($effect eq 'allow');
 8617: 	    }
 8618: 	}
 8619:     }
 8620:     return $access;
 8621: }
 8622: 
 8623: # ------------------------------------------------- Check for a user privilege
 8624: 
 8625: sub allowed {
 8626:     my ($priv,$uri,$symb,$role,$clientip,$noblockcheck,$ignorecache,$nodeeplinkcheck,$nodeeplinkout)=@_;
 8627:     my $ver_orguri=$uri;
 8628:     $uri=&deversion($uri);
 8629:     my $orguri=$uri;
 8630:     $uri=&declutter($uri);
 8631: 
 8632:     if ($priv eq 'evb') {
 8633: # Evade communication block restrictions for specified role in a course or domain
 8634:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
 8635:             return $1;
 8636:         } else {
 8637:             return;
 8638:         }
 8639:     }
 8640: 
 8641:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
 8642: # Free bre access to adm and meta resources
 8643:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard|viewclasslist|aboutme|ext\.tool)$})) 
 8644: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
 8645: 	&& ($priv eq 'bre')) {
 8646: 	return 'F';
 8647:     }
 8648: 
 8649: # Free bre access to user's own portfolio contents
 8650:     my ($space,$domain,$name,@dir)=split('/',$uri);
 8651:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
 8652: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
 8653:         my %setters;
 8654:         my ($startblock,$endblock,$triggerblock,$by_ip,$blockdom) = 
 8655:             &Apache::loncommon::blockcheck(\%setters,'port',$clientip);
 8656:         if (($startblock && $endblock) || ($by_ip)) {
 8657:             return 'B';
 8658:         } else {
 8659:             return 'F';
 8660:         }
 8661:     }
 8662: 
 8663: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
 8664:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
 8665:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
 8666:         if (exists($env{'request.course.id'})) {
 8667:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 8668:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 8669:             if (($domain eq $cdom) && ($name eq $cnum)) {
 8670:                 my $courseprivid=$env{'request.course.id'};
 8671:                 $courseprivid=~s/\_/\//;
 8672:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
 8673:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
 8674:                     return $1; 
 8675:                 } else {
 8676:                     if ($env{'request.course.sec'}) {
 8677:                         $courseprivid.='/'.$env{'request.course.sec'};
 8678:                     }
 8679:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
 8680:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
 8681:                         return $2;
 8682:                     }
 8683:                 }
 8684:             }
 8685:         }
 8686:     }
 8687: 
 8688: # Free bre to public access
 8689: 
 8690:     if ($priv eq 'bre') {
 8691:         my $copyright;
 8692:         unless ($uri =~ /ext\.tool/) {
 8693:             $copyright=&metadata($uri,'copyright');
 8694:         }
 8695: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
 8696:            return 'F'; 
 8697:         }
 8698:         if ($copyright eq 'priv') {
 8699:             $uri=~/([^\/]+)\/([^\/]+)\//;
 8700: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
 8701: 		return '';
 8702:             }
 8703:         }
 8704:         if ($copyright eq 'domain') {
 8705:             $uri=~/([^\/]+)\/([^\/]+)\//;
 8706: 	    unless (($env{'user.domain'} eq $1) ||
 8707:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
 8708: 		return '';
 8709:             }
 8710:         }
 8711:         if ($env{'request.role'}=~ /li\.\//) {
 8712:             # Library role, so allow browsing of resources in this domain.
 8713:             return 'F';
 8714:         }
 8715:         if ($copyright eq 'custom') {
 8716: 	    unless (&customaccess($priv,$uri)) { return ''; }
 8717:         }
 8718:     }
 8719:     # Domain coordinator is trying to create a course
 8720:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
 8721:         # uri is the requested domain in this case.
 8722:         # comparison to 'request.role.domain' shows if the user has selected
 8723:         # a role of dc for the domain in question.
 8724:         return 'F' if ($uri eq $env{'request.role.domain'});
 8725:     }
 8726: 
 8727:     my $thisallowed='';
 8728:     my $statecond=0;
 8729:     my $courseprivid='';
 8730: 
 8731:     my $ownaccess;
 8732:     # Community Coordinator or Assistant Co-author browsing resource space.
 8733:     if (($priv eq 'bro') && ($env{'user.author'})) {
 8734:         if ($uri eq '') {
 8735:             $ownaccess = 1;
 8736:         } else {
 8737:             if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
 8738:                 my $udom = $env{'user.domain'};
 8739:                 my $uname = $env{'user.name'};
 8740:                 if ($uri =~ m{^\Q$udom\E/?$}) {
 8741:                     $ownaccess = 1;
 8742:                 } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
 8743:                     unless ($uri =~ m{\.\./}) {
 8744:                         $ownaccess = 1;
 8745:                     }
 8746:                 } elsif (($udom ne 'public') && ($uname ne 'public')) {
 8747:                     my $now = time;
 8748:                     if ($uri =~ m{^([^/]+)/?$}) {
 8749:                         my $adom = $1;
 8750:                         foreach my $key (keys(%env)) {
 8751:                             if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
 8752:                                 my ($start,$end) = split(/\./,$env{$key});
 8753:                                 if (($now >= $start) && (!$end || $end > $now)) {
 8754:                                     $ownaccess = 1;
 8755:                                     last;
 8756:                                 }
 8757:                             }
 8758:                         }
 8759:                     } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
 8760:                         my $adom = $1;
 8761:                         my $aname = $2;
 8762:                         foreach my $role ('ca','aa') { 
 8763:                             if ($env{"user.role.$role./$adom/$aname"}) {
 8764:                                 my ($start,$end) =
 8765:                                     split(/\./,$env{"user.role.$role./$adom/$aname"});
 8766:                                 if (($now >= $start) && (!$end || $end > $now)) {
 8767:                                     $ownaccess = 1;
 8768:                                     last;
 8769:                                 }
 8770:                             }
 8771:                         }
 8772:                     }
 8773:                 }
 8774:             }
 8775:         }
 8776:     }
 8777: 
 8778: # Course
 8779: 
 8780:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
 8781:         unless (($priv eq 'bro') && (!$ownaccess)) {
 8782:             $thisallowed.=$1;
 8783:         }
 8784:     }
 8785: 
 8786: # Domain
 8787: 
 8788:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
 8789:        =~/\Q$priv\E\&([^\:]*)/) {
 8790:         unless (($priv eq 'bro') && (!$ownaccess)) {
 8791:             $thisallowed.=$1;
 8792:         }
 8793:     }
 8794: 
 8795: # User who is not author or co-author might still be able to edit
 8796: # resource of an author in the domain (e.g., if Domain Coordinator).
 8797:     if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
 8798:         (&allowed('mdc',$env{'request.course.id'}))) {
 8799:         if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
 8800:             $thisallowed.=$1;
 8801:         }
 8802:     }
 8803: 
 8804: # Course: uri itself is a course
 8805:     my $courseuri=$uri;
 8806:     $courseuri=~s/\_(\d)/\/$1/;
 8807:     $courseuri=~s/^([^\/])/\/$1/;
 8808: 
 8809:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
 8810:        =~/\Q$priv\E\&([^\:]*)/) {
 8811:         if ($priv eq 'mip') {
 8812:             my $rem = $1;
 8813:             if (($uri ne '') && ($env{'request.course.id'} eq $uri) &&
 8814:                 ($env{'course.'.$env{'request.course.id'}.'.internal.courseowner'} eq $env{'user.name'}.':'.$env{'user.domain'})) {
 8815:                 my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 8816:                 if ($cdom ne '') {
 8817:                     my %passwdconf = &get_passwdconf($cdom);
 8818:                     if (ref($passwdconf{'crsownerchg'}) eq 'HASH') {
 8819:                         if (ref($passwdconf{'crsownerchg'}{'by'}) eq 'ARRAY') {
 8820:                             if (@{$passwdconf{'crsownerchg'}{'by'}}) {
 8821:                                 my @inststatuses = split(':',$env{'environment.inststatus'});
 8822:                                 unless (@inststatuses) {
 8823:                                     @inststatuses = ('default');
 8824:                                 }
 8825:                                 foreach my $status (@inststatuses) {
 8826:                                     if (grep(/^\Q$status\E$/,@{$passwdconf{'crsownerchg'}{'by'}})) {
 8827:                                         $thisallowed.=$rem;
 8828:                                     }
 8829:                                 }
 8830:                             }
 8831:                         }
 8832:                     }
 8833:                 }
 8834:             }
 8835:         } else {
 8836:             unless (($priv eq 'bro') && (!$ownaccess)) {
 8837:                 $thisallowed.=$1;
 8838:             }
 8839:         }
 8840:     }
 8841: 
 8842: # URI is an uploaded document for this course, default permissions don't matter
 8843: # not allowing 'edit' access (editupload) to uploaded course docs
 8844:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
 8845: 	$thisallowed='';
 8846:         my ($match)=&is_on_map($uri);
 8847:         if ($match) {
 8848:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
 8849:                   =~/\Q$priv\E\&([^\:]*)/) {
 8850:                 my $value = $1;
 8851:                 my $deeplinkblock;
 8852:                 unless ($nodeeplinkcheck) {
 8853:                     $deeplinkblock = &deeplink_check($priv,$symb,$uri);
 8854:                 }
 8855:                 if ($deeplinkblock) {
 8856:                     $thisallowed='D';
 8857:                 } elsif ($noblockcheck) {
 8858:                     $thisallowed.=$value;
 8859:                 } else {
 8860:                     my @blockers = &has_comm_blocking($priv,$symb,$uri,$ignorecache);
 8861:                     if (@blockers > 0) {
 8862:                         $thisallowed = 'B';
 8863:                     } else {
 8864:                         $thisallowed.=$value;
 8865:                     }
 8866:                 }
 8867:             }
 8868:         } else {
 8869:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
 8870:             if ($refuri) {
 8871:                 if ($refuri =~ m|^/adm/|) {
 8872:                     $thisallowed='F';
 8873:                 } else {
 8874:                     $refuri=&declutter($refuri);
 8875:                     my ($match) = &is_on_map($refuri);
 8876:                     if ($match) {
 8877:                         my $deeplinkblock;
 8878:                         unless ($nodeeplinkcheck) {
 8879:                             $deeplinkblock = &deeplink_check($priv,$symb,$refuri);
 8880:                         }
 8881:                         if ($deeplinkblock) {
 8882:                             $thisallowed='D';
 8883:                         } elsif ($noblockcheck) {
 8884:                             $thisallowed='F';
 8885:                         } else {
 8886:                             my @blockers = &has_comm_blocking($priv,'',$refuri,'',1);
 8887:                             if (@blockers > 0) {
 8888:                                 $thisallowed = 'B';
 8889:                             } else {
 8890:                                 $thisallowed='F';
 8891:                             }
 8892:                         }
 8893:                     }
 8894:                 }
 8895:             }
 8896:         }
 8897:     }
 8898: 
 8899:     if ($priv eq 'bre'
 8900: 	&& $thisallowed ne 'F' 
 8901: 	&& $thisallowed ne '2'
 8902: 	&& &is_portfolio_url($uri)) {
 8903: 	$thisallowed = &portfolio_access($uri,$clientip);
 8904:     }
 8905: 
 8906: # Full access at system, domain or course-wide level? Exit.
 8907:     if ($thisallowed=~/F/) {
 8908: 	return 'F';
 8909:     }
 8910: 
 8911: # If this is generating or modifying users, exit with special codes
 8912: 
 8913:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:vca:vaa:'=~/\:\Q$priv\E\:/) {
 8914: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
 8915: 	    my ($audom,$auname)=split('/',$uri);
 8916: # no author name given, so this just checks on the general right to make a co-author in this domain
 8917: 	    unless ($auname) { return $thisallowed; }
 8918: # an author name is given, so we are about to actually make a co-author for a certain account
 8919: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
 8920: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
 8921: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
 8922: 	} elsif (($priv eq 'vca') || ($priv eq 'vaa')) {
 8923:             my ($audom,$auname)=split('/',$uri);
 8924:             unless ($auname) { return $thisallowed; }
 8925:             unless (($env{'request.role'} eq "dc./$audom") ||
 8926:                     ($env{'request.role'} eq "ca./$uri")) {
 8927:                 return '';
 8928:             }
 8929: 	}
 8930: 	return $thisallowed;
 8931:     }
 8932: #
 8933: # Gathered so far: system, domain and course wide privileges
 8934: #
 8935: # Course: See if uri or referer is an individual resource that is part of 
 8936: # the course
 8937: 
 8938:     if ($env{'request.course.id'}) {
 8939: 
 8940:         if ($priv eq 'bre') {
 8941:             if (&is_coursetool_logo($uri)) {
 8942:                 return 'F';
 8943:             }
 8944:         }
 8945: 
 8946: # If this is modifying password (internal auth) domains must match for user and user's role.
 8947: 
 8948:         if ($priv eq 'mip') {
 8949:             if ($env{'user.domain'} eq $env{'request.role.domain'}) {
 8950:                 return $thisallowed;
 8951:             } else {
 8952:                 return '';
 8953:             }
 8954:         }
 8955: 
 8956:        $courseprivid=$env{'request.course.id'};
 8957:        if ($env{'request.course.sec'}) {
 8958:           $courseprivid.='/'.$env{'request.course.sec'};
 8959:        }
 8960:        $courseprivid=~s/\_/\//;
 8961:        my $checkreferer=1;
 8962:        my ($match,$cond)=&is_on_map($uri);
 8963:        if ($match) {
 8964:            $statecond=$cond;
 8965:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 8966:                =~/\Q$priv\E\&([^\:]*)/) {
 8967:                my $value = $1;
 8968:                if ($priv eq 'bre') {
 8969:                    my $deeplinkblock;
 8970:                    unless ($nodeeplinkcheck) {
 8971:                        $deeplinkblock = &deeplink_check($priv,$symb,$uri);
 8972:                    }
 8973:                    if ($deeplinkblock) {
 8974:                        $thisallowed = 'D';
 8975:                    } elsif ($noblockcheck) {
 8976:                        $thisallowed.=$value;
 8977:                    } else {
 8978:                        my @blockers = &has_comm_blocking($priv,$symb,$uri,$ignorecache);
 8979:                        if (@blockers > 0) {
 8980:                            $thisallowed = 'B';
 8981:                        } else {
 8982:                            $thisallowed.=$value;
 8983:                        }
 8984:                    }
 8985:                } else {
 8986:                    $thisallowed.=$value;
 8987:                }
 8988:                $checkreferer=0;
 8989:            }
 8990:        }
 8991: 
 8992:        if ($checkreferer) {
 8993: 	  my $refuri=$env{'httpref.'.$orguri};
 8994:             unless ($refuri) {
 8995:                 foreach my $key (keys(%env)) {
 8996: 		    if ($key=~/^httpref\..*\*/) {
 8997: 			my $pattern=$key;
 8998:                         $pattern=~s/^httpref\.\/res\///;
 8999:                         $pattern=~s/\*/\[\^\/\]\+/g;
 9000:                         $pattern=~s/\//\\\//g;
 9001:                         if ($orguri=~/$pattern/) {
 9002: 			    $refuri=$env{$key};
 9003:                         }
 9004:                     }
 9005:                 }
 9006:             }
 9007: 
 9008:          if ($refuri) { 
 9009: 	  $refuri=&declutter($refuri);
 9010:           my ($match,$cond)=&is_on_map($refuri);
 9011:             if ($match) {
 9012:               my $refstatecond=$cond;
 9013:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 9014:                   =~/\Q$priv\E\&([^\:]*)/) {
 9015:                   my $value = $1;
 9016:                   if ($priv eq 'bre') {
 9017:                       my $deeplinkblock;
 9018:                       unless ($nodeeplinkcheck) {
 9019:                           $deeplinkblock = &deeplink_check($priv,$symb,$refuri);
 9020:                       }
 9021:                       if ($deeplinkblock) {
 9022:                           $thisallowed = 'D';
 9023:                       } elsif ($noblockcheck) {
 9024:                           $thisallowed.=$value;
 9025:                       } else {
 9026:                           my @blockers = &has_comm_blocking($priv,'',$refuri,'',1);
 9027:                           if (@blockers > 0) {
 9028:                               $thisallowed = 'B';
 9029:                           } else {
 9030:                               $thisallowed.=$value;
 9031:                           }
 9032:                       }
 9033:                   } else {
 9034:                       $thisallowed.=$value;
 9035:                   }
 9036:                   $uri=$refuri;
 9037:                   $statecond=$refstatecond;
 9038:               }
 9039:           }
 9040:         }
 9041:        }
 9042:    }
 9043: 
 9044: #
 9045: # Gathered now: all privileges that could apply, and condition number
 9046: # 
 9047: #
 9048: # Full or no access?
 9049: #
 9050: 
 9051:     if ($thisallowed=~/F/) {
 9052: 	return 'F';
 9053:     }
 9054: 
 9055:     unless ($thisallowed) {
 9056:         return '';
 9057:     }
 9058: 
 9059: # Restrictions exist, deal with them
 9060: #
 9061: #   C:according to course preferences
 9062: #   R:according to resource settings
 9063: #   L:unless locked
 9064: #   X:according to user session state
 9065: #
 9066: 
 9067: # Possibly locked functionality, check all courses
 9068: # In roles.tab, L (unless locked) available for bre, pch, plc, pac and sma.
 9069: # Locks might take effect only after 10 minutes cache expiration for other
 9070: # courses, and 2 minutes for current course, in which user has st or ta role
 9071: # which is neither expired nor a future role (unless current course).
 9072: 
 9073:     my ($needlockcheck,$now,$crsonly);
 9074:     if ($thisallowed=~/L/) {
 9075:         $now = time;
 9076:         if ($priv eq 'bre') {
 9077:             if ($uri ne '') {
 9078:                 if ($orguri =~ m{^/+res/}) {
 9079:                     if ($uri =~ m{^lib/templates/}) {
 9080:                         if ($env{'request.course.id'}) {
 9081:                             $crsonly = 1;
 9082:                             $needlockcheck = 1;
 9083:                         }
 9084:                     } else {
 9085:                         $needlockcheck = 1;
 9086:                     }
 9087:                 } elsif ($env{'request.course.id'}) {
 9088:                     my ($crsdom,$crsnum) = split('_',$env{'request.course.id'});
 9089:                     if (($uri =~ m{^(adm|uploaded|public)/$crsdom/$crsnum/}) ||
 9090:                         ($uri =~ m{^adm/$match_domain/$match_username/\d+/(smppg|bulletinboard)$})) {
 9091:                         $crsonly = 1;
 9092:                     }
 9093:                     $needlockcheck = 1;
 9094:                 }
 9095:             }
 9096:         } elsif (($priv eq 'pch') || ($priv eq 'plc') || ($priv eq 'pac') || ($priv eq 'sma')) {
 9097:             $needlockcheck = 1;
 9098:         }
 9099:     }
 9100:     if ($needlockcheck) {
 9101:         foreach my $envkey (keys(%env)) {
 9102:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
 9103:                my $courseid=$2;
 9104:                my $roleid=$1.'.'.$2;
 9105:                $courseid=~s/^\///;
 9106:                unless ($env{'request.role'} eq $roleid) {
 9107:                    my ($start,$end) = split(/\./,$env{$envkey});
 9108:                    next unless (($now >= $start) && (!$end || $end > $now));
 9109:                }
 9110:                my $expiretime=600;
 9111:                if ($env{'request.role'} eq $roleid) {
 9112: 		  $expiretime=120;
 9113:                }
 9114: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
 9115:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
 9116:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
 9117: 		   &coursedescription($courseid,{'freshen_cache' => 1});
 9118:                }
 9119:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
 9120:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
 9121: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
 9122:                        &log($env{'user.domain'},$env{'user.name'},
 9123:                             $env{'user.home'},
 9124:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
 9125:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 9126:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 9127: 		       return '';
 9128:                    }
 9129:                }
 9130:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
 9131:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
 9132: 		   if ($env{$prefix.'priv.'.$priv.'.lock.expire'}>time) {
 9133:                        &log($env{'user.domain'},$env{'user.name'},
 9134:                             $env{'user.home'},
 9135:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
 9136:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 9137:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 9138: 		       return '';
 9139:                    }
 9140:                }
 9141: 	   }
 9142:        }
 9143:     }
 9144: 
 9145: #
 9146: # Rest of the restrictions depend on selected course
 9147: #
 9148: 
 9149:     unless ($env{'request.course.id'}) {
 9150: 	if ($thisallowed eq 'A') {
 9151: 	    return 'A';
 9152:         } elsif ($thisallowed eq 'B') {
 9153:             return 'B';
 9154: 	} else {
 9155: 	    return '1';
 9156: 	}
 9157:     }
 9158: 
 9159: #
 9160: # Now user is definitely in a course
 9161: #
 9162: 
 9163: 
 9164: # Course preferences
 9165: 
 9166:    if ($thisallowed=~/C/) {
 9167:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 9168:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
 9169:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
 9170: 	   =~/\Q$rolecode\E/) {
 9171: 	   if (($priv ne 'pch') && ($priv ne 'plc') && ($priv ne 'pac')) {
 9172: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 9173: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
 9174: 			$env{'request.course.id'});
 9175: 	   }
 9176:            return '';
 9177:        }
 9178: 
 9179:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
 9180: 	   =~/\Q$unamedom\E/) {
 9181: 	   if (($priv ne 'pch') && ($priv ne 'plc') && ($priv ne 'pac')) {
 9182: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
 9183: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
 9184: 			$env{'request.course.id'});
 9185: 	   }
 9186:            return '';
 9187:        }
 9188:    }
 9189: 
 9190: # Resource preferences
 9191: 
 9192:    if ($thisallowed=~/R/) {
 9193:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 9194:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
 9195: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
 9196: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 9197: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
 9198: 	   }
 9199: 	   return '';
 9200:        }
 9201:    }
 9202: 
 9203: # Restricted for deeplinked session?
 9204: 
 9205:     if ($env{'request.deeplink.login'}) {
 9206:         if ($env{'acc.deeplinkout'} && !$nodeeplinkout) {
 9207:             if (!$symb) { $symb=&symbread($uri,1); }
 9208:             if (($symb) && ($env{'acc.deeplinkout'}=~/\&\Q$symb\E\&/)) {
 9209:                 return '';
 9210:             }
 9211:         }
 9212:     }
 9213: 
 9214: # Restricted by state or randomout?
 9215: 
 9216:    if ($thisallowed=~/X/) {
 9217:       if ($env{'acc.randomout'}) {
 9218: 	 if (!$symb) { $symb=&symbread($uri,1); }
 9219:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
 9220:             return ''; 
 9221:          }
 9222:       }
 9223:       if (&condval($statecond)) {
 9224: 	 return '2';
 9225:       } else {
 9226:          return '';
 9227:       }
 9228:    }
 9229: 
 9230:     if ($thisallowed eq 'A') {
 9231: 	return 'A';
 9232:     } elsif ($thisallowed eq 'B') {
 9233:         return 'B';
 9234:     } elsif ($thisallowed eq 'D') {
 9235:         return 'D';
 9236:     }
 9237:    return 'F';
 9238: }
 9239: 
 9240: # ------------------------------------------- Check construction space access
 9241: 
 9242: sub constructaccess {
 9243:     my ($url,$setpriv)=@_;
 9244: 
 9245: # We do not allow editing of previous versions of files
 9246:     if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
 9247: 
 9248: # Get username and domain from URL
 9249:     my ($ownername,$ownerdomain,$ownerhome);
 9250: 
 9251:     ($ownerdomain,$ownername) =
 9252:         ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)(?:/daxepage|/daxeopen)?/priv/($match_domain)/($match_username)(?:/|$)});
 9253: 
 9254: # The URL does not really point to any authorspace, forget it
 9255:     unless (($ownername) && ($ownerdomain)) { return ''; }
 9256: 
 9257: # Now we need to see if the user has access to the authorspace of
 9258: # $ownername at $ownerdomain
 9259: 
 9260:     if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
 9261: # Real author for this?
 9262:        $ownerhome = $env{'user.home'};
 9263:        if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
 9264:           return ($ownername,$ownerdomain,$ownerhome);
 9265:        }
 9266:     } elsif (&is_course($ownerdomain,$ownername)) {
 9267: # Course Authoring Space?
 9268:         if ($env{'request.course.id'}) {
 9269:             if (($ownername eq $env{'course.'.$env{'request.course.id'}.'.num'}) &&
 9270:                 ($ownerdomain eq $env{'course.'.$env{'request.course.id'}.'.domain'})) {
 9271:                 if (&allowed('mdc',$env{'request.course.id'})) {
 9272:                     return if ($env{'course.'.$env{'request.course.id'}.'.internal.crsauthor'} eq '0');
 9273:                     unless ($env{'course.'.$env{'request.course.id'}.'.internal.crsauthor'}) {
 9274:                         my %domdefs = &get_domain_defaults($ownerdomain);
 9275:                         my $type = lc($env{'course.'.$env{'request.course.id'}.'.type'});
 9276:                         unless (($type eq 'community') || ($type eq 'placement')) {
 9277:                             $type = 'unofficial';
 9278:                             if ($env{'course.'.$env{'request.course.id'}.'internal.coursecode'} ne '') {
 9279:                                 $type = 'official';
 9280:                             } elsif ($env{'course.'.$env{'request.course.id'}.'internal.textbook'} ne '') {
 9281:                                 $type = 'textbook';
 9282:                             } else {
 9283:                                 $type = 'unofficial';
 9284:                             }
 9285:                         }
 9286:                         return if ($domdefs{$type.'crsauthor'} eq '0');
 9287:                     }
 9288:                     $ownerhome = $env{'course.'.$env{'request.course.id'}.'.home'};
 9289:                     return ($ownername,$ownerdomain,$ownerhome);
 9290:                 }
 9291:             }
 9292:         }
 9293:         return '';
 9294:     } else {
 9295: # Co-author for this?
 9296:         if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
 9297:             exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
 9298:             $ownerhome = &homeserver($ownername,$ownerdomain);
 9299:             return ($ownername,$ownerdomain,$ownerhome);
 9300:         }
 9301:     }
 9302: 
 9303: # We don't have any access right now. If we are not possibly going to do anything about this,
 9304: # we might as well leave
 9305:    unless ($setpriv) { return ''; }
 9306: 
 9307: # Backdoor access?
 9308:     my $allowed=&allowed('eco',$ownerdomain);
 9309: # Nope
 9310:     unless ($allowed) { return ''; }
 9311: # Looks like we may have access, but could be locked by the owner of the construction space
 9312:     if ($allowed eq 'U') {
 9313:         my %blocked=&get('environment',['domcoord.author'],
 9314:                          $ownerdomain,$ownername);
 9315: # Is blocked by owner
 9316:         if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
 9317:     }
 9318:     if (($allowed eq 'F') || ($allowed eq 'U')) {
 9319: # Grant temporary access
 9320:         my $then=$env{'user.login.time'};
 9321:         my $update=$env{'user.update.time'};
 9322:         if (!$update) { $update = $then; }
 9323:         my $refresh=$env{'user.refresh.time'};
 9324:         if (!$refresh) { $refresh = $update; }
 9325:         my $now = time;
 9326:         &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
 9327:                            $now,'ca','constructaccess');
 9328:         $ownerhome = &homeserver($ownername,$ownerdomain);
 9329:         return($ownername,$ownerdomain,$ownerhome);
 9330:     }
 9331: # No business here
 9332:     return '';
 9333: }
 9334: 
 9335: # ----------------------------------------------------------- Content Blocking
 9336: 
 9337: {
 9338: # Caches for faster Course Contents display where content blocking
 9339: # is in operation (i.e., interval param set) for timed quiz.
 9340: #
 9341: # User for whom data are being temporarily cached.
 9342: my $cacheduser='';
 9343: # Course for which data are being temporarily cached.
 9344: my $cachedcid='';
 9345: # Cached blockers for this user (a hash of blocking items). 
 9346: my %cachedblockers=();
 9347: # When the data were last cached.
 9348: my $cachedlast='';
 9349: 
 9350: sub load_all_blockers {
 9351:     my ($uname,$udom)=@_;
 9352:     if (($uname ne '') && ($udom ne '')) { 
 9353:         if (($cacheduser eq $uname.':'.$udom) &&
 9354:             ($cachedcid eq $env{'request.course.id'}) &&
 9355:             (abs($cachedlast-time)<5)) {
 9356:             return;
 9357:         }
 9358:     }
 9359:     $cachedlast=time;
 9360:     $cacheduser=$uname.':'.$udom;
 9361:     $cachedcid=$env{'request.course.id'};
 9362:     %cachedblockers = &get_commblock_resources();
 9363:     return;
 9364: }
 9365: 
 9366: sub get_comm_blocks {
 9367:     my ($cdom,$cnum) = @_;
 9368:     if ($cdom eq '' || $cnum eq '') {
 9369:         return unless ($env{'request.course.id'});
 9370:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 9371:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 9372:     }
 9373:     my %commblocks;
 9374:     my $hashid=$cdom.'_'.$cnum;
 9375:     my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
 9376:     if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
 9377:         %commblocks = %{$blocksref};
 9378:     } else {
 9379:         %commblocks = &dump('comm_block',$cdom,$cnum);
 9380:         my $cachetime = 600;
 9381:         &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
 9382:     }
 9383:     return %commblocks;
 9384: }
 9385: 
 9386: sub get_commblock_resources {
 9387:     my ($blocks) = @_;
 9388:     my %blockers = ();
 9389:     return %blockers unless ($env{'request.course.id'});
 9390:     my $courseurl = &courseid_to_courseurl($env{'request.course.id'});
 9391:     if ($env{'request.course.sec'}) {
 9392:         $courseurl .= '/'.$env{'request.course.sec'};
 9393:     }
 9394:     return %blockers if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseurl} =~/evb\&([^\:]*)/);
 9395:     my %commblocks;
 9396:     if (ref($blocks) eq 'HASH') {
 9397:         %commblocks = %{$blocks};
 9398:     } else {
 9399:         %commblocks = &get_comm_blocks();
 9400:     }
 9401:     return %blockers unless (keys(%commblocks) > 0); 
 9402:     my $navmap = Apache::lonnavmaps::navmap->new();
 9403:     return %blockers unless (ref($navmap));
 9404:     my $now = time;
 9405:     foreach my $block (keys(%commblocks)) {
 9406:         if ($block =~ /^(\d+)____(\d+)$/) {
 9407:             my ($start,$end) = ($1,$2);
 9408:             if ($start <= $now && $end >= $now) {
 9409:                 if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
 9410:                     if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
 9411:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
 9412:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
 9413:                                 $blockers{$block}{maps} = $commblocks{$block}{'blocks'}{'docs'}{'maps'}; 
 9414:                             }
 9415:                         }
 9416:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
 9417:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
 9418:                                 $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
 9419:                             }
 9420:                         }
 9421:                     }
 9422:                 }
 9423:             }
 9424:         } elsif ($block =~ /^firstaccess____(.+)$/) {
 9425:             my $item = $1;
 9426:             if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
 9427:                 if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
 9428:                     my (@interval,$mapname);
 9429:                     my $type = 'map';
 9430:                     if ($item eq 'course') {
 9431:                         $type = 'course';
 9432:                         @interval=&EXT("resource.0.interval");
 9433:                     } else {
 9434:                         if ($item =~ /___\d+___/) {
 9435:                             $type = 'resource';
 9436:                             @interval=&EXT("resource.0.interval",$item);
 9437:                         } else {
 9438:                             $mapname = &deversion($item);
 9439:                             if (ref($navmap)) {
 9440:                                 my $timelimit = $navmap->get_mapparam(undef,$mapname,'0.interval');
 9441:                                 @interval = ($timelimit,'map');
 9442:                             }
 9443:                         }
 9444:                     }
 9445:                     if ($interval[0] =~ /^(\d+)/) {
 9446:                         my $timelimit = $1; 
 9447:                         my $first_access;
 9448:                         if ($type eq 'resource') {
 9449:                             $first_access=&get_first_access($interval[1],$item);
 9450:                         } elsif ($type eq 'map') {
 9451:                             $first_access=&get_first_access($interval[1],undef,$item);
 9452:                         } else {
 9453:                             $first_access=&get_first_access($interval[1]);
 9454:                         }
 9455:                         if ($first_access) {
 9456:                             my $timesup = $first_access+$timelimit;
 9457:                             if ($timesup > $now) {
 9458:                                 my $activeblock;
 9459:                                 if ($type eq 'resource') {
 9460:                                     if (ref($navmap)) {
 9461:                                         my $res = $navmap->getBySymb($item);
 9462:                                         if ($res->answerable()) {
 9463:                                             $activeblock = 1;
 9464:                                         }
 9465:                                     }
 9466:                                 } elsif ($type eq 'map') {
 9467:                                     my $mapsymb = &symbread($mapname,1);
 9468:                                     if (($mapsymb) && (ref($navmap))) {
 9469:                                         my $mapres = $navmap->getBySymb($mapsymb);
 9470:                                         if (ref($mapres)) {
 9471:                                             my $first = $mapres->map_start();
 9472:                                             my $finish = $mapres->map_finish();
 9473:                                             my $it = $navmap->getIterator($first,$finish,undef,0,0);
 9474:                                             if (ref($it)) {
 9475:                                                 my $res;
 9476:                                                 while ($res = $it->next(undef,1)) {
 9477:                                                     next unless (ref($res));
 9478:                                                     my $symb = $res->symb();
 9479:                                                     next if (($symb eq $mapsymb) || ($symb eq ''));
 9480:                                                     @interval=&EXT("resource.0.interval",$symb);
 9481:                                                     if ($interval[1] eq 'map') {
 9482:                                                         if ($res->answerable()) {
 9483:                                                             $activeblock = 1;
 9484:                                                             last;
 9485:                                                         }
 9486:                                                     }
 9487:                                                 }
 9488:                                             }
 9489:                                         }
 9490:                                     }
 9491:                                 }
 9492:                                 if ($activeblock) {
 9493:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
 9494:                                          if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
 9495:                                              $blockers{$block}{'maps'} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
 9496:                                          }
 9497:                                     }
 9498:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
 9499:                                         if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
 9500:                                             $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
 9501:                                         }
 9502:                                     }
 9503:                                 }
 9504:                             }
 9505:                         }
 9506:                     }
 9507:                 }
 9508:             }
 9509:         }
 9510:     }
 9511:     return %blockers;
 9512: }
 9513: 
 9514: sub has_comm_blocking {
 9515:     my ($priv,$symb,$uri,$ignoresymbdb,$noenccheck,$blocked,$blocks) = @_;
 9516:     my @blockers;
 9517:     return unless ($env{'request.course.id'});
 9518:     return unless ($priv eq 'bre');
 9519:     return if ($env{'request.state'} eq 'construct');
 9520:     my $courseurl = &courseid_to_courseurl($env{'request.course.id'});
 9521:     if ($env{'request.course.sec'}) {
 9522:         $courseurl .= '/'.$env{'request.course.sec'};
 9523:     }
 9524:     return if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseurl} =~/evb\&([^\:]*)/);
 9525:     my %blockinfo;
 9526:     if (ref($blocks) eq 'HASH') {
 9527:         %blockinfo = &get_commblock_resources($blocks);
 9528:     } else {
 9529:         &load_all_blockers($env{'user.name'},$env{'user.domain'});
 9530:         %blockinfo = %cachedblockers;
 9531:     }
 9532:     return unless (keys(%blockinfo) > 0);
 9533:     my (%possibles,@symbs);
 9534:     if (!$symb) {
 9535:         $symb = &symbread($uri,1,1,1,\%possibles,$ignoresymbdb,$noenccheck);
 9536:     }
 9537:     if ($symb) {
 9538:         @symbs = ($symb);
 9539:     } elsif (keys(%possibles)) { 
 9540:         @symbs = keys(%possibles);
 9541:     }
 9542:     my $noblock;
 9543:     foreach my $symb (@symbs) {
 9544:         last if ($noblock);
 9545:         my ($map,$resid,$resurl)=&decode_symb($symb);
 9546:         foreach my $block (keys(%blockinfo)) {
 9547:             if ($block =~ /^firstaccess____(.+)$/) {
 9548:                 my $item = $1;
 9549:                 unless ($blocked) {
 9550:                     if (($item eq $map) || ($item eq $symb)) {
 9551:                         $noblock = 1;
 9552:                         last;
 9553:                     }
 9554:                 }
 9555:             }
 9556:             if (ref($blockinfo{$block}) eq 'HASH') {
 9557:                 if (ref($blockinfo{$block}{'resources'}) eq 'HASH') {
 9558:                     if ($blockinfo{$block}{'resources'}{$symb}) {
 9559:                         unless (grep(/^\Q$block\E$/,@blockers)) {
 9560:                             push(@blockers,$block);
 9561:                         }
 9562:                     }
 9563:                 }
 9564:                 if (ref($blockinfo{$block}{'maps'}) eq 'HASH') {
 9565:                     if ($blockinfo{$block}{'maps'}{$map}) {
 9566:                         unless (grep(/^\Q$block\E$/,@blockers)) {
 9567:                             push(@blockers,$block);
 9568:                         }
 9569:                     }
 9570:                 }
 9571:             }
 9572:         }
 9573:     }
 9574:     unless ($noblock) { 
 9575:         return @blockers;
 9576:     }
 9577:     return;
 9578: }
 9579: }
 9580: 
 9581: sub deeplink_check {
 9582:     my ($priv,$symb,$uri) = @_;
 9583:     return unless ($env{'request.course.id'});
 9584:     return unless ($priv eq 'bre');
 9585:     return if ($env{'request.state'} eq 'construct');
 9586:     return if ($env{'request.role.adv'});
 9587:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 9588:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 9589:     my (%possibles,@symbs);
 9590:     if (!$symb) {
 9591:         $symb = &symbread($uri,1,1,1,\%possibles);
 9592:     }
 9593:     if ($symb) {
 9594:         @symbs = ($symb);
 9595:     } elsif (keys(%possibles)) {
 9596:         @symbs = keys(%possibles);
 9597:     }
 9598: 
 9599:     my ($deeplink_symb,$allow);
 9600:     if ($env{'request.deeplink.login'}) {
 9601:         $deeplink_symb = &Apache::loncommon::deeplink_login_symb($cnum,$cdom);
 9602:     }
 9603:     foreach my $symb (@symbs) {
 9604:         last if ($allow);
 9605:         my $deeplink = &EXT("resource.0.deeplink",$symb);
 9606:         if ($deeplink eq '') {
 9607:             $allow = 1;
 9608:         } else {
 9609:             my ($state,$others,$listed,$scope,$protect) = split(/,/,$deeplink);
 9610:             if ($state ne 'only') {
 9611:                 $allow = 1;
 9612:             } else {
 9613:                 my $check_deeplink_entry;
 9614:                 if ($protect ne 'none') {
 9615:                     my ($acctype,$item) = split(/:/,$protect);
 9616:                     if (($acctype eq 'ltic') && ($env{'user.linkprotector'})) {
 9617:                         if (grep(/^\Q$item\Ec$/,split(/,/,$env{'user.linkprotector'}))) {
 9618:                             $check_deeplink_entry = 1
 9619:                         }
 9620:                     } elsif (($acctype eq 'ltid') && ($env{'user.linkprotector'})) {
 9621:                         if (grep(/^\Q$item\Ed$/,split(/,/,$env{'user.linkprotector'}))) {
 9622:                             $check_deeplink_entry = 1;
 9623:                         }
 9624:                     } elsif (($acctype eq 'key') && ($env{'user.deeplinkkey'})) {
 9625:                         if (grep(/^\Q$item\E$/,split(/,/,$env{'user.deeplinkkey'}))) {
 9626:                             $check_deeplink_entry = 1;
 9627:                         }
 9628:                     }
 9629:                 }
 9630:                 if (($protect eq 'none') || ($check_deeplink_entry)) {
 9631:                     if ($scope eq 'res') {
 9632:                         if ($symb eq $deeplink_symb) {
 9633:                             $allow = 1;
 9634:                         }
 9635:                     } elsif (($scope eq 'map') || ($scope eq 'rec')) {
 9636:                         my ($map_from_symb,$map_from_login);
 9637:                         $map_from_symb = &deversion((&decode_symb($symb))[0]);
 9638:                         if ($deeplink_symb =~ /\.(page|sequence)$/) {
 9639:                             $map_from_login = &deversion((&decode_symb($deeplink_symb))[2]);
 9640:                         } else {
 9641:                             $map_from_login = &deversion((&decode_symb($deeplink_symb))[0]);
 9642:                         }
 9643:                         if (($map_from_symb) && ($map_from_login)) {
 9644:                             if ($map_from_symb eq $map_from_login) {
 9645:                                 $allow = 1;
 9646:                             } elsif ($scope eq 'rec') {
 9647:                                 my @recurseup = &get_map_hierarchy($map_from_symb,$env{'request.course.id'});
 9648:                                 if (grep(/^\Q$map_from_login\E$/,@recurseup)) {
 9649:                                     $allow = 1;
 9650:                                 }
 9651:                             }
 9652:                         }
 9653:                     }
 9654:                 }
 9655:             }
 9656:         }
 9657:     }
 9658:     return if ($allow);
 9659:     return 1;
 9660: }
 9661: 
 9662: # -------------------------------- Deversion and split uri into path an filename   
 9663: 
 9664: #
 9665: #   Removes the version from a URI and
 9666: #   splits it in to its filename and path to the filename.
 9667: #   Seems like File::Basename could have done this more clearly.
 9668: #   Parameters:
 9669: #      $uri   - input URI
 9670: #   Returns:
 9671: #     Two element list consisting of 
 9672: #     $pathname  - the URI up to and excluding the trailing /
 9673: #     $filename  - The part of the URI following the last /
 9674: #  NOTE:
 9675: #    Another realization of this is simply:
 9676: #    use File::Basename;
 9677: #    ...
 9678: #    $uri = shift;
 9679: #    $filename = basename($uri);
 9680: #    $path     = dirname($uri);
 9681: #    return ($filename, $path);
 9682: #
 9683: #     The implementation below is probably faster however.
 9684: #
 9685: sub split_uri_for_cond {
 9686:     my $uri=&deversion(&declutter(shift));
 9687:     my @uriparts=split(/\//,$uri);
 9688:     my $filename=pop(@uriparts);
 9689:     my $pathname=join('/',@uriparts);
 9690:     return ($pathname,$filename);
 9691: }
 9692: # --------------------------------------------------- Is a resource on the map?
 9693: 
 9694: sub is_on_map {
 9695:     my ($pathname,$filename) = &split_uri_for_cond(shift);
 9696:     #Trying to find the conditional for the file
 9697:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
 9698: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
 9699:     if ($match) {
 9700: 	return (1,$1);
 9701:     } else {
 9702: 	return (0,0);
 9703:     }
 9704: }
 9705: 
 9706: # --------------------------------------------------------- Get symb from alias
 9707: 
 9708: sub get_symb_from_alias {
 9709:     my $symb=shift;
 9710:     my ($map,$resid,$url)=&decode_symb($symb);
 9711: # Already is a symb
 9712:     if ($url) { return $symb; }
 9713: # Must be an alias
 9714:     my $aliassymb='';
 9715:     my %bighash;
 9716:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 9717:                             &GDBM_READER(),0640)) {
 9718:         my $rid=$bighash{'mapalias_'.$symb};
 9719: 	if ($rid) {
 9720: 	    my ($mapid,$resid)=split(/\./,$rid);
 9721: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
 9722: 				    $resid,$bighash{'src_'.$rid});
 9723: 	}
 9724:         untie %bighash;
 9725:     }
 9726:     return $aliassymb;
 9727: }
 9728: 
 9729: # ----------------------------------------------------------------- Define Role
 9730: 
 9731: sub definerole {
 9732:   if (allowed('mcr','/')) {
 9733:     my ($rolename,$sysrole,$domrole,$courole,$uname,$udom)=@_;
 9734:     foreach my $role (split(':',$sysrole)) {
 9735: 	my ($crole,$cqual)=split(/\&/,$role);
 9736:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
 9737:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
 9738: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 9739:                return "refused:s:$crole&$cqual"; 
 9740:             }
 9741:         }
 9742:     }
 9743:     foreach my $role (split(':',$domrole)) {
 9744: 	my ($crole,$cqual)=split(/\&/,$role);
 9745:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
 9746:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
 9747: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
 9748:                return "refused:d:$crole&$cqual"; 
 9749:             }
 9750:         }
 9751:     }
 9752:     foreach my $role (split(':',$courole)) {
 9753: 	my ($crole,$cqual)=split(/\&/,$role);
 9754:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
 9755:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
 9756: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 9757:                return "refused:c:$crole&$cqual"; 
 9758:             }
 9759:         }
 9760:     }
 9761:     my $uhome;
 9762:     if (($uname ne '') && ($udom ne '')) {
 9763:         $uhome = &homeserver($uname,$udom);
 9764:         return $uhome if ($uhome eq 'no_host');
 9765:     } else {
 9766:         $uname = $env{'user.name'};
 9767:         $udom = $env{'user.domain'};
 9768:         $uhome = $env{'user.home'};
 9769:     }
 9770:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
 9771:                 "$udom:$uname:rolesdef_$rolename=".
 9772:                 escape($sysrole.'_'.$domrole.'_'.$courole);
 9773:     return reply($command,$uhome);
 9774:   } else {
 9775:     return 'refused';
 9776:   }
 9777: }
 9778: 
 9779: # ---------------- Make a metadata query against the network of library servers
 9780: 
 9781: sub metadata_query {
 9782:     my ($query,$custom,$customshow,$server_array,$domains_hash)=@_;
 9783:     my %rhash;
 9784:     my %libserv = &all_library();
 9785:     my @server_list = (defined($server_array) ? @$server_array
 9786:                                               : keys(%libserv) );
 9787:     for my $server (@server_list) {
 9788:         my $domains = ''; 
 9789:         if (ref($domains_hash) eq 'HASH') {
 9790:             $domains = $domains_hash->{$server}; 
 9791:         }
 9792: 	unless ($custom or $customshow) {
 9793: 	    my $reply=&reply("querysend:".&escape($query).':::'.&escape($domains),$server);
 9794: 	    $rhash{$server}=$reply;
 9795: 	}
 9796: 	else {
 9797: 	    my $reply=&reply("querysend:".&escape($query).':'.
 9798: 			     &escape($custom).':'.&escape($customshow).':'.&escape($domains),
 9799: 			     $server);
 9800: 	    $rhash{$server}=$reply;
 9801: 	}
 9802:     }
 9803:     return \%rhash;
 9804: }
 9805: 
 9806: # ----------------------------------------- Send log queries and wait for reply
 9807: 
 9808: sub log_query {
 9809:     my ($uname,$udom,$query,%filters)=@_;
 9810:     my $uhome=&homeserver($uname,$udom);
 9811:     if ($uhome eq 'no_host') { return 'error: no_host'; }
 9812:     my $uhost=&hostname($uhome);
 9813:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
 9814:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
 9815:                        $uhome);
 9816:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
 9817:     return get_query_reply($queryid);
 9818: }
 9819: 
 9820: # -------------------------- Update MySQL table for portfolio file
 9821: 
 9822: sub update_portfolio_table {
 9823:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
 9824:     if ($group ne '') {
 9825:         $file_name =~s /^\Q$group\E//;
 9826:     }
 9827:     my $homeserver = &homeserver($uname,$udom);
 9828:     my $queryid=
 9829:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
 9830:                ':'.&escape($file_name).':'.$action,$homeserver);
 9831:     my $reply = &get_query_reply($queryid);
 9832:     return $reply;
 9833: }
 9834: 
 9835: # -------------------------- Update MySQL allusers table
 9836: 
 9837: sub update_allusers_table {
 9838:     my ($uname,$udom,$names) = @_;
 9839:     my $homeserver = &homeserver($uname,$udom);
 9840:     my $queryid=
 9841:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
 9842:                'lastname='.&escape($names->{'lastname'}).'%%'.
 9843:                'firstname='.&escape($names->{'firstname'}).'%%'.
 9844:                'middlename='.&escape($names->{'middlename'}).'%%'.
 9845:                'generation='.&escape($names->{'generation'}).'%%'.
 9846:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
 9847:                'id='.&escape($names->{'id'}),$homeserver);
 9848:     return;
 9849: }
 9850: 
 9851: # ------- Request retrieval of institutional classlists for course(s)
 9852: 
 9853: sub fetch_enrollment_query {
 9854:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
 9855:     my ($homeserver,$sleep,$loopmax);
 9856:     my $maxtries = 1;
 9857:     if ($context eq 'automated') {
 9858:         $homeserver = $perlvar{'lonHostID'};
 9859:         $sleep = 2;
 9860:         $loopmax = 100;
 9861:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
 9862:     } else {
 9863:         $homeserver = &homeserver($cnum,$dom);
 9864:     }
 9865:     my $host=&hostname($homeserver);
 9866:     my $cmd = '';
 9867:     foreach my $affiliate (keys(%{$affiliatesref})) {
 9868:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
 9869:     }
 9870:     $cmd =~ s/%%$//;
 9871:     $cmd = &escape($cmd);
 9872:     my $query = 'fetchenrollment';
 9873:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
 9874:     unless ($queryid=~/^\Q$host\E\_/) { 
 9875:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
 9876:         return 'error: '.$queryid;
 9877:     }
 9878:     my $reply = &get_query_reply($queryid,$sleep,$loopmax);
 9879:     my $tries = 1;
 9880:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 9881:         $reply = &get_query_reply($queryid,$sleep,$loopmax);
 9882:         $tries ++;
 9883:     }
 9884:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 9885:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 9886:     } else {
 9887:         my @responses = split(/:/,$reply);
 9888:         if (grep { $_ eq $homeserver } &current_machine_ids()) {
 9889:             foreach my $line (@responses) {
 9890:                 my ($key,$value) = split(/=/,$line,2);
 9891:                 $$replyref{$key} = $value;
 9892:             }
 9893:         } else {
 9894:             my $pathname = LONCAPA::tempdir();
 9895:             foreach my $line (@responses) {
 9896:                 my ($key,$value) = split(/=/,$line);
 9897:                 $$replyref{$key} = $value;
 9898:                 if ($value > 0) {
 9899:                     foreach my $item (@{$$affiliatesref{$key}}) {
 9900:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
 9901:                         my $destname = $pathname.'/'.$filename;
 9902:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
 9903:                         if ($xml_classlist =~ /^error/) {
 9904:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
 9905:                         } else {
 9906:                             if ( open(FILE,">",$destname) ) {
 9907:                                 print FILE &unescape($xml_classlist);
 9908:                                 close(FILE);
 9909:                             } else {
 9910:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
 9911:                             }
 9912:                         }
 9913:                     }
 9914:                 }
 9915:             }
 9916:         }
 9917:         return 'ok';
 9918:     }
 9919:     return 'error';
 9920: }
 9921: 
 9922: sub get_query_reply {
 9923:     my ($queryid,$sleep,$loopmax) = @_;
 9924:     if (($sleep eq '') || ($sleep !~ /^\d+\.?\d*$/)) {
 9925:         $sleep = 0.2;
 9926:     }
 9927:     if (($loopmax eq '') || ($loopmax =~ /\D/)) {
 9928:         $loopmax = 100;
 9929:     }
 9930:     my $replyfile=LONCAPA::tempdir().$queryid;
 9931:     my $reply='';
 9932:     for (1..$loopmax) {
 9933: 	sleep($sleep);
 9934:         if (-e $replyfile.'.end') {
 9935: 	    if (open(my $fh,"<",$replyfile)) {
 9936: 		$reply = join('',<$fh>);
 9937: 		close($fh);
 9938: 	   } else { return 'error: reply_file_error'; }
 9939:            return &unescape($reply);
 9940: 	}
 9941:     }
 9942:     return 'timeout:'.$queryid;
 9943: }
 9944: 
 9945: sub courselog_query {
 9946: #
 9947: # possible filters:
 9948: # url: url or symb
 9949: # username
 9950: # domain
 9951: # action: view, submit, grade
 9952: # start: timestamp
 9953: # end: timestamp
 9954: #
 9955:     my (%filters)=@_;
 9956:     unless ($env{'request.course.id'}) { return 'no_course'; }
 9957:     if ($filters{'url'}) {
 9958: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
 9959:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
 9960:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
 9961:     }
 9962:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 9963:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 9964:     return &log_query($cname,$cdom,'courselog',%filters);
 9965: }
 9966: 
 9967: sub userlog_query {
 9968: #
 9969: # possible filters:
 9970: # action: log check role
 9971: # start: timestamp
 9972: # end: timestamp
 9973: #
 9974:     my ($uname,$udom,%filters)=@_;
 9975:     return &log_query($uname,$udom,'userlog',%filters);
 9976: }
 9977: 
 9978: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
 9979: 
 9980: sub auto_run {
 9981:     my ($cnum,$cdom) = @_;
 9982:     my $response = 0;
 9983:     my $settings;
 9984:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
 9985:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
 9986:         $settings = $domconfig{'autoenroll'};
 9987:         if ($settings->{'run'} eq '1') {
 9988:             $response = 1;
 9989:         }
 9990:     } else {
 9991:         my $homeserver;
 9992:         if (&is_course($cdom,$cnum)) {
 9993:             $homeserver = &homeserver($cnum,$cdom);
 9994:         } else {
 9995:             $homeserver = &domain($cdom,'primary');
 9996:         }
 9997:         if ($homeserver ne 'no_host') {
 9998:             $response = &reply('autorun:'.$cdom,$homeserver);
 9999:         }
10000:     }
10001:     return $response;
10002: }
10003: 
10004: sub auto_get_sections {
10005:     my ($cnum,$cdom,$inst_coursecode) = @_;
10006:     my $homeserver;
10007:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) { 
10008:         $homeserver = &homeserver($cnum,$cdom);
10009:     }
10010:     if (!defined($homeserver)) { 
10011:         if ($cdom =~ /^$match_domain$/) {
10012:             $homeserver = &domain($cdom,'primary');
10013:         }
10014:     }
10015:     my @secs;
10016:     if (defined($homeserver)) {
10017:         my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
10018:         unless ($response eq 'refused') {
10019:             @secs = split(/:/,$response);
10020:         }
10021:     }
10022:     return @secs;
10023: }
10024: 
10025: sub auto_new_course {
10026:     my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
10027:     my $homeserver = &homeserver($cnum,$cdom);
10028:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
10029:     return $response;
10030: }
10031: 
10032: sub auto_validate_courseID {
10033:     my ($cnum,$cdom,$inst_course_id) = @_;
10034:     my $homeserver = &homeserver($cnum,$cdom);
10035:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
10036:     return $response;
10037: }
10038: 
10039: sub auto_validate_instcode {
10040:     my ($cnum,$cdom,$instcode,$owner) = @_;
10041:     my ($homeserver,$response);
10042:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
10043:         $homeserver = &homeserver($cnum,$cdom);
10044:     }
10045:     if (!defined($homeserver)) {
10046:         if ($cdom =~ /^$match_domain$/) {
10047:             $homeserver = &domain($cdom,'primary');
10048:         }
10049:     }
10050:     $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
10051:                         &escape($instcode).':'.&escape($owner),$homeserver));
10052:     my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
10053:     return ($outcome,$description,$defaultcredits);
10054: }
10055: 
10056: sub auto_validate_inst_crosslist {
10057:     my ($cnum,$cdom,$instcode,$inst_xlist,$coowner) = @_;
10058:     my ($homeserver,$response);
10059:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
10060:         $homeserver = &homeserver($cnum,$cdom);
10061:     }
10062:     if (!defined($homeserver)) {
10063:         if ($cdom =~ /^$match_domain$/) {
10064:             $homeserver = &domain($cdom,'primary');
10065:         }
10066:     }
10067:     unless (($homeserver eq '') || ($homeserver eq 'no_host')) {
10068:         $response=&reply('autovalidateinstcrosslist:'.$cdom.':'.
10069:                          &escape($instcode).':'.&escape($inst_xlist).':'.
10070:                          &escape($coowner),$homeserver);
10071:     }
10072:     return $response;
10073: }
10074: 
10075: sub auto_create_password {
10076:     my ($cnum,$cdom,$authparam,$udom) = @_;
10077:     my ($homeserver,$response);
10078:     my $create_passwd = 0;
10079:     my $authchk = '';
10080:     if ($udom =~ /^$match_domain$/) {
10081:         $homeserver = &domain($udom,'primary');
10082:     }
10083:     if ($homeserver eq '') {
10084:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
10085:             $homeserver = &homeserver($cnum,$cdom);
10086:         }
10087:     }
10088:     if ($homeserver eq '') {
10089:         $authchk = 'nodomain';
10090:     } else {
10091:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
10092:         if ($response eq 'refused') {
10093:             $authchk = 'refused';
10094:         } else {
10095:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
10096:         }
10097:     }
10098:     return ($authparam,$create_passwd,$authchk);
10099: }
10100: 
10101: sub auto_photo_permission {
10102:     my ($cnum,$cdom,$students) = @_;
10103:     my $homeserver = &homeserver($cnum,$cdom);
10104:     my ($outcome,$perm_reqd,$conditions) = 
10105: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
10106:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
10107: 	return (undef,undef);
10108:     }
10109:     return ($outcome,$perm_reqd,$conditions);
10110: }
10111: 
10112: sub auto_checkphotos {
10113:     my ($uname,$udom,$pid) = @_;
10114:     my $homeserver = &homeserver($uname,$udom);
10115:     my ($result,$resulttype);
10116:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
10117: 				   &escape($uname).':'.&escape($pid),
10118: 				   $homeserver));
10119:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
10120: 	return (undef,undef);
10121:     }
10122:     if ($outcome) {
10123:         ($result,$resulttype) = split(/:/,$outcome);
10124:     } 
10125:     return ($result,$resulttype);
10126: }
10127: 
10128: sub auto_photochoice {
10129:     my ($cnum,$cdom) = @_;
10130:     my $homeserver = &homeserver($cnum,$cdom);
10131:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
10132: 						       &escape($cdom),
10133: 						       $homeserver)));
10134:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
10135: 	return (undef,undef);
10136:     }
10137:     return ($update,$comment);
10138: }
10139: 
10140: sub auto_photoupdate {
10141:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
10142:     my $homeserver = &homeserver($cnum,$dom);
10143:     my $host=&hostname($homeserver);
10144:     my $cmd = '';
10145:     my $maxtries = 1;
10146:     foreach my $affiliate (keys(%{$affiliatesref})) {
10147:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
10148:     }
10149:     $cmd =~ s/%%$//;
10150:     $cmd = &escape($cmd);
10151:     my $query = 'institutionalphotos';
10152:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
10153:     unless ($queryid=~/^\Q$host\E\_/) {
10154:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
10155:         return 'error: '.$queryid;
10156:     }
10157:     my $reply = &get_query_reply($queryid);
10158:     my $tries = 1;
10159:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
10160:         $reply = &get_query_reply($queryid);
10161:         $tries ++;
10162:     }
10163:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
10164:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
10165:     } else {
10166:         my @responses = split(/:/,$reply);
10167:         my $outcome = shift(@responses); 
10168:         foreach my $item (@responses) {
10169:             my ($key,$value) = split(/=/,$item);
10170:             $$photo{$key} = $value;
10171:         }
10172:         return $outcome;
10173:     }
10174:     return 'error';
10175: }
10176: 
10177: sub auto_instcode_format {
10178:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
10179: 	$cat_order) = @_;
10180:     my $courses = '';
10181:     my @homeservers;
10182:     if ($caller eq 'global') {
10183: 	my %servers = &get_servers($codedom,'library');
10184: 	foreach my $tryserver (keys(%servers)) {
10185: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
10186: 		push(@homeservers,$tryserver);
10187: 	    }
10188:         }
10189:     } elsif ($caller eq 'requests') {
10190:         if ($codedom =~ /^$match_domain$/) {
10191:             my $chome = &domain($codedom,'primary');
10192:             unless ($chome eq 'no_host') {
10193:                 push(@homeservers,$chome);
10194:             }
10195:         }
10196:     } else {
10197:         push(@homeservers,&homeserver($caller,$codedom));
10198:     }
10199:     foreach my $code (keys(%{$instcodes})) {
10200:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
10201:     }
10202:     chop($courses);
10203:     my $ok_response = 0;
10204:     my $response;
10205:     while (@homeservers > 0 && $ok_response == 0) {
10206:         my $server = shift(@homeservers); 
10207:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
10208:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
10209:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
10210: 		split(/:/,$response);
10211:             %{$codes} = (%{$codes},&str2hash($codes_str));
10212:             push(@{$codetitles},&str2array($codetitles_str));
10213:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
10214:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
10215:             $ok_response = 1;
10216:         }
10217:     }
10218:     if ($ok_response) {
10219:         return 'ok';
10220:     } else {
10221:         return $response;
10222:     }
10223: }
10224: 
10225: sub auto_instcode_defaults {
10226:     my ($domain,$returnhash,$code_order) = @_;
10227:     my @homeservers;
10228: 
10229:     my %servers = &get_servers($domain,'library');
10230:     foreach my $tryserver (keys(%servers)) {
10231: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
10232: 	    push(@homeservers,$tryserver);
10233: 	}
10234:     }
10235: 
10236:     my $response;
10237:     foreach my $server (@homeservers) {
10238:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
10239:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
10240: 	
10241: 	foreach my $pair (split(/\&/,$response)) {
10242: 	    my ($name,$value)=split(/\=/,$pair);
10243: 	    if ($name eq 'code_order') {
10244: 		@{$code_order} = split(/\&/,&unescape($value));
10245: 	    } else {
10246: 		$returnhash->{&unescape($name)}=&unescape($value);
10247: 	    }
10248: 	}
10249: 	return 'ok';
10250:     }
10251: 
10252:     return $response;
10253: }
10254: 
10255: sub auto_possible_instcodes {
10256:     my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
10257:     unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') && 
10258:             (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
10259:         return;
10260:     }
10261:     my (@homeservers,$uhome);
10262:     if (defined(&domain($domain,'primary'))) {
10263:         $uhome=&domain($domain,'primary');
10264:         push(@homeservers,&domain($domain,'primary'));
10265:     } else {
10266:         my %servers = &get_servers($domain,'library');
10267:         foreach my $tryserver (keys(%servers)) {
10268:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
10269:                 push(@homeservers,$tryserver);
10270:             }
10271:         }
10272:     }
10273:     my $response;
10274:     foreach my $server (@homeservers) {
10275:         $response=&reply('autopossibleinstcodes:'.$domain,$server);
10276:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
10277:         my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) = 
10278:             split(':',$response);
10279:         @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
10280:         @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
10281:         foreach my $item (split('&',$cat_title)) {   
10282:             my ($name,$value)=split('=',$item);
10283:             $cat_titles->{&unescape($name)}=&thaw_unescape($value);
10284:         }
10285:         foreach my $item (split('&',$cat_order)) {
10286:             my ($name,$value)=split('=',$item);
10287:             $cat_orders->{&unescape($name)}=&thaw_unescape($value);
10288:         }
10289:         return 'ok';
10290:     }
10291:     return $response;
10292: }
10293: 
10294: sub auto_courserequest_checks {
10295:     my ($dom) = @_;
10296:     my ($homeserver,%validations);
10297:     if ($dom =~ /^$match_domain$/) {
10298:         $homeserver = &domain($dom,'primary');
10299:     }
10300:     unless ($homeserver eq 'no_host') {
10301:         my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
10302:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
10303:             my @items = split(/&/,$response);
10304:             foreach my $item (@items) {
10305:                 my ($key,$value) = split('=',$item);
10306:                 $validations{&unescape($key)} = &thaw_unescape($value);
10307:             }
10308:         }
10309:     }
10310:     return %validations; 
10311: }
10312: 
10313: sub auto_courserequest_validation {
10314:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist,$custominfo) = @_;
10315:     my ($homeserver,$response);
10316:     if ($dom =~ /^$match_domain$/) {
10317:         $homeserver = &domain($dom,'primary');
10318:     }
10319:     unless ($homeserver eq 'no_host') {
10320:         my $customdata;
10321:         if (ref($custominfo) eq 'HASH') {
10322:             $customdata = &freeze_escape($custominfo);
10323:         }
10324:         $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
10325:                                     ':'.&escape($crstype).':'.&escape($inststatuslist).
10326:                                     ':'.&escape($instcode).':'.&escape($instseclist).':'.
10327:                                     $customdata,$homeserver));
10328:     }
10329:     return $response;
10330: }
10331: 
10332: sub auto_validate_class_sec {
10333:     my ($cdom,$cnum,$owners,$inst_class) = @_;
10334:     my $homeserver = &homeserver($cnum,$cdom);
10335:     my $ownerlist;
10336:     if (ref($owners) eq 'ARRAY') {
10337:         $ownerlist = join(',',@{$owners});
10338:     } else {
10339:         $ownerlist = $owners;
10340:     }
10341:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
10342:                         &escape($ownerlist).':'.$cdom,$homeserver);
10343:     return $response;
10344: }
10345: 
10346: sub auto_instsec_reformat {
10347:     my ($cdom,$action,$instsecref) = @_;
10348:     return unless(($action eq 'clutter') || ($action eq 'declutter'));
10349:     my @homeservers;
10350:     if (defined(&domain($cdom,'primary'))) {
10351:         push(@homeservers,&domain($cdom,'primary'));
10352:     } else {
10353:         my %servers = &get_servers($cdom,'library');
10354:         foreach my $tryserver (keys(%servers)) {
10355:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
10356:                 push(@homeservers,$tryserver);
10357:             }
10358:         }
10359:     }
10360:     my $response;
10361:     my %reformatted = %{$instsecref};
10362:     foreach my $server (@homeservers) {
10363:         if (ref($instsecref) eq 'HASH') {
10364:             my $info = &freeze_escape($instsecref);
10365:             my $response=&reply('autoinstsecreformat:'.$cdom.':'.
10366:                                 $action.':'.$info,$server);
10367:             next if ($response =~ /(con_lost|error|no_such_host|refused|unknown_command)/);
10368:             my @items = split(/&/,$response);
10369:             foreach my $item (@items) {
10370:                 my ($key,$value) = split(/=/,$item);
10371:                 $reformatted{&unescape($key)} = &thaw_unescape($value);
10372:             }
10373:         }
10374:     }
10375:     return %reformatted;
10376: }
10377: 
10378: sub auto_validate_instclasses {
10379:     my ($cdom,$cnum,$owners,$classesref) = @_;
10380:     my ($homeserver,%validations);
10381:     $homeserver = &homeserver($cnum,$cdom);
10382:     unless ($homeserver eq 'no_host') {
10383:         my $ownerlist;
10384:         if (ref($owners) eq 'ARRAY') {
10385:             $ownerlist = join(',',@{$owners});
10386:         } else {
10387:             $ownerlist = $owners;
10388:         }
10389:         if (ref($classesref) eq 'HASH') {
10390:             my $classes = &freeze_escape($classesref);
10391:             my $response=&reply('autovalidateinstclasses:'.&escape($ownerlist).
10392:                                 ':'.$cdom.':'.$classes,$homeserver);
10393:             unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
10394:                 my @items = split(/&/,$response);
10395:                 foreach my $item (@items) {
10396:                     my ($key,$value) = split('=',$item);
10397:                     $validations{&unescape($key)} = &thaw_unescape($value);
10398:                 }
10399:             }
10400:         }
10401:     }
10402:     return %validations;
10403: }
10404: 
10405: sub auto_crsreq_update {
10406:     my ($cdom,$cnum,$crstype,$action,$ownername,$ownerdomain,$fullname,$title,
10407:         $code,$accessstart,$accessend,$inbound) = @_;
10408:     my ($homeserver,%crsreqresponse);
10409:     if ($cdom =~ /^$match_domain$/) {
10410:         $homeserver = &domain($cdom,'primary');
10411:     }
10412:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
10413:         my $info;
10414:         if (ref($inbound) eq 'HASH') {
10415:             $info = &freeze_escape($inbound);
10416:         }
10417:         my $response=&reply('autocrsrequpdate:'.$cdom.':'.$cnum.':'.&escape($crstype).
10418:                             ':'.&escape($action).':'.&escape($ownername).':'.
10419:                             &escape($ownerdomain).':'.&escape($fullname).':'.
10420:                             &escape($title).':'.&escape($code).':'.
10421:                             &escape($accessstart).':'.&escape($accessend).':'.$info,
10422:                             $homeserver);
10423:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
10424:             my @items = split(/&/,$response);
10425:             foreach my $item (@items) {
10426:                 my ($key,$value) = split('=',$item);
10427:                 $crsreqresponse{&unescape($key)} = &thaw_unescape($value);
10428:             }
10429:         }
10430:     }
10431:     return \%crsreqresponse;
10432: }
10433: 
10434: sub auto_export_grades {
10435:     my ($cdom,$cnum,$inforef,$gradesref) = @_;
10436:     my ($homeserver,%exportresponse);
10437:     if ($cdom =~ /^$match_domain$/) {
10438:         $homeserver = &domain($cdom,'primary');
10439:     }
10440:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
10441:         my $info;
10442:         if (ref($inforef) eq 'HASH') {
10443:             $info = &freeze_escape($inforef);
10444:         }
10445:         if (ref($gradesref) eq 'HASH') {
10446:             my $grades = &freeze_escape($gradesref);
10447:             my $response=&reply('encrypt:autoexportgrades:'.$cdom.':'.$cnum.':'.
10448:                                 $info.':'.$grades,$homeserver);
10449:             unless ($response =~ /(con_lost|error|no_such_host|refused|unknown_command)/) {
10450:                 my @items = split(/&/,$response);
10451:                 foreach my $item (@items) {
10452:                     my ($key,$value) = split('=',$item);
10453:                     $exportresponse{&unescape($key)} = &thaw_unescape($value);
10454:                 }
10455:             }
10456:         }
10457:     }
10458:     return \%exportresponse;
10459: }
10460: 
10461: sub check_instcode_cloning {
10462:     my ($codedefaults,$code_order,$cloner,$clonefromcode,$clonetocode) = @_;
10463:     unless ((ref($codedefaults) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
10464:         return;
10465:     }
10466:     my $canclone;
10467:     if (@{$code_order} > 0) {
10468:         my $instcoderegexp ='^';
10469:         my @clonecodes = split(/\&/,$cloner);
10470:         foreach my $item (@{$code_order}) {
10471:             if (grep(/^\Q$item\E=/,@clonecodes)) {
10472:                 foreach my $pair (@clonecodes) {
10473:                     my ($key,$val) = split(/\=/,$pair,2);
10474:                     $val = &unescape($val);
10475:                     if ($key eq $item) {
10476:                         $instcoderegexp .= '('.$val.')';
10477:                         last;
10478:                     }
10479:                 }
10480:             } else {
10481:                 $instcoderegexp .= $codedefaults->{$item};
10482:             }
10483:         }
10484:         $instcoderegexp .= '$';
10485:         my (@from,@to);
10486:         eval {
10487:                (@from) = ($clonefromcode =~ /$instcoderegexp/);
10488:                (@to) = ($clonetocode =~ /$instcoderegexp/);
10489:         };
10490:         if ((@from > 0) && (@to > 0)) {
10491:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
10492:             if (!@diffs) {
10493:                 $canclone = 1;
10494:             }
10495:         }
10496:     }
10497:     return $canclone;
10498: }
10499: 
10500: sub default_instcode_cloning {
10501:     my ($clonedom,$domdefclone,$clonefromcode,$clonetocode,$codedefaultsref,$codeorderref) = @_;
10502:     my (%codedefaults,@code_order,$canclone);
10503:     if ((ref($codedefaultsref) eq 'HASH') && (ref($codeorderref) eq 'ARRAY')) {
10504:         %codedefaults = %{$codedefaultsref};
10505:         @code_order = @{$codeorderref};
10506:     } elsif ($clonedom) {
10507:         &auto_instcode_defaults($clonedom,\%codedefaults,\@code_order);
10508:     }
10509:     if (($domdefclone) && (@code_order)) {
10510:         my @clonecodes = split(/\+/,$domdefclone);
10511:         my $instcoderegexp ='^';
10512:         foreach my $item (@code_order) {
10513:             if (grep(/^\Q$item\E$/,@clonecodes)) {
10514:                 $instcoderegexp .= '('.$codedefaults{$item}.')';
10515:             } else {
10516:                 $instcoderegexp .= $codedefaults{$item};
10517:             }
10518:         }
10519:         $instcoderegexp .= '$';
10520:         my (@from,@to);
10521:         eval {
10522:             (@from) = ($clonefromcode =~ /$instcoderegexp/);
10523:             (@to) = ($clonetocode =~ /$instcoderegexp/);
10524:         };
10525:         if ((@from > 0) && (@to > 0)) {
10526:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
10527:             if (!@diffs) {
10528:                 $canclone = 1;
10529:             }
10530:         }
10531:     }
10532:     return $canclone;
10533: }
10534: 
10535: # ------------------------------------------------------- Course Group routines
10536: 
10537: sub get_coursegroups {
10538:     my ($cdom,$cnum,$group,$namespace) = @_;
10539:     return(&dump($namespace,$cdom,$cnum,$group));
10540: }
10541: 
10542: sub modify_coursegroup {
10543:     my ($cdom,$cnum,$groupsettings) = @_;
10544:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
10545: }
10546: 
10547: sub toggle_coursegroup_status {
10548:     my ($cdom,$cnum,$group,$action) = @_;
10549:     my ($from_namespace,$to_namespace);
10550:     if ($action eq 'delete') {
10551:         $from_namespace = 'coursegroups';
10552:         $to_namespace = 'deleted_groups';
10553:     } else {
10554:         $from_namespace = 'deleted_groups';
10555:         $to_namespace = 'coursegroups';
10556:     }
10557:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
10558:     if (my $tmp = &error(%curr_group)) {
10559:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
10560:         return ('read error',$tmp);
10561:     } else {
10562:         my %savedsettings = %curr_group; 
10563:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
10564:         my $deloutcome;
10565:         if ($result eq 'ok') {
10566:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
10567:         } else {
10568:             return ('write error',$result);
10569:         }
10570:         if ($deloutcome eq 'ok') {
10571:             return 'ok';
10572:         } else {
10573:             return ('delete error',$deloutcome);
10574:         }
10575:     }
10576: }
10577: 
10578: sub modify_group_roles {
10579:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context,
10580:         $othdomby,$requester) = @_;
10581:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
10582:     my $role = 'gr/'.&escape($userprivs);
10583:     my ($uname,$udom) = split(/:/,$user);
10584:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context,
10585:                              $othdomby,$requester);
10586:     if ($result eq 'ok') {
10587:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
10588:     }
10589:     return $result;
10590: }
10591: 
10592: sub modify_coursegroup_membership {
10593:     my ($cdom,$cnum,$membership) = @_;
10594:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
10595:     return $result;
10596: }
10597: 
10598: sub get_active_groups {
10599:     my ($udom,$uname,$cdom,$cnum) = @_;
10600:     my $now = time;
10601:     my %groups = ();
10602:     foreach my $key (keys(%env)) {
10603:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
10604:             my ($start,$end) = split(/\./,$env{$key});
10605:             if (($end!=0) && ($end<$now)) { next; }
10606:             if (($start!=0) && ($start>$now)) { next; }
10607:             if ($1 eq $cdom && $2 eq $cnum) {
10608:                 $groups{$3} = $env{$key} ;
10609:             }
10610:         }
10611:     }
10612:     return %groups;
10613: }
10614: 
10615: sub get_group_membership {
10616:     my ($cdom,$cnum,$group) = @_;
10617:     return(&dump('groupmembership',$cdom,$cnum,$group));
10618: }
10619: 
10620: sub get_users_groups {
10621:     my ($udom,$uname,$courseid) = @_;
10622:     my @usersgroups;
10623:     my $cachetime=1800;
10624: 
10625:     my $hashid="$udom:$uname:$courseid";
10626:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
10627:     if (defined($cached)) {
10628:         @usersgroups = split(/:/,$grouplist);
10629:     } else {  
10630:         $grouplist = '';
10631:         my $courseurl = &courseid_to_courseurl($courseid);
10632:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
10633:         my $access_end = $env{'course.'.$courseid.
10634:                               '.default_enrollment_end_date'};
10635:         my $now = time;
10636:         foreach my $key (keys(%roleshash)) {
10637:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
10638:                 my $group = $1;
10639:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
10640:                     my $start = $2;
10641:                     my $end = $1;
10642:                     if ($start == -1) { next; } # deleted from group
10643:                     if (($start!=0) && ($start>$now)) { next; }
10644:                     if (($end!=0) && ($end<$now)) {
10645:                         if ($access_end && $access_end < $now) {
10646:                             if ($access_end - $end < 86400) {
10647:                                 push(@usersgroups,$group);
10648:                             }
10649:                         }
10650:                         next;
10651:                     }
10652:                     push(@usersgroups,$group);
10653:                 }
10654:             }
10655:         }
10656:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
10657:         $grouplist = join(':',@usersgroups);
10658:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
10659:     }
10660:     return @usersgroups;
10661: }
10662: 
10663: sub devalidate_getgroups_cache {
10664:     my ($udom,$uname,$cdom,$cnum)=@_;
10665:     my $courseid = $cdom.'_'.$cnum;
10666: 
10667:     my $hashid="$udom:$uname:$courseid";
10668:     &devalidate_cache_new('getgroups',$hashid);
10669: }
10670: 
10671: # ------------------------------------------------------------------ Plain Text
10672: 
10673: sub plaintext {
10674:     my ($short,$type,$cid,$forcedefault) = @_;
10675:     if ($short =~ m{^cr/}) {
10676: 	return (split('/',$short))[-1];
10677:     }
10678:     if (!defined($cid)) {
10679:         $cid = $env{'request.course.id'};
10680:     }
10681:     my %rolenames = (
10682:                       Course    => 'std',
10683:                       Community => 'alt1',
10684:                       Placement => 'std',
10685:                     );
10686:     if ($cid ne '') {
10687:         if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
10688:             unless ($forcedefault) {
10689:                 my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
10690:                 &Apache::lonlocal::mt_escape(\$roletext);
10691:                 return &Apache::lonlocal::mt($roletext);
10692:             }
10693:         }
10694:     }
10695:     if ((defined($type)) && (defined($rolenames{$type})) &&
10696:         (defined($rolenames{$type})) && 
10697:         (defined($prp{$short}{$rolenames{$type}}))) {
10698:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
10699:     } elsif ($cid ne '') {
10700:         my $crstype = $env{'course.'.$cid.'.type'};
10701:         if (($crstype ne '') && (defined($rolenames{$crstype})) &&
10702:             (defined($prp{$short}{$rolenames{$crstype}}))) {
10703:             return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
10704:         }
10705:     }
10706:     return &Apache::lonlocal::mt($prp{$short}{'std'});
10707: }
10708: 
10709: # ----------------------------------------------------------------- Assign Role
10710: 
10711: sub assignrole {
10712:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
10713:         $context,$othdomby,$requester,$reqsec,$reqrole)=@_;
10714:     my ($mrole,$rolelogcontext);
10715:     if ($role =~ /^cr\//) {
10716:         my $cwosec=$url;
10717:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
10718:         if ((!&allowed('ccr',$cwosec)) && (!&allowed('ccr',$udom))) {
10719:             my $refused = 1;
10720:             if ($context eq 'requestcourses') {
10721:                 if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
10722:                     if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
10723:                         if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
10724:                             my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
10725:                             my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
10726:                             if ($crsenv{'internal.courseowner'} eq
10727:                                 $env{'user.name'}.':'.$env{'user.domain'}) {
10728:                                 $refused = '';
10729:                             }
10730:                         }
10731:                     }
10732:                 }
10733:             } elsif (($context eq 'course') && ($othdomby eq 'othdombyuser')) {
10734:                 my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
10735:                 my ($sec) = ($url =~ m{^/\Q$cwosec\E/(.*)$});
10736:                 my $key = "$uname:$udom:$role:$sec";
10737:                 my %queuedrolereq = &Apache::lonnet::get('nohist_othdomqueued',[$key],$cdom,$cnum);
10738:                 if ((exists($queuedrolereq{$key})) && (ref($queuedrolereq{$key}) eq 'HASH')) {
10739:                     if (($queuedrolereq{$key}{'adj'} eq 'user') && ($queuedrolereq{$key}{'requester'} eq $requester)) {
10740:                         $refused = '';
10741:                     }
10742:                 }
10743:             }
10744:             if ($refused) {
10745:                 &logthis('Refused custom assignrole: '.
10746:                          $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
10747:                          ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
10748:                 return 'refused';
10749:             }
10750:         }
10751:         $mrole='cr';
10752:     } elsif ($role =~ /^gr\//) {
10753:         my $cwogrp=$url;
10754:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
10755:         if (!&allowed('mdg',$cwogrp)) {
10756:             my $refused = 1;
10757:             if (($refused) && ($othdomby eq 'othdombyuser') && ($requester ne '') && ($reqrole ne '')) {
10758:                 my ($cdom,$cnum) = ($cwogrp =~ m{^/?($match_domain)/($match_courseid)$});
10759:                 my $key = "$uname:$udom:$reqrole:$reqsec";
10760:                 my %queuedrolereq = &Apache::lonnet::get('nohist_othdomqueued',[$key],$cdom,$cnum);
10761:                 if ((exists($queuedrolereq{$key})) && (ref($queuedrolereq{$key}) eq 'HASH')) {
10762:                     if (($queuedrolereq{$key}{'adj'} eq 'user') && ($queuedrolereq{$key}{'requester'} eq $requester)) {
10763:                         $refused = '';
10764:                     }
10765:                 }
10766:             }
10767:             if ($refused) {
10768:                 &logthis('Refused group assignrole: '.
10769:                          $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
10770:                          $env{'user.name'}.' at '.$env{'user.domain'});
10771:                 return 'refused';
10772:             }
10773:         }
10774:         $mrole='gr';
10775:     } else {
10776:         my $cwosec=$url;
10777:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
10778:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
10779:             my $refused;
10780:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
10781:                 if (!(&allowed('c'.$role,$url))) {
10782:                     $refused = 1;
10783:                 }
10784:             } else {
10785:                 $refused = 1;
10786:             }
10787:             if ($refused) {
10788:                 my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
10789:                 if (!$selfenroll && ($othdomby ne 'othdombyuser') &&
10790:                    (($context eq 'course') || ($context eq 'ltienroll' && $env{'request.lti.login'}))) {
10791:                     my %crsenv;
10792:                     if ($role eq 'cc' || $role eq 'co') {
10793:                         %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
10794:                         if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
10795:                             if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
10796:                                 if ($crsenv{'internal.courseowner'} eq 
10797:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
10798:                                     $refused = '';
10799:                                 }
10800:                             }
10801:                         } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) { 
10802:                             if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
10803:                                 if ($crsenv{'internal.courseowner'} eq 
10804:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
10805:                                     $refused = '';
10806:                                 }
10807:                             }
10808:                         }
10809:                     }
10810:                 } elsif (($selfenroll == 1) && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
10811:                     if ($role eq 'st') {
10812:                         $refused = '';
10813:                     } elsif (($context eq 'ltienroll') && ($env{'request.lti.login'})) {
10814:                         $refused = '';
10815:                     }
10816:                 } elsif ($othdomby eq 'othdombyuser') {
10817:                     my ($key,%queuedrolereq);
10818:                     if ($context eq 'course') {
10819:                         my ($sec) = ($url =~ m{^/\Q$cwosec\E/(.*)$});
10820:                         $key = "$uname:$udom:$role:$sec";
10821:                         %queuedrolereq = &Apache::lonnet::get('nohist_othdomqueued',[$key],$cdom,$cnum);
10822:                         if ((exists($queuedrolereq{$key})) && (ref($queuedrolereq{$key}) eq 'HASH')) {
10823:                             if (($queuedrolereq{$key}{'adj'} eq 'user') && ($queuedrolereq{$key}{'requester'} eq $requester)) {
10824:                                 if ((($role eq 'cc') && ($cnum !~ /^$match_community$/)) || 
10825:                                     (($role eq 'co') && ($cnum =~ /^$match_community$/))) {
10826:                                     my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
10827:                                     if ($crsenv{'internal.courseowner'} eq $requester) {
10828:                                         $refused = '';
10829:                                     }
10830:                                 } elsif ($role =~ /^(?:in|ta|ep|st)$/) {
10831:                                     $refused = '';
10832:                                 }
10833:                             }
10834:                         }
10835:                     } elsif (($context eq 'author') && ($role =~ /^ca|aa$/)) {
10836:                         my $key = "$uname:$udom:$role"; 
10837:                         my ($audom,$auname) = ($url =~ m{^/($match_domain)/($match_username)$});
10838:                         if (($audom ne '') && ($auname ne '')) {
10839:                             my %queuedrolereq = &Apache::lonnet::get('nohist_othdomqueued',[$key],$audom,$auname);
10840:                             if ((exists($queuedrolereq{$key})) && (ref($queuedrolereq{$key}) eq 'HASH')) {
10841:                                 if (($queuedrolereq{$key}{'adj'} eq 'user') && ($queuedrolereq{$key}{'requester'} eq $requester)) {
10842:                                     $refused = '';
10843:                                 }
10844:                             }
10845:                         }
10846:                     } elsif (($context eq 'domain') && ($role ne 'dc') && ($role ne 'su')) {
10847:                         my $key = "$uname:$udom:$role";
10848:                         my ($roledom) = ($url =~ m{^/($match_domain)/\Q$role\E$});
10849:                         if ($roledom ne '') {
10850:                             my $confname = $roledom.'-domainconfig';
10851:                             my %queuedrolereq = &Apache::lonnet::get('nohist_othdomqueued',[$key],$roledom,$confname);
10852:                             if ((exists($queuedrolereq{$key})) && (ref($queuedrolereq{$key}) eq 'HASH')) {
10853:                                 if (($queuedrolereq{$key}{'adj'} eq 'user') && ($queuedrolereq{$key}{'requester'} eq $requester)) {
10854:                                     $refused = '';
10855:                                 }
10856:                             }
10857:                         }
10858:                     }
10859:                 } elsif ($context eq 'requestcourses') {
10860:                     my @possroles = ('st','ta','ep','in','cc','co');
10861:                     if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
10862:                         my $wrongcc;
10863:                         if ($cnum =~ /^$match_community$/) {
10864:                             $wrongcc = 1 if ($role eq 'cc');
10865:                         } else {
10866:                             $wrongcc = 1 if ($role eq 'co');
10867:                         }
10868:                         unless ($wrongcc) {
10869:                             my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
10870:                             if ($crsenv{'internal.courseowner'} eq 
10871:                                  $env{'user.name'}.':'.$env{'user.domain'}) {
10872:                                 $refused = '';
10873:                             }
10874:                         }
10875:                     }
10876:                 } elsif ($context eq 'requestauthor') {
10877:                     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) && 
10878:                         ($url eq '/'.$udom.'/') && ($role eq 'au')) {
10879:                         if ($env{'environment.requestauthor'} eq 'automatic') {
10880:                             $refused = '';
10881:                         } else {
10882:                             my %domdefaults = &get_domain_defaults($udom);
10883:                             if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
10884:                                 my $checkbystatus;
10885:                                 if ($env{'user.adv'}) { 
10886:                                     my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
10887:                                     if ($disposition eq 'automatic') {
10888:                                         $refused = '';
10889:                                     } elsif ($disposition eq '') {
10890:                                         $checkbystatus = 1;
10891:                                     } 
10892:                                 } else {
10893:                                     $checkbystatus = 1;
10894:                                 }
10895:                                 if ($checkbystatus) {
10896:                                     if ($env{'environment.inststatus'}) {
10897:                                         my @inststatuses = split(/,/,$env{'environment.inststatus'});
10898:                                         foreach my $type (@inststatuses) {
10899:                                             if (($type ne '') &&
10900:                                                 ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
10901:                                                 $refused = '';
10902:                                             }
10903:                                         }
10904:                                     } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
10905:                                         $refused = '';
10906:                                     }
10907:                                 }
10908:                             }
10909:                         }
10910:                     }
10911:                 } elsif (($context eq 'author') && (($role eq 'ca' || $role eq 'aa'))) {
10912:                     if ($url =~ m{^/($match_domain)/($match_username)$}) {
10913:                         my ($audom,$auname) = ($1,$2);
10914:                         if ((&Apache::lonnet::allowed('v'.$role,"$audom/$auname")) &&
10915:                             ($env{"environment.internal.manager.$url"})) {
10916:                             $refused = '';
10917:                             $rolelogcontext = 'coauthor';
10918:                         }
10919:                     }
10920:                 }
10921:                 if ($refused) {
10922:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
10923:                              ' '.$role.' '.$end.' '.$start.' by '.
10924: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
10925:                     return 'refused';
10926:                 }
10927:             }
10928:         } elsif ($role eq 'au') {
10929:             if ($url ne '/'.$udom.'/') {
10930:                 &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
10931:                          ' to assign author role for '.$uname.':'.$udom.
10932:                          ' in domain: '.$url.' refused (wrong domain).');
10933:                 return 'refused';
10934:             }
10935:         }
10936:         $mrole=$role;
10937:     }
10938:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
10939:                 "$udom:$uname:$url".'_'."$mrole=$role";
10940:     if ($end) { $command.='_'.$end; }
10941:     if ($start) {
10942: 	if ($end) { 
10943:            $command.='_'.$start; 
10944:         } else {
10945:            $command.='_0_'.$start;
10946:         }
10947:     }
10948:     my $origstart = $start;
10949:     my $origend = $end;
10950:     my $delflag;
10951: # actually delete
10952:     if ($deleteflag) {
10953: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
10954: # modify command to delete the role
10955:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
10956:                 "$udom:$uname:$url".'_'."$mrole";
10957: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
10958: # set start and finish to negative values for userrolelog
10959:            $start=-1;
10960:            $end=-1;
10961:            $delflag = 1;
10962:         }
10963:     }
10964: # send command
10965:     my $answer=&reply($command,&homeserver($uname,$udom));
10966: # log new user role if status is ok
10967:     if ($answer eq 'ok') {
10968: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
10969:         if (($role eq 'cc') || ($role eq 'in') ||
10970:             ($role eq 'ep') || ($role eq 'ad') ||
10971:             ($role eq 'ta') || ($role eq 'st') ||
10972:             ($role=~/^cr/) || ($role eq 'gr') ||
10973:             ($role eq 'co')) {
10974: # for course roles, perform group memberships changes triggered by role change.
10975:             unless ($role =~ /^gr/) {
10976:                 &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
10977:                                                  $origstart,$selfenroll,$context);
10978:             }
10979:             &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
10980:                            $selfenroll,$context,$othdomby,$requester);
10981:         } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
10982:                  ($role eq 'au') || ($role eq 'dc') || ($role eq 'dh') ||
10983:                  ($role eq 'da')) {
10984:             &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
10985:                            $context,$othdomby,$requester);
10986:         } elsif (($role eq 'ca') || ($role eq 'aa')) {
10987:             if ($rolelogcontext eq '') {
10988:                 $rolelogcontext = $context;
10989:             }
10990:             &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
10991:                              $rolelogcontext,$othdomby,$requester); 
10992:         }
10993:         if ($role eq 'cc') {
10994:             &autoupdate_coowners($url,$end,$start,$uname,$udom);
10995:         }
10996:     }
10997:     return $answer;
10998: }
10999: 
11000: sub autoupdate_coowners {
11001:     my ($url,$end,$start,$uname,$udom) = @_;
11002:     my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
11003:     if (($cdom ne '') && ($cnum ne '')) {
11004:         my $now = time;
11005:         my %domdesign = &Apache::loncommon::get_domainconf($cdom);
11006:         if ($domdesign{$cdom.'.autoassign.co-owners'}) {
11007:             my %coursehash = &coursedescription($cdom.'_'.$cnum);
11008:             my $instcode = $coursehash{'internal.coursecode'};
11009:             my $xlists = $coursehash{'internal.crosslistings'};
11010:             if ($instcode ne '') {
11011:                 if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
11012:                     unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
11013:                         my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
11014:                         my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
11015:                         unless ($result eq 'valid') {
11016:                             if ($xlists ne '') {
11017:                                 foreach my $xlist (split(',',$xlists)) {
11018:                                     my ($inst_crosslist,$lcsec) = split(':',$xlist);
11019:                                     $result =
11020:                                         &auto_validate_inst_crosslist($cnum,$cdom,$instcode,
11021:                                                                       $inst_crosslist,$uname.':'.$udom);
11022:                                     last if ($result eq 'valid');
11023:                                 }
11024:                             }
11025:                         }
11026:                         if ($result eq 'valid') {
11027:                             if ($coursehash{'internal.co-owners'}) {
11028:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
11029:                                     push(@newcoowners,$coowner);
11030:                                 }
11031:                                 unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
11032:                                     push(@newcoowners,$uname.':'.$udom);
11033:                                 }
11034:                                 @newcoowners = sort(@newcoowners);
11035:                             } else {
11036:                                 push(@newcoowners,$uname.':'.$udom);
11037:                             }
11038:                         } elsif ($coursehash{'internal.co-owners'}) {
11039:                             foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
11040:                                 unless ($coowner eq $uname.':'.$udom) {
11041:                                     push(@newcoowners,$coowner);
11042:                                 }
11043:                             }
11044:                             unless (@newcoowners > 0) {
11045:                                 $delcoowners = 1;
11046:                                 $coowners = '';
11047:                             }
11048:                         }
11049:                         if (@newcoowners || $delcoowners) {
11050:                             &store_coowners($cdom,$cnum,$coursehash{'home'},
11051:                                             $delcoowners,@newcoowners);
11052:                         }
11053:                     }
11054:                 }
11055:             }
11056:         }
11057:     }
11058: }
11059: 
11060: sub store_coowners {
11061:     my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
11062:     my $cid = $cdom.'_'.$cnum;
11063:     my ($coowners,$delresult,$putresult);
11064:     if (@newcoowners) {
11065:         $coowners = join(',',@newcoowners);
11066:         my %coownershash = (
11067:                             'internal.co-owners' => $coowners,
11068:                            );
11069:         $putresult = &put('environment',\%coownershash,$cdom,$cnum);
11070:         if ($putresult eq 'ok') {
11071:             if ($env{'course.'.$cid.'.num'} eq $cnum) {
11072:                 &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
11073:             }
11074:         }
11075:     }
11076:     if ($delcoowners) {
11077:         $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
11078:         if ($delresult eq 'ok') {
11079:             if ($env{'course.'.$cid.'.internal.co-owners'}) {
11080:                 &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
11081:             }
11082:         }
11083:     }
11084:     if (($putresult eq 'ok') || ($delresult eq 'ok')) {
11085:         my %crsinfo =
11086:             &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
11087:         if (ref($crsinfo{$cid}) eq 'HASH') {
11088:             $crsinfo{$cid}{'co-owners'} = \@newcoowners;
11089:             my $cidput = &courseidput($cdom,\%crsinfo,$chome,'notime');
11090:         }
11091:     }
11092: }
11093: 
11094: # -------------------------------------------------- Modify user authentication
11095: # Overrides without validation
11096: 
11097: sub modifyuserauth {
11098:     my ($udom,$uname,$umode,$upass)=@_;
11099:     my $uhome=&homeserver($uname,$udom);
11100:     my $allowed;
11101:     if (&allowed('mau',$udom)) {
11102:         $allowed = 1;
11103:     } elsif (($umode eq 'internal') && ($udom eq $env{'user.domain'}) &&
11104:              ($env{'request.course.id'}) && (&allowed('mip',$env{'request.course.id'})) &&
11105:              (!$env{'course.'.$env{'request.course.id'}.'.internal.nopasswdchg'})) {
11106:         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
11107:         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
11108:         if (($cdom ne '') && ($cnum ne '')) {
11109:             my $is_owner = &is_course_owner($cdom,$cnum);
11110:             if ($is_owner) {
11111:                 $allowed = 1;
11112:             }
11113:         }
11114:     }
11115:     unless ($allowed) { return 'refused'; }
11116:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
11117:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
11118:              ' in domain '.$env{'request.role.domain'});  
11119:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
11120: 		     &escape($upass),$uhome);
11121:     my $ip = &get_requestor_ip();
11122:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
11123:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
11124:          '(Remote '.$ip.'): '.$reply);
11125:     &log($udom,,$uname,$uhome,
11126:         'Authentication changed by '.$env{'user.domain'}.', '.
11127:                                      $env{'user.name'}.', '.$umode.
11128:          '(Remote '.$ip.'): '.$reply);
11129:     unless ($reply eq 'ok') {
11130:         &logthis('Authentication mode error: '.$reply);
11131: 	return 'error: '.$reply;
11132:     }   
11133:     return 'ok';
11134: }
11135: 
11136: # --------------------------------------------------------------- Modify a user
11137: 
11138: sub modifyuser {
11139:     my ($udom,    $uname, $uid,
11140:         $umode,   $upass, $first,
11141:         $middle,  $last,  $gene,
11142:         $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
11143:     $udom= &LONCAPA::clean_domain($udom);
11144:     $uname=&LONCAPA::clean_username($uname);
11145:     my $showcandelete = 'none';
11146:     if (ref($candelete) eq 'ARRAY') {
11147:         if (@{$candelete} > 0) {
11148:             $showcandelete = join(', ',@{$candelete});
11149:         }
11150:     }
11151:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
11152:              $umode.', '.$first.', '.$middle.', '.
11153: 	     $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
11154:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
11155:                                      ' desiredhome not specified'). 
11156:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
11157:              ' in domain '.$env{'request.role.domain'});
11158:     my $uhome=&homeserver($uname,$udom,'true');
11159:     my $newuser;
11160:     if ($uhome eq 'no_host') {
11161:         $newuser = 1;
11162:         unless (($umode && ($upass ne '')) || ($umode eq 'localauth') ||
11163:                 ($umode eq 'lti')) {
11164:             return 'error: more information needed to create new user';
11165:         }
11166:     }
11167: # ----------------------------------------------------------------- Create User
11168:     if (($uhome eq 'no_host') && 
11169: 	(($umode && $upass) || ($umode eq 'localauth') || ($umode eq 'lti'))) {
11170:         my $unhome='';
11171:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
11172:             $unhome = $desiredhome;
11173: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
11174: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
11175:         } else { # load balancing routine for determining $unhome
11176:             my $loadm=10000000;
11177: 	    my %servers = &get_servers($udom,'library');
11178: 	    foreach my $tryserver (keys(%servers)) {
11179: 		my $answer=reply('load',$tryserver);
11180: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
11181: 		    $loadm=$answer;
11182: 		    $unhome=$tryserver;
11183: 		}
11184: 	    }
11185:         }
11186:         if (($unhome eq '') || ($unhome eq 'no_host')) {
11187: 	    return 'error: unable to find a home server for '.$uname.
11188:                    ' in domain '.$udom;
11189:         }
11190:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
11191:                          &escape($upass),$unhome);
11192: 	unless ($reply eq 'ok') {
11193:             return 'error: '.$reply;
11194:         }   
11195:         $uhome=&homeserver($uname,$udom,'true');
11196:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
11197: 	    return 'error: unable verify users home machine.';
11198:         }
11199:     }   # End of creation of new user
11200: # ---------------------------------------------------------------------- Add ID
11201:     if ($uid) {
11202:        $uid=~tr/A-Z/a-z/;
11203:        my %uidhash=&idrget($udom,$uname);
11204:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
11205:          && (!$forceid)) {
11206: 	  unless ($uid eq $uidhash{$uname}) {
11207: 	      return 'error: user id "'.$uid.'" does not match '.
11208:                   'current user id "'.$uidhash{$uname}.'".';
11209:           }
11210:        } else {
11211: 	  &idput($udom,{$uname => $uid},$uhome,'ids');
11212:        }
11213:     }
11214: # -------------------------------------------------------------- Add names, etc
11215:     my @tmp=&get('environment',
11216: 		   ['firstname','middlename','lastname','generation','id',
11217:                     'permanentemail','inststatus'],
11218: 		   $udom,$uname);
11219:     my (%names,%oldnames);
11220:     if ($tmp[0] =~ m/^error:.*/) { 
11221:         %names=(); 
11222:     } else {
11223:         %names = @tmp;
11224:         %oldnames = %names;
11225:     }
11226: #
11227: # If name, email and/or uid are blank (e.g., because an uploaded file
11228: # of users did not contain them), do not overwrite existing values
11229: # unless field is in $candelete array ref.  
11230: #
11231: 
11232:     my @fields = ('firstname','middlename','lastname','generation',
11233:                   'permanentemail','id');
11234:     my %newvalues;
11235:     if (ref($candelete) eq 'ARRAY') {
11236:         foreach my $field (@fields) {
11237:             if (grep(/^\Q$field\E$/,@{$candelete})) {
11238:                 if ($field eq 'firstname') {
11239:                     $names{$field} = $first;
11240:                 } elsif ($field eq 'middlename') {
11241:                     $names{$field} = $middle;
11242:                 } elsif ($field eq 'lastname') {
11243:                     $names{$field} = $last;
11244:                 } elsif ($field eq 'generation') { 
11245:                     $names{$field} = $gene;
11246:                 } elsif ($field eq 'permanentemail') {
11247:                     $names{$field} = $email;
11248:                 } elsif ($field eq 'id') {
11249:                     $names{$field}  = $uid;
11250:                 }
11251:             }
11252:         }
11253:     }
11254:     if ($first)  { $names{'firstname'}  = $first; }
11255:     if (defined($middle)) { $names{'middlename'} = $middle; }
11256:     if ($last)   { $names{'lastname'}   = $last; }
11257:     if (defined($gene))   { $names{'generation'} = $gene; }
11258:     if ($email) {
11259:        $email=~s/[^\w\@\.\-\,]//gs;
11260:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
11261:     }
11262:     if ($uid) { $names{'id'}  = $uid; }
11263:     if (defined($inststatus)) {
11264:         $names{'inststatus'} = '';
11265:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
11266:         if (ref($usertypes) eq 'HASH') {
11267:             my @okstatuses; 
11268:             foreach my $item (split(/:/,$inststatus)) {
11269:                 if (defined($usertypes->{$item})) {
11270:                     push(@okstatuses,$item);  
11271:                 }
11272:             }
11273:             if (@okstatuses) {
11274:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
11275:             }
11276:         }
11277:     }
11278:     my $logmsg = $udom.', '.$uname.', '.$uid.', '.
11279:                  $umode.', '.$first.', '.$middle.', '.
11280:                  $last.', '.$gene.', '.$email.', '.$inststatus;
11281:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
11282:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
11283:     } else {
11284:         $logmsg .= ' during self creation';
11285:     }
11286:     my $changed;
11287:     if ($newuser) {
11288:         $changed = 1;
11289:     } else {
11290:         foreach my $field (@fields) {
11291:             if ($names{$field} ne $oldnames{$field}) {
11292:                 $changed = 1;
11293:                 last;
11294:             }
11295:         }
11296:     }
11297:     unless ($changed) {
11298:         $logmsg = 'No changes in user information needed for: '.$logmsg;
11299:         &logthis($logmsg);
11300:         return 'ok';
11301:     }
11302:     my $reply = &put('environment', \%names, $udom,$uname);
11303:     if ($reply ne 'ok') { 
11304:         return 'error: '.$reply;
11305:     }
11306:     if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
11307:         &devalidate_cache_new('emailscache',$uname.':'.$udom);
11308:     }
11309:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
11310:     &devalidate_cache_new('namescache',$uname.':'.$udom);
11311:     $logmsg = 'Success modifying user '.$logmsg;
11312:     &logthis($logmsg);
11313:     return 'ok';
11314: }
11315: 
11316: # -------------------------------------------------------------- Modify student
11317: 
11318: sub modifystudent {
11319:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
11320:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
11321:         $selfenroll,$context,$inststatus,$credits,$instsec)=@_;
11322:     if (!$cid) {
11323: 	unless ($cid=$env{'request.course.id'}) {
11324: 	    return 'not_in_class';
11325: 	}
11326:     }
11327: # --------------------------------------------------------------- Make the user
11328:     my $reply=&modifyuser
11329: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
11330:          $desiredhome,$email,$inststatus);
11331:     unless ($reply eq 'ok') { return $reply; }
11332:     # This will cause &modify_student_enrollment to get the uid from the
11333:     # student's environment
11334:     $uid = undef if (!$forceid);
11335:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
11336:                                         $gene,$usec,$end,$start,$type,$locktype,
11337:                                         $cid,$selfenroll,$context,$credits,$instsec);
11338:     return $reply;
11339: }
11340: 
11341: sub modify_student_enrollment {
11342:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,
11343:         $locktype,$cid,$selfenroll,$context,$credits,$instsec,$othdomby,$requester) = @_;
11344:     my ($cdom,$cnum,$chome);
11345:     if (!$cid) {
11346: 	unless ($cid=$env{'request.course.id'}) {
11347: 	    return 'not_in_class';
11348: 	}
11349: 	$cdom=$env{'course.'.$cid.'.domain'};
11350: 	$cnum=$env{'course.'.$cid.'.num'};
11351:     } else {
11352: 	($cdom,$cnum)=split(/_/,$cid);
11353:     }
11354:     $chome=$env{'course.'.$cid.'.home'};
11355:     if (!$chome) {
11356: 	$chome=&homeserver($cnum,$cdom);
11357:     }
11358:     if (!$chome) { return 'unknown_course'; }
11359:     # Make sure the user exists
11360:     my $uhome=&homeserver($uname,$udom);
11361:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
11362: 	return 'error: no such user';
11363:     }
11364:     # Get student data if we were not given enough information
11365:     if (!defined($first)  || $first  eq '' || 
11366:         !defined($last)   || $last   eq '' || 
11367:         !defined($uid)    || $uid    eq '' || 
11368:         !defined($middle) || $middle eq '' || 
11369:         !defined($gene)   || $gene   eq '') {
11370:         # They did not supply us with enough data to enroll the student, so
11371:         # we need to pick up more information.
11372:         my %tmp = &get('environment',
11373:                        ['firstname','middlename','lastname', 'generation','id']
11374:                        ,$udom,$uname);
11375: 
11376:         #foreach my $key (keys(%tmp)) {
11377:         #    &logthis("key $key = ".$tmp{$key});
11378:         #}
11379:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
11380:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
11381:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
11382:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
11383:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
11384:     }
11385:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
11386:     my $user = "$uname:$udom";
11387:     my %old_entry = &get('classlist',[$user],$cdom,$cnum);
11388:     my $reply=cput('classlist',
11389: 		   {$user => 
11390: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits,$instsec) },
11391: 		   $cdom,$cnum);
11392:     if (($reply eq 'ok') || ($reply eq 'delayed')) {
11393:         &devalidate_getsection_cache($udom,$uname,$cid);
11394:     } else { 
11395: 	return 'error: '.$reply;
11396:     }
11397:     # Add student role to user
11398:     my $uurl='/'.$cid;
11399:     $uurl=~s/\_/\//g;
11400:     if ($usec) {
11401: 	$uurl.='/'.$usec;
11402:     }
11403:     my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
11404:                              $selfenroll,$context,$othdomby,$requester);
11405:     if ($result ne 'ok') {
11406:         if ($old_entry{$user} ne '') {
11407:             $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
11408:         } else {
11409:             $reply = &del('classlist',[$user],$cdom,$cnum);
11410:         }
11411:     }
11412:     return $result; 
11413: }
11414: 
11415: sub format_name {
11416:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
11417:     my $name;
11418:     if ($first ne 'lastname') {
11419: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
11420:     } else {
11421: 	if ($lastname=~/\S/) {
11422: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
11423: 	    $name=~s/\s+,/,/;
11424: 	} else {
11425: 	    $name.= $firstname.' '.$middlename.' '.$generation;
11426: 	}
11427:     }
11428:     $name=~s/^\s+//;
11429:     $name=~s/\s+$//;
11430:     $name=~s/\s+/ /g;
11431:     return $name;
11432: }
11433: 
11434: # ------------------------------------------------- Write to course preferences
11435: 
11436: sub writecoursepref {
11437:     my ($courseid,%prefs)=@_;
11438:     $courseid=~s/^\///;
11439:     $courseid=~s/\_/\//g;
11440:     my ($cdomain,$cnum)=split(/\//,$courseid);
11441:     my $chome=homeserver($cnum,$cdomain);
11442:     if (($chome eq '') || ($chome eq 'no_host')) { 
11443: 	return 'error: no such course';
11444:     }
11445:     my $cstring='';
11446:     foreach my $pref (keys(%prefs)) {
11447: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
11448:     }
11449:     $cstring=~s/\&$//;
11450:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
11451: }
11452: 
11453: # ---------------------------------------------------------- Make/modify course
11454: 
11455: sub createcourse {
11456:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
11457:         $course_owner,$crstype,$cnum,$context,$category,$callercontext)=@_;
11458:     $url=&declutter($url);
11459:     my $cid='';
11460:     if ($context eq 'requestcourses') {
11461:         my $can_create = 0;
11462:         my ($ownername,$ownerdom) = split(':',$course_owner);
11463:         if ($udom eq $ownerdom) {
11464:             my $reload;
11465:             if (($callercontext eq 'auto') &&
11466:                ($ownerdom eq $env{'user.domain'}) && ($ownername eq $env{'user.name'})) {
11467:                 $reload = 'reload';
11468:             }
11469:             if (&usertools_access($ownername,$ownerdom,$category,$reload,
11470:                                   $context)) {
11471:                 $can_create = 1;
11472:             }
11473:         } else {
11474:             my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
11475:                                            $category);
11476:             if ($userenv{'reqcrsotherdom.'.$category} ne '') {
11477:                 my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
11478:                 if (@curr > 0) {
11479:                     my @options = qw(approval validate autolimit);
11480:                     my $optregex = join('|',@options);
11481:                     if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
11482:                         $can_create = 1;
11483:                     }
11484:                 }
11485:             }
11486:         }
11487:         if ($can_create) {
11488:             unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
11489:                 unless (&allowed('ccc',$udom)) {
11490:                     return 'refused'; 
11491:                 }
11492:             }
11493:         } else {
11494:             return 'refused';
11495:         }
11496:     } elsif (!&allowed('ccc',$udom)) {
11497:         return 'refused';
11498:     }
11499: # --------------------------------------------------------------- Get Unique ID
11500:     my $uname;
11501:     if ($cnum =~ /^$match_courseid$/) {
11502:         my $chome=&homeserver($cnum,$udom,'true');
11503:         if (($chome eq '') || ($chome eq 'no_host')) {
11504:             $uname = $cnum;
11505:         } else {
11506:             $uname = &generate_coursenum($udom,$crstype);
11507:         }
11508:     } else {
11509:         $uname = &generate_coursenum($udom,$crstype);
11510:     }
11511:     return $uname if ($uname =~ /^error/);
11512: # -------------------------------------------------- Check supplied server name
11513:     if (!defined($course_server)) {
11514:         if (defined(&domain($udom,'primary'))) {
11515:             $course_server = &domain($udom,'primary');
11516:         } else {
11517:             $course_server = $env{'user.home'}; 
11518:         }
11519:     }
11520:     my %host_servers =
11521:         &get_servers($udom,'library');
11522:     unless ($host_servers{$course_server}) {
11523:         return 'error: invalid home server for course: '.$course_server;
11524:     }
11525: # ------------------------------------------------------------- Make the course
11526:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
11527:                       $course_server);
11528:     unless ($reply eq 'ok') { return 'error: '.$reply; }
11529:     my $uhome=&homeserver($uname,$udom,'true');
11530:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
11531: 	return 'error: no such course';
11532:     }
11533: # ----------------------------------------------------------------- Course made
11534: # log existence
11535:     my $now = time;
11536:     my $newcourse = {
11537:                     $udom.'_'.$uname => {
11538:                                      description => $description,
11539:                                      inst_code   => $inst_code,
11540:                                      owner       => $course_owner,
11541:                                      type        => $crstype,
11542:                                      creator     => $env{'user.name'}.':'.
11543:                                                     $env{'user.domain'},
11544:                                      created     => $now,
11545:                                      context     => $context,
11546:                                                 },
11547:                     };
11548:     &courseidput($udom,$newcourse,$uhome,'notime');
11549: # set toplevel url
11550:     my $topurl=$url;
11551:     unless ($nonstandard) {
11552: # ------------------------------------------ For standard courses, make top url
11553:         my $mapurl=&clutter($url);
11554:         if ($mapurl eq '/res/') { $mapurl=''; }
11555:         $env{'form.initmap'}=(<<ENDINITMAP);
11556: <map>
11557: <resource id="1" type="start"></resource>
11558: <resource id="2" src="$mapurl"></resource>
11559: <resource id="3" type="finish"></resource>
11560: <link index="1" from="1" to="2"></link>
11561: <link index="2" from="2" to="3"></link>
11562: </map>
11563: ENDINITMAP
11564:         $topurl=&declutter(
11565:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
11566:                           );
11567:     }
11568: # ----------------------------------------------------------- Write preferences
11569:     &writecoursepref($udom.'_'.$uname,
11570:                      ('description'              => $description,
11571:                       'url'                      => $topurl,
11572:                       'internal.creator'         => $env{'user.name'}.':'.
11573:                                                     $env{'user.domain'},
11574:                       'internal.created'         => $now,
11575:                       'internal.creationcontext' => $context)
11576:                     );
11577:     return '/'.$udom.'/'.$uname;
11578: }
11579: 
11580: # ------------------------------------------------------------------- Create ID
11581: sub generate_coursenum {
11582:     my ($udom,$crstype) = @_;
11583:     my $domdesc = &domain($udom);
11584:     return 'error: invalid domain' if ($domdesc eq '');
11585:     my $first;
11586:     if ($crstype eq 'Community') {
11587:         $first = '0';
11588:     } else {
11589:         $first = int(1+rand(9)); 
11590:     } 
11591:     my $uname=$first.
11592:         ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
11593:         substr($$.time,0,5).unpack("H8",pack("I32",time)).
11594:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
11595: # ----------------------------------------------- Make sure that does not exist
11596:     my $uhome=&homeserver($uname,$udom,'true');
11597:     unless (($uhome eq '') || ($uhome eq 'no_host')) {
11598:         if ($crstype eq 'Community') {
11599:             $first = '0';
11600:         } else {
11601:             $first = int(1+rand(9));
11602:         }
11603:         $uname=$first.
11604:                ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
11605:                substr($$.time,0,5).unpack("H8",pack("I32",time)).
11606:                unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
11607:         $uhome=&homeserver($uname,$udom,'true');
11608:         unless (($uhome eq '') || ($uhome eq 'no_host')) {
11609:             return 'error: unable to generate unique course-ID';
11610:         }
11611:     }
11612:     return $uname;
11613: }
11614: 
11615: sub is_course {
11616:     my ($cdom, $cnum) = scalar(@_) == 1 ? 
11617:          ($_[0] =~ /^($match_domain)_($match_courseid)$/)  :  @_;
11618: 
11619:     return unless (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/));
11620:     my $uhome=&homeserver($cnum,$cdom);
11621:     my $iscourse;
11622:     if (grep { $_ eq $uhome } current_machine_ids()) {
11623:         $iscourse = &LONCAPA::Lond::is_course($cdom,$cnum);
11624:     } else {
11625:         my $hashid = $cdom.':'.$cnum;
11626:         ($iscourse,my $cached) = &is_cached_new('iscourse',$hashid);
11627:         unless (defined($cached)) {
11628:             my %courses = &courseiddump($cdom, '.', 1, '.', '.',
11629:                                         $cnum,undef,undef,'.');
11630:             $iscourse = 0;
11631:             if (exists($courses{$cdom.'_'.$cnum})) {
11632:                 $iscourse = 1;
11633:             }
11634:             &do_cache_new('iscourse',$hashid,$iscourse,3600);
11635:         }
11636:     }
11637:     return unless ($iscourse);
11638:     return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
11639: }
11640: 
11641: sub store_userdata {
11642:     my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
11643:     my $result;
11644:     if ($datakey ne '') {
11645:         if (ref($storehash) eq 'HASH') {
11646:             if ($udom eq '' || $uname eq '') {
11647:                 $udom = $env{'user.domain'};
11648:                 $uname = $env{'user.name'};
11649:             }
11650:             my $uhome=&homeserver($uname,$udom);
11651:             if (($uhome eq '') || ($uhome eq 'no_host')) {
11652:                 $result = 'error: no_host';
11653:             } else {
11654:                 $storehash->{'ip'} = &get_requestor_ip();
11655:                 $storehash->{'host'} = $perlvar{'lonHostID'};
11656: 
11657:                 my $namevalue='';
11658:                 foreach my $key (keys(%{$storehash})) {
11659:                     $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
11660:                 }
11661:                 $namevalue=~s/\&$//;
11662:                 unless ($namespace eq 'courserequests') {
11663:                     $datakey = &escape($datakey);
11664:                 }
11665:                 $result =  &reply("store:$udom:$uname:$namespace:$datakey:".
11666:                                   $namevalue,$uhome);
11667:             }
11668:         } else {
11669:             $result = 'error: data to store was not a hash reference'; 
11670:         }
11671:     } else {
11672:         $result= 'error: invalid requestkey'; 
11673:     }
11674:     return $result;
11675: }
11676: 
11677: # ---------------------------------------------------------- Assign Custom Role
11678: 
11679: sub assigncustomrole {
11680:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,
11681:         $selfenroll,$context,$othdomby,$requester)=@_;
11682:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
11683:                        $end,$start,$deleteflag,$selfenroll,$context,$othdomby,
11684:                        $requester);
11685: }
11686: 
11687: # ----------------------------------------------------------------- Revoke Role
11688: 
11689: sub revokerole {
11690:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
11691:     my $now=time;
11692:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
11693: }
11694: 
11695: # ---------------------------------------------------------- Revoke Custom Role
11696: 
11697: sub revokecustomrole {
11698:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
11699:     my $now=time;
11700:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
11701:            $deleteflag,$selfenroll,$context);
11702: }
11703: 
11704: # ------------------------------------------------------------ Disk usage
11705: sub diskusage {
11706:     my ($udom,$uname,$directorypath,$getpropath)=@_;
11707:     $directorypath =~ s/\/$//;
11708:     my $listing=&reply('du2:'.&escape($directorypath).':'
11709:                        .&escape($getpropath).':'.&escape($uname).':'
11710:                        .&escape($udom),homeserver($uname,$udom));
11711:     if ($listing eq 'unknown_cmd') {
11712:         if ($getpropath) {
11713:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
11714:         }
11715:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
11716:     }
11717:     return $listing;
11718: }
11719: 
11720: sub is_locked {
11721:     my ($file_name, $domain, $user, $which) = @_;
11722:     my @check;
11723:     my $is_locked;
11724:     push (@check,$file_name);
11725:     my %locked = &get('file_permissions',\@check,
11726: 		      $env{'user.domain'},$env{'user.name'});
11727:     my ($tmp)=keys(%locked);
11728:     if ($tmp=~/^error:/) { undef(%locked); }
11729:     
11730:     if (ref($locked{$file_name}) eq 'ARRAY') {
11731:         $is_locked = 'false';
11732:         foreach my $entry (@{$locked{$file_name}}) {
11733:            if (ref($entry) eq 'ARRAY') {
11734:                $is_locked = 'true';
11735:                if (ref($which) eq 'ARRAY') {
11736:                    push(@{$which},$entry);
11737:                } else {
11738:                    last;
11739:                }
11740:            }
11741:        }
11742:     } else {
11743:         $is_locked = 'false';
11744:     }
11745:     return $is_locked;
11746: }
11747: 
11748: sub declutter_portfile {
11749:     my ($file) = @_;
11750:     $file =~ s{^(/portfolio/|portfolio/)}{/};
11751:     return $file;
11752: }
11753: 
11754: # ------------------------------------------------------------- Mark as Read Only
11755: 
11756: sub mark_as_readonly {
11757:     my ($domain,$user,$files,$what) = @_;
11758:     my %current_permissions = &dump('file_permissions',$domain,$user);
11759:     my ($tmp)=keys(%current_permissions);
11760:     if ($tmp=~/^error:/) { undef(%current_permissions); }
11761:     foreach my $file (@{$files}) {
11762: 	$file = &declutter_portfile($file);
11763:         push(@{$current_permissions{$file}},$what);
11764:     }
11765:     &put('file_permissions',\%current_permissions,$domain,$user);
11766:     return;
11767: }
11768: 
11769: # ------------------------------------------------------------Save Selected Files
11770: 
11771: sub save_selected_files {
11772:     my ($user, $path, @files) = @_;
11773:     my $filename = $user."savedfiles";
11774:     my @other_files = &files_not_in_path($user, $path);
11775:     open (OUT,'>',LONCAPA::tempdir().$filename);
11776:     foreach my $file (@files) {
11777:         print (OUT $env{'form.currentpath'}.$file."\n");
11778:     }
11779:     foreach my $file (@other_files) {
11780:         print (OUT $file."\n");
11781:     }
11782:     close (OUT);
11783:     return 'ok';
11784: }
11785: 
11786: sub clear_selected_files {
11787:     my ($user) = @_;
11788:     my $filename = $user."savedfiles";
11789:     open (OUT,'>',LONCAPA::tempdir().$filename);
11790:     print (OUT undef);
11791:     close (OUT);
11792:     return ("ok");    
11793: }
11794: 
11795: sub files_in_path {
11796:     my ($user, $path) = @_;
11797:     my $filename = $user."savedfiles";
11798:     my %return_files;
11799:     open (IN,'<',LONCAPA::tempdir().$filename);
11800:     while (my $line_in = <IN>) {
11801:         chomp ($line_in);
11802:         my @paths_and_file = split (m!/!, $line_in);
11803:         my $file_part = pop (@paths_and_file);
11804:         my $path_part = join ('/', @paths_and_file);
11805:         $path_part.='/';
11806:         my $path_and_file = $path_part.$file_part;
11807:         if ($path_part eq $path) {
11808:             $return_files{$file_part}= 'selected';
11809:         }
11810:     }
11811:     close (IN);
11812:     return (\%return_files);
11813: }
11814: 
11815: # called in portfolio select mode, to show files selected NOT in current directory
11816: sub files_not_in_path {
11817:     my ($user, $path) = @_;
11818:     my $filename = $user."savedfiles";
11819:     my @return_files;
11820:     my $path_part;
11821:     open(IN, '<',LONCAPA::tempdir().$filename);
11822:     while (my $line = <IN>) {
11823:         #ok, I know it's clunky, but I want it to work
11824:         my @paths_and_file = split(m|/|, $line);
11825:         my $file_part = pop(@paths_and_file);
11826:         chomp($file_part);
11827:         my $path_part = join('/', @paths_and_file);
11828:         $path_part .= '/';
11829:         my $path_and_file = $path_part.$file_part;
11830:         if ($path_part ne $path) {
11831:             push(@return_files, ($path_and_file));
11832:         }
11833:     }
11834:     close(OUT);
11835:     return (@return_files);
11836: }
11837: 
11838: #------------------------------Submitted/Handedback Portfolio Files Versioning
11839:  
11840: sub portfiles_versioning {
11841:     my ($symb,$domain,$stu_name,$portfiles,$versioned_portfiles) = @_;
11842:     my $portfolio_root = '/userfiles/portfolio';
11843:     return unless ((ref($portfiles) eq 'ARRAY') && (ref($versioned_portfiles) eq 'ARRAY'));
11844:     foreach my $file (@{$portfiles}) {
11845:         &unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
11846:         my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
11847:         my ($answer_name,$answer_ver,$answer_ext) = &file_name_version_ext($answer_file);
11848:         my $getpropath = 1;
11849:         my ($dir_list,$listerror) = &dirlist($portfolio_root.$directory,$domain,
11850:                                              $stu_name,$getpropath);
11851:         my $version = &get_next_version($answer_name,$answer_ext,$dir_list);
11852:         my $new_answer = 
11853:             &version_selected_portfile($domain,$stu_name,$directory,$answer_file,$version);
11854:         if ($new_answer ne 'problem getting file') {
11855:             push(@{$versioned_portfiles}, $directory.$new_answer);
11856:             &mark_as_readonly($domain,$stu_name,[$directory.$new_answer],
11857:                               [$symb,$env{'request.course.id'},'graded']);
11858:         }
11859:     }
11860: }
11861: 
11862: sub get_next_version {
11863:     my ($answer_name, $answer_ext, $dir_list) = @_;
11864:     my $version;
11865:     if (ref($dir_list) eq 'ARRAY') {
11866:         foreach my $row (@{$dir_list}) {
11867:             my ($file) = split(/\&/,$row,2);
11868:             my ($file_name,$file_version,$file_ext) =
11869:                 &file_name_version_ext($file);
11870:             if (($file_name eq $answer_name) &&
11871:                 ($file_ext eq $answer_ext)) {
11872:                      # gets here if filename and extension match,
11873:                      # regardless of version
11874:                 if ($file_version ne '') {
11875:                     # a versioned file is found  so save it for later
11876:                     if ($file_version > $version) {
11877:                         $version = $file_version;
11878:                     }
11879:                 }
11880:             }
11881:         }
11882:     }
11883:     $version ++;
11884:     return($version);
11885: }
11886: 
11887: sub version_selected_portfile {
11888:     my ($domain,$stu_name,$directory,$file_name,$version) = @_;
11889:     my ($answer_name,$answer_ver,$answer_ext) =
11890:         &file_name_version_ext($file_name);
11891:     my $new_answer;
11892:     $env{'form.copy'} =
11893:         &getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
11894:     if($env{'form.copy'} eq '-1') {
11895:         $new_answer = 'problem getting file';
11896:     } else {
11897:         $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
11898:         my $copy_result = 
11899:             &finishuserfileupload($stu_name,$domain,'copy',
11900:                                   '/portfolio'.$directory.$new_answer);
11901:     }
11902:     undef($env{'form.copy'});
11903:     return ($new_answer);
11904: }
11905: 
11906: sub file_name_version_ext {
11907:     my ($file)=@_;
11908:     my @file_parts = split(/\./, $file);
11909:     my ($name,$version,$ext);
11910:     if (@file_parts > 1) {
11911:         $ext=pop(@file_parts);
11912:         if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
11913:             $version=pop(@file_parts);
11914:         }
11915:         $name=join('.',@file_parts);
11916:     } else {
11917:         $name=join('.',@file_parts);
11918:     }
11919:     return($name,$version,$ext);
11920: }
11921: 
11922: #----------------------------------------------Get portfolio file permissions
11923: 
11924: sub get_portfile_permissions {
11925:     my ($domain,$user) = @_;
11926:     my %current_permissions = &dump('file_permissions',$domain,$user);
11927:     my ($tmp)=keys(%current_permissions);
11928:     if ($tmp=~/^error:/) { undef(%current_permissions); }
11929:     return \%current_permissions;
11930: }
11931: 
11932: #---------------------------------------------Get portfolio file access controls
11933: 
11934: sub get_access_controls {
11935:     my ($current_permissions,$group,$file) = @_;
11936:     my %access;
11937:     my $real_file = $file;
11938:     $file =~ s/\.meta$//;
11939:     if (defined($file)) {
11940:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
11941:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
11942:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
11943:             }
11944:         }
11945:     } else {
11946:         foreach my $key (keys(%{$current_permissions})) {
11947:             if ($key =~ /\0accesscontrol$/) {
11948:                 if (defined($group)) {
11949:                     if ($key !~ m-^\Q$group\E/-) {
11950:                         next;
11951:                     }
11952:                 }
11953:                 my ($fullpath) = split(/\0/,$key);
11954:                 if (ref($$current_permissions{$key}) eq 'HASH') {
11955:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
11956:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
11957:                     }
11958:                 }
11959:             }
11960:         }
11961:     }
11962:     return %access;
11963: }
11964: 
11965: sub modify_access_controls {
11966:     my ($file_name,$changes,$domain,$user)=@_;
11967:     my ($outcome,$deloutcome);
11968:     my %store_permissions;
11969:     my %new_values;
11970:     my %new_control;
11971:     my %translation;
11972:     my @deletions = ();
11973:     my $now = time;
11974:     if (exists($$changes{'activate'})) {
11975:         if (ref($$changes{'activate'}) eq 'HASH') {
11976:             my @newitems = sort(keys(%{$$changes{'activate'}}));
11977:             my $numnew = scalar(@newitems);
11978:             for (my $i=0; $i<$numnew; $i++) {
11979:                 my $newkey = $newitems[$i];
11980:                 my $newid = &Apache::loncommon::get_cgi_id();
11981:                 if ($newkey =~ /^\d+:/) { 
11982:                     $newkey =~ s/^(\d+)/$newid/;
11983:                     $translation{$1} = $newid;
11984:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
11985:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
11986:                     $translation{$1} = $newid;
11987:                 }
11988:                 $new_values{$file_name."\0".$newkey} = 
11989:                                           $$changes{'activate'}{$newitems[$i]};
11990:                 $new_control{$newkey} = $now;
11991:             }
11992:         }
11993:     }
11994:     my %todelete;
11995:     my %changed_items;
11996:     foreach my $action ('delete','update') {
11997:         if (exists($$changes{$action})) {
11998:             if (ref($$changes{$action}) eq 'HASH') {
11999:                 foreach my $key (keys(%{$$changes{$action}})) {
12000:                     my ($itemnum) = ($key =~ /^([^:]+):/);
12001:                     if ($action eq 'delete') { 
12002:                         $todelete{$itemnum} = 1;
12003:                     } else {
12004:                         $changed_items{$itemnum} = $key;
12005:                     }
12006:                 }
12007:             }
12008:         }
12009:     }
12010:     # get lock on access controls for file.
12011:     my $lockhash = {
12012:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
12013:                                                        ':'.$env{'user.domain'},
12014:                    }; 
12015:     my $tries = 0;
12016:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
12017:    
12018:     while (($gotlock ne 'ok') && $tries < 10) {
12019:         $tries ++;
12020:         sleep(0.1);
12021:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
12022:     }
12023:     if ($gotlock eq 'ok') {
12024:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
12025:         my ($tmp)=keys(%curr_permissions);
12026:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
12027:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
12028:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
12029:             if (ref($curr_controls) eq 'HASH') {
12030:                 foreach my $control_item (keys(%{$curr_controls})) {
12031:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
12032:                     if (defined($todelete{$itemnum})) {
12033:                         push(@deletions,$file_name."\0".$control_item);
12034:                     } else {
12035:                         if (defined($changed_items{$itemnum})) {
12036:                             $new_control{$changed_items{$itemnum}} = $now;
12037:                             push(@deletions,$file_name."\0".$control_item);
12038:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
12039:                         } else {
12040:                             $new_control{$control_item} = $$curr_controls{$control_item};
12041:                         }
12042:                     }
12043:                 }
12044:             }
12045:         }
12046:         my ($group);
12047:         if (&is_course($domain,$user)) {
12048:             ($group,my $file) = split(/\//,$file_name,2);
12049:         }
12050:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
12051:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
12052:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
12053:         #  remove lock
12054:         my @del_lock = ($file_name."\0".'locked_access_records');
12055:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
12056:         my $sqlresult =
12057:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
12058:                                     $group);
12059:     } else {
12060:         $outcome = "error: could not obtain lockfile\n";  
12061:     }
12062:     return ($outcome,$deloutcome,\%new_values,\%translation);
12063: }
12064: 
12065: sub make_public_indefinitely {
12066:     my (@requrl) = @_;
12067:     return &automated_portfile_access('public',\@requrl);
12068: }
12069: 
12070: sub automated_portfile_access {
12071:     my ($accesstype,$addsref,$delsref,$info) = @_;
12072:     unless (($accesstype eq 'public') || ($accesstype eq 'ip')) {
12073:         return 'invalid';
12074:     }
12075:     my %urls;
12076:     if (ref($addsref) eq 'ARRAY') {
12077:         foreach my $requrl (@{$addsref}) {
12078:             if (&is_portfolio_url($requrl)) {
12079:                 unless (exists($urls{$requrl})) {
12080:                     $urls{$requrl} = 'add';
12081:                 }
12082:             }
12083:         }
12084:     }
12085:     if (ref($delsref) eq 'ARRAY') {
12086:         foreach my $requrl (@{$delsref}) { 
12087:             if (&is_portfolio_url($requrl)) {
12088:                 unless (exists($urls{$requrl})) {
12089:                     $urls{$requrl} = 'delete'; 
12090:                 }
12091:             }
12092:         }
12093:     }
12094:     unless (keys(%urls)) {
12095:         return 'invalid';
12096:     }
12097:     my $ip;
12098:     if ($accesstype eq 'ip') {
12099:         if (ref($info) eq 'HASH') {
12100:             if ($info->{'ip'} ne '') {
12101:                 $ip = $info->{'ip'};
12102:             }
12103:         }
12104:         if ($ip eq '') {
12105:             return 'invalid';
12106:         }
12107:     }
12108:     my $errors;
12109:     my $now = time;
12110:     my %current_perms;
12111:     foreach my $requrl (sort(keys(%urls))) {
12112:         my $action;
12113:         if ($urls{$requrl} eq 'add') {
12114:             $action = 'activate';
12115:         } else {
12116:             $action = 'none';
12117:         }
12118:         my $aclnum = 0;
12119:         my (undef,$udom,$unum,$file_name,$group) =
12120:             &parse_portfolio_url($requrl);
12121:         unless (exists($current_perms{$unum.':'.$udom})) {
12122:             $current_perms{$unum.':'.$udom} = &get_portfile_permissions($udom,$unum);
12123:         }
12124:         my %access_controls = &get_access_controls($current_perms{$unum.':'.$udom},
12125:                                                    $group,$file_name);
12126:         foreach my $key (keys(%{$access_controls{$file_name}})) {
12127:             my ($num,$scope,$end,$start) = 
12128:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
12129:             if ($scope eq $accesstype) {
12130:                 if (($start <= $now) && ($end == 0)) {
12131:                     if ($accesstype eq 'ip') {
12132:                         if (ref($access_controls{$file_name}{$key}) eq 'HASH') {
12133:                             if (ref($access_controls{$file_name}{$key}{'ip'}) eq 'ARRAY') {
12134:                                 if (grep(/^\Q$ip\E$/,@{$access_controls{$file_name}{$key}{'ip'}})) {
12135:                                     if ($urls{$requrl} eq 'add') {
12136:                                         $action = 'none';
12137:                                         last;
12138:                                     } else {
12139:                                         $action = 'delete';
12140:                                         $aclnum = $num;
12141:                                         last;
12142:                                     }
12143:                                 }
12144:                             }
12145:                         }
12146:                     } elsif ($accesstype eq 'public') {
12147:                         if ($urls{$requrl} eq 'add') {
12148:                             $action = 'none';
12149:                             last;
12150:                         } else {
12151:                             $action = 'delete';
12152:                             $aclnum = $num;
12153:                             last;
12154:                         }
12155:                     }
12156:                 } elsif ($accesstype eq 'public') {
12157:                     $action = 'update';
12158:                     $aclnum = $num;
12159:                     last;
12160:                 }
12161:             }
12162:         }
12163:         if ($action eq 'none') {
12164:             next;
12165:         } else {
12166:             my %changes;
12167:             my $newend = 0;
12168:             my $newstart = $now;
12169:             my $newkey = $aclnum.':'.$accesstype.'_'.$newend.'_'.$newstart;
12170:             $changes{$action}{$newkey} = {
12171:                 type => $accesstype,
12172:                 time => {
12173:                     start => $newstart,
12174:                     end   => $newend,
12175:                 },
12176:             };
12177:             if ($accesstype eq 'ip') {
12178:                 $changes{$action}{$newkey}{'ip'} = [$ip];
12179:             }
12180:             my ($outcome,$deloutcome,$new_values,$translation) =
12181:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
12182:             unless ($outcome eq 'ok') {
12183:                 $errors .= $outcome.' ';
12184:             }
12185:         }
12186:     }
12187:     if ($errors) {
12188:         $errors =~ s/\s$//;
12189:         return $errors;
12190:     } else {
12191:         return 'ok';
12192:     }
12193: }
12194: 
12195: #------------------------------------------------------Get Marked as Read Only
12196: 
12197: sub get_marked_as_readonly {
12198:     my ($domain,$user,$what,$group) = @_;
12199:     my $current_permissions = &get_portfile_permissions($domain,$user);
12200:     my @readonly_files;
12201:     my $cmp1=$what;
12202:     if (ref($what)) { $cmp1=join('',@{$what}) };
12203:     while (my ($file_name,$value) = each(%{$current_permissions})) {
12204:         if (defined($group)) {
12205:             if ($file_name !~ m-^\Q$group\E/-) {
12206:                 next;
12207:             }
12208:         }
12209:         if (ref($value) eq "ARRAY"){
12210:             foreach my $stored_what (@{$value}) {
12211:                 my $cmp2=$stored_what;
12212:                 if (ref($stored_what) eq 'ARRAY') {
12213:                     $cmp2=join('',@{$stored_what});
12214:                 }
12215:                 if ($cmp1 eq $cmp2) {
12216:                     push(@readonly_files, $file_name);
12217:                     last;
12218:                 } elsif (!defined($what)) {
12219:                     push(@readonly_files, $file_name);
12220:                     last;
12221:                 }
12222:             }
12223:         }
12224:     }
12225:     return @readonly_files;
12226: }
12227: #-----------------------------------------------------------Get Marked as Read Only Hash
12228: 
12229: sub get_marked_as_readonly_hash {
12230:     my ($current_permissions,$group,$what) = @_;
12231:     my %readonly_files;
12232:     while (my ($file_name,$value) = each(%{$current_permissions})) {
12233:         if (defined($group)) {
12234:             if ($file_name !~ m-^\Q$group\E/-) {
12235:                 next;
12236:             }
12237:         }
12238:         if (ref($value) eq "ARRAY"){
12239:             foreach my $stored_what (@{$value}) {
12240:                 if (ref($stored_what) eq 'ARRAY') {
12241:                     foreach my $lock_descriptor(@{$stored_what}) {
12242:                         if ($lock_descriptor eq 'graded') {
12243:                             $readonly_files{$file_name} = 'graded';
12244:                         } elsif ($lock_descriptor eq 'handback') {
12245:                             $readonly_files{$file_name} = 'handback';
12246:                         } else {
12247:                             if (!exists($readonly_files{$file_name})) {
12248:                                 $readonly_files{$file_name} = 'locked';
12249:                             }
12250:                         }
12251:                     }
12252:                 } 
12253:             }
12254:         } 
12255:     }
12256:     return %readonly_files;
12257: }
12258: # ------------------------------------------------------------ Unmark as Read Only
12259: 
12260: sub unmark_as_readonly {
12261:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
12262:     # for portfolio submissions, $what contains [$symb,$crsid] 
12263:     my ($domain,$user,$what,$file_name,$group) = @_;
12264:     $file_name = &declutter_portfile($file_name);
12265:     my $symb_crs = $what;
12266:     if (ref($what)) { $symb_crs=join('',@$what); }
12267:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
12268:     my ($tmp)=keys(%current_permissions);
12269:     if ($tmp=~/^error:/) { undef(%current_permissions); }
12270:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
12271:     foreach my $file (@readonly_files) {
12272: 	my $clean_file = &declutter_portfile($file);
12273: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
12274: 	my $current_locks = $current_permissions{$file};
12275:         my @new_locks;
12276:         my @del_keys;
12277:         if (ref($current_locks) eq "ARRAY"){
12278:             foreach my $locker (@{$current_locks}) {
12279:                 my $compare=$locker;
12280:                 if (ref($locker) eq 'ARRAY') {
12281:                     $compare=join('',@{$locker});
12282:                     if ($compare ne $symb_crs) {
12283:                         push(@new_locks, $locker);
12284:                     }
12285:                 }
12286:             }
12287:             if (scalar(@new_locks) > 0) {
12288:                 $current_permissions{$file} = \@new_locks;
12289:             } else {
12290:                 push(@del_keys, $file);
12291:                 &del('file_permissions',\@del_keys, $domain, $user);
12292:                 delete($current_permissions{$file});
12293:             }
12294:         }
12295:     }
12296:     &put('file_permissions',\%current_permissions,$domain,$user);
12297:     return;
12298: }
12299: 
12300: # ------------------------------------------------------------ Directory lister
12301: 
12302: sub dirlist {
12303:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
12304:     $uri=~s/^\///;
12305:     $uri=~s/\/$//;
12306:     my ($udom, $uname);
12307:     if ($getuserdir) {
12308:         $udom = $userdomain;
12309:         $uname = $username;
12310:     } else {
12311:         (undef,$udom,$uname)=split(/\//,$uri);
12312:         if(defined($userdomain)) {
12313:             $udom = $userdomain;
12314:         }
12315:         if(defined($username)) {
12316:             $uname = $username;
12317:         }
12318:     }
12319:     my ($dirRoot,$listing,@listing_results);
12320: 
12321:     $dirRoot = $perlvar{'lonDocRoot'};
12322:     if (defined($getpropath)) {
12323:         $dirRoot = &propath($udom,$uname);
12324:         $dirRoot =~ s/\/$//;
12325:     } elsif (defined($getuserdir)) {
12326:         my $subdir=$uname.'__';
12327:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
12328:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
12329:                    ."/$udom/$subdir/$uname";
12330:     } elsif (defined($alternateRoot)) {
12331:         $dirRoot = $alternateRoot;
12332:     }
12333: 
12334:     if($udom) {
12335:         if($uname) {
12336:             my $uhome = &homeserver($uname,$udom);
12337:             if ($uhome eq 'no_host') {
12338:                 return ([],'no_host');
12339:             }
12340:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
12341:                               .$getuserdir.':'.&escape($dirRoot)
12342:                               .':'.&escape($uname).':'.&escape($udom),$uhome);
12343:             if ($listing eq 'unknown_cmd') {
12344:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
12345:             } else {
12346:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
12347:             }
12348:             if ($listing eq 'unknown_cmd') {
12349:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
12350:                 @listing_results = split(/:/,$listing);
12351:             } else {
12352:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
12353:             }
12354:             if (($listing eq 'no_such_host') || ($listing eq 'con_lost') || 
12355:                 ($listing eq 'rejected') || ($listing eq 'refused') ||
12356:                 ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
12357:                 return ([],$listing);
12358:             } else {
12359:                 return (\@listing_results);
12360:             }
12361:         } elsif(!$alternateRoot) {
12362:             my (%allusers,%listerror);
12363: 	    my %servers = &get_servers($udom,'library');
12364:  	    foreach my $tryserver (keys(%servers)) {
12365:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
12366:                                   &escape($udom),$tryserver);
12367:                 if ($listing eq 'unknown_cmd') {
12368: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
12369: 				      $udom, $tryserver);
12370:                 } else {
12371:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
12372:                 }
12373: 		if ($listing eq 'unknown_cmd') {
12374: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
12375: 				      $udom, $tryserver);
12376: 		    @listing_results = split(/:/,$listing);
12377: 		} else {
12378: 		    @listing_results =
12379: 			map { &unescape($_); } split(/:/,$listing);
12380: 		}
12381:                 if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
12382:                     ($listing eq 'rejected') || ($listing eq 'refused') ||
12383:                     ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
12384:                     $listerror{$tryserver} = $listing;
12385:                 } else {
12386: 		    foreach my $line (@listing_results) {
12387: 			my ($entry) = split(/&/,$line,2);
12388: 			$allusers{$entry} = 1;
12389: 		    }
12390: 		}
12391:             }
12392:             my @alluserslist=();
12393:             foreach my $user (sort(keys(%allusers))) {
12394:                 push(@alluserslist,$user.'&user');
12395:             }
12396: 
12397:             if (!%listerror) {
12398:                 # no errors
12399:                 return (\@alluserslist);
12400:             } elsif (scalar(keys(%servers)) == 1) {
12401:                 # one library server, one error 
12402:                 my ($key) = keys(%listerror);
12403:                 return (\@alluserslist, $listerror{$key});
12404:             } elsif ( grep { $_ eq 'con_lost' } values(%listerror) ) {
12405:                 # con_lost indicates that we might miss data from at least one
12406:                 # library server
12407:                 return (\@alluserslist, 'con_lost');
12408:             } else {
12409:                 # multiple library servers and no con_lost -> data should be
12410:                 # complete. 
12411:                 return (\@alluserslist);
12412:             }
12413: 
12414:         } else {
12415:             return ([],'missing username');
12416:         }
12417:     } elsif(!defined($getpropath)) {
12418:         my $path = $perlvar{'lonDocRoot'}.'/res/'; 
12419:         my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
12420:         return (\@all_domains);
12421:     } else {
12422:         return ([],'missing domain');
12423:     }
12424: }
12425: 
12426: # --------------------------------------------- GetFileTimestamp
12427: # This function utilizes dirlist and returns the date stamp for
12428: # when it was last modified.  It will also return an error of -1
12429: # if an error occurs
12430: 
12431: sub GetFileTimestamp {
12432:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
12433:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
12434:     $studentName   = &LONCAPA::clean_username($studentName);
12435:     my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
12436:                                     undef,$getuserdir);
12437:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
12438:         return -1;
12439:     }
12440:     if (ref($fileref) eq 'ARRAY') {
12441:         my @stats = split('&',$fileref->[0]);
12442:         # @stats contains first the filename, then the stat output
12443:         return $stats[10]; # so this is 10 instead of 9.
12444:     } else {
12445:         return -1;
12446:     }
12447: }
12448: 
12449: sub stat_file {
12450:     my ($uri) = @_;
12451:     $uri = &clutter_with_no_wrapper($uri);
12452: 
12453:     my ($udom,$uname,$file);
12454:     if ($uri =~ m-^/(uploaded|editupload)/-) {
12455: 	($udom,$uname,$file) =
12456: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
12457: 	$file = 'userfiles/'.$file;
12458:     }
12459:     if ($uri =~ m-^/res/-) {
12460: 	($udom,$uname) = 
12461: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
12462: 	$file = $uri;
12463:     }
12464: 
12465:     if (!$udom || !$uname || !$file) {
12466: 	# unable to handle the uri
12467: 	return ();
12468:     }
12469:     my $getpropath;
12470:     if ($file =~ /^userfiles\//) {
12471:         $getpropath = 1;
12472:     }
12473:     my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
12474:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
12475:         return ();
12476:     } else {
12477:         if (ref($listref) eq 'ARRAY') {
12478:             my @stats = split('&',$listref->[0]);
12479: 	    shift(@stats); #filename is first
12480: 	    return @stats;
12481:         }
12482:     }
12483:     return ();
12484: }
12485: 
12486: # --------------------------------------------------------- recursedirs
12487: # Recursive function to traverse either a specific user's Authoring Space
12488: # or corresponding Published Resource Space, and populate the hash ref:
12489: # $dirhashref with URLs of all directories, and if $filehashref hash
12490: # ref arg is provided, the URLs of any files, excluding versioned, .meta,
12491: # or .rights files in resource space, and .meta, .save, .log, .bak and
12492: # .rights files in Authoring Space.
12493: #
12494: # Inputs:
12495: #
12496: # $is_home - true if current server is home server for user's space
12497: # $recurse - if true will also traverse subdirectories recursively
12498: # $include - reference to hash containing allowed file extensions.  If provided,
12499: #             files which do not have a matching extension will be ignored.
12500: # $exclude - reference to hash containing excluded file extensions.  If provided,
12501: #             files which have a matching extension will be ignored.
12502: # $nonemptydir - if true, will only populate $fileshashref hash entry for a particular
12503: #             directory with first file found (with acceptable extension).
12504: # $addtopdir - if true, set $dirhashref->{'/'} = 1 
12505: # $toppath - Top level directory (i.e., /res/$dom/$uname or /priv/$dom/$uname
12506: # $relpath - Current path (relative to top level).
12507: # $dirhashref - reference to hash to populate with URLs of directories (Required)
12508: # $filehashref - reference to hash to populate with URLs of files (Optional)
12509: #
12510: # Returns: nothing
12511: #
12512: # Side Effects: populates $dirhashref, and $filehashref (if provided).
12513: #
12514: # Currently used by interface/londocs.pm to create linked select boxes for
12515: # directory and filename to import a Course "Author" resource into a course, and
12516: # also to create linked select boxes for Authoring Space and Directory to choose
12517: # save location for creation of a new "standard" problem from the Course Editor.
12518: #
12519: 
12520: sub recursedirs {
12521:     my ($is_home,$recurse,$include,$exclude,$nonemptydir,$addtopdir,$toppath,$relpath,$dirhashref,$filehashref) = @_;
12522:     return unless (ref($dirhashref) eq 'HASH');
12523:     my $docroot = $perlvar{'lonDocRoot'};
12524:     my $currpath = $docroot.$toppath;
12525:     if ($relpath ne '') {
12526:         $currpath .= "/$relpath";
12527:     }
12528:     my ($savefile,$checkinc,$checkexc);
12529:     if (ref($filehashref)) {
12530:         $savefile = 1;
12531:     }
12532:     if (ref($include) eq 'HASH') {
12533:         $checkinc = 1;
12534:     }
12535:     if (ref($exclude) eq 'HASH') {
12536:         $checkexc = 1;
12537:     }
12538:     if ($is_home) {
12539:         if ((-e $currpath) && (opendir(my $dirh,$currpath))) {
12540:             my $filecount = 0;
12541:             foreach my $item (sort { lc($a) cmp lc($b) } grep(!/^\.+$/,readdir($dirh))) {
12542:                 next if ($item eq '');
12543:                 if (-d "$currpath/$item") {
12544:                     my $newpath;
12545:                     if ($relpath ne '') {
12546:                         $newpath = "$relpath/$item";
12547:                     } else {
12548:                         $newpath = $item;
12549:                     }
12550:                     $dirhashref->{&Apache::lonlocal::js_escape($newpath)} = 1;
12551:                     if ($recurse) {
12552:                         &recursedirs($is_home,$recurse,$include,$exclude,$nonemptydir,$addtopdir,$toppath,$newpath,$dirhashref,$filehashref);
12553:                     }
12554:                 } elsif (($savefile) || ($relpath eq '')) {
12555:                     next if ($nonemptydir && $filecount);
12556:                     if ($checkinc || $checkexc) {
12557:                         my ($extension) = ($item =~ /\.(\w+)$/);
12558:                         if ($checkinc) {
12559:                             next unless ($extension && $include->{$extension});
12560:                         }
12561:                         if ($checkexc) {
12562:                             next if ($extension && $exclude->{$extension});
12563:                         }
12564:                     }
12565:                     if (($relpath eq '') && (!exists($dirhashref->{'/'}))) {
12566:                         $dirhashref->{'/'} = 1;
12567:                     }
12568:                     if ($savefile) {
12569:                         if ($relpath eq '') {
12570:                             $filehashref->{'/'}{$item} = 1;
12571:                         } else {
12572:                             $filehashref->{&Apache::lonlocal::js_escape($relpath)}{$item} = 1;
12573:                         }
12574:                     }
12575:                     $filecount ++;
12576:                 }
12577:             }
12578:             closedir($dirh);
12579:         }
12580:     } else {
12581:         my ($dirlistref,$listerror) =
12582:             &dirlist($toppath.$relpath);
12583:         my @dir_lines;
12584:         my $dirptr=16384;
12585:         if (ref($dirlistref) eq 'ARRAY') {
12586:             my $filecount = 0;
12587:             foreach my $dir_line (sort
12588:                               {
12589:                                   my ($afile)=split('&',$a,2);
12590:                                   my ($bfile)=split('&',$b,2);
12591:                                   return (lc($afile) cmp lc($bfile));
12592:                               } (@{$dirlistref})) {
12593:                 my ($item,$dom,undef,$testdir,undef,undef,undef,undef,$size,undef,$mtime,undef,undef,undef,$obs,undef) =
12594:                     split(/\&/,$dir_line,16);
12595:                 $item =~ s/\s+$//;
12596:                 next if (($item =~ /^\.\.?$/) || ($obs));
12597:                 if ($dirptr&$testdir) {
12598:                     my $newpath;
12599:                     if ($relpath) {
12600:                         $newpath = "$relpath/$item";
12601:                     } else {
12602:                         $newpath = $item;
12603:                     }
12604:                     $dirhashref->{&Apache::lonlocal::js_escape($newpath)} = 1;
12605:                     if ($recurse) {
12606:                         &recursedirs($is_home,$recurse,$include,$exclude,$nonemptydir,$addtopdir,$toppath,$newpath,$dirhashref,$filehashref);
12607:                     }
12608:                 } elsif (($savefile) || ($relpath eq '')) {
12609:                     next if ($nonemptydir && $filecount);
12610:                     if ($checkinc || $checkexc) {
12611:                         my $extension;
12612:                         if ($checkinc) {
12613:                             next unless ($extension && $include->{$extension});
12614:                         }
12615:                         if ($checkexc) {
12616:                             next if ($extension && $exclude->{$extension});
12617:                         }
12618:                     }
12619:                     if (($relpath eq '') && (!exists($dirhashref->{'/'}))) {
12620:                         $dirhashref->{'/'} = 1;
12621:                     }
12622:                     if ($savefile) {
12623:                         if ($relpath eq '') {
12624:                             $filehashref->{'/'}{$item} = 1;
12625:                         } else {
12626:                             $filehashref->{&Apache::lonlocal::js_escape($relpath)}{$item} = 1;
12627:                         }
12628:                     }
12629:                     $filecount ++; 
12630:                 }
12631:             }
12632:         }
12633:     }
12634:     if ($addtopdir) {
12635:         if (($relpath eq '') && (!exists($dirhashref->{'/'}))) {
12636:             $dirhashref->{'/'} = 1;
12637:         }
12638:     }
12639:     return;
12640: }
12641: 
12642: sub priv_exclude {
12643:     return {
12644:              meta => 1,
12645:              save => 1,
12646:              log => 1,
12647:              bak => 1,
12648:              rights => 1,
12649:              DS_Store => 1,
12650:            };
12651: }
12652: 
12653: # -------------------------------------------------------- Value of a Condition
12654: 
12655: # gets the value of a specific preevaluated condition
12656: #    stored in the string  $env{user.state.<cid>}
12657: # or looks up a condition reference in the bighash and if if hasn't
12658: # already been evaluated recurses into docondval to get the value of
12659: # the condition, then memoizing it to 
12660: #   $env{user.state.<cid>.<condition>}
12661: sub directcondval {
12662:     my $number=shift;
12663:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
12664: 	&Apache::lonuserstate::evalstate();
12665:     }
12666:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
12667: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
12668:     } elsif ($number =~ /^_/) {
12669: 	my $sub_condition;
12670: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
12671: 		&GDBM_READER(),0640)) {
12672: 	    $sub_condition=$bighash{'conditions'.$number};
12673: 	    untie(%bighash);
12674: 	}
12675: 	my $value = &docondval($sub_condition);
12676: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
12677: 	return $value;
12678:     }
12679:     if ($env{'user.state.'.$env{'request.course.id'}}) {
12680:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
12681:     } else {
12682:        return 2;
12683:     }
12684: }
12685: 
12686: # get the collection of conditions for this resource
12687: sub condval {
12688:     my $condidx=shift;
12689:     my $allpathcond='';
12690:     foreach my $cond (split(/\|/,$condidx)) {
12691: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
12692: 	    $allpathcond.=
12693: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
12694: 	}
12695:     }
12696:     $allpathcond=~s/\|$//;
12697:     return &docondval($allpathcond);
12698: }
12699: 
12700: #evaluates an expression of conditions
12701: sub docondval {
12702:     my ($allpathcond) = @_;
12703:     my $result=0;
12704:     if ($env{'request.course.id'}
12705: 	&& defined($allpathcond)) {
12706: 	my $operand='|';
12707: 	my @stack;
12708: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
12709: 	    if ($chunk eq '(') {
12710: 		push @stack,($operand,$result);
12711: 	    } elsif ($chunk eq ')') {
12712: 		my $before=pop @stack;
12713: 		if (pop @stack eq '&') {
12714: 		    $result=$result>$before?$before:$result;
12715: 		} else {
12716: 		    $result=$result>$before?$result:$before;
12717: 		}
12718: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
12719: 		$operand=$chunk;
12720: 	    } else {
12721: 		my $new=directcondval($chunk);
12722: 		if ($operand eq '&') {
12723: 		    $result=$result>$new?$new:$result;
12724: 		} else {
12725: 		    $result=$result>$new?$result:$new;
12726: 		}
12727: 	    }
12728: 	}
12729:     }
12730:     return $result;
12731: }
12732: 
12733: # ---------------------------------------------------- Devalidate courseresdata
12734: 
12735: sub devalidatecourseresdata {
12736:     my ($coursenum,$coursedomain)=@_;
12737:     my $hashid=$coursenum.':'.$coursedomain;
12738:     &devalidate_cache_new('courseres',$hashid);
12739: }
12740: 
12741: 
12742: # --------------------------------------------------- Course Resourcedata Query
12743: #
12744: #  Parameters:
12745: #      $coursenum    - Number of the course.
12746: #      $coursedomain - Domain at which the course was created.
12747: #  Returns:
12748: #     A hash of the course parameters along (I think) with timestamps
12749: #     and version info.
12750: 
12751: sub get_courseresdata {
12752:     my ($coursenum,$coursedomain)=@_;
12753:     my $coursehom=&homeserver($coursenum,$coursedomain);
12754:     my $hashid=$coursenum.':'.$coursedomain;
12755:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
12756:     my %dumpreply;
12757:     unless (defined($cached)) {
12758: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
12759: 	$result=\%dumpreply;
12760: 	my ($tmp) = keys(%dumpreply);
12761: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
12762: 	    &do_cache_new('courseres',$hashid,$result,600);
12763: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
12764: 	    return $tmp;
12765: 	} elsif ($tmp =~ /^(error)/) {
12766: 	    $result=undef;
12767: 	    &do_cache_new('courseres',$hashid,$result,600);
12768: 	}
12769:     }
12770:     return $result;
12771: }
12772: 
12773: sub devalidateuserresdata {
12774:     my ($uname,$udom)=@_;
12775:     my $hashid="$udom:$uname";
12776:     &devalidate_cache_new('userres',$hashid);
12777: }
12778: 
12779: sub get_userresdata {
12780:     my ($uname,$udom)=@_;
12781:     #most student don\'t have any data set, check if there is some data
12782:     if (&EXT_cache_status($udom,$uname)) { return undef; }
12783: 
12784:     my $hashid="$udom:$uname";
12785:     my ($result,$cached)=&is_cached_new('userres',$hashid);
12786:     if (!defined($cached)) {
12787: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
12788: 	$result=\%resourcedata;
12789: 	&do_cache_new('userres',$hashid,$result,600);
12790:     }
12791:     my ($tmp)=keys(%$result);
12792:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
12793: 	return $result;
12794:     }
12795:     #error 2 occurs when the .db doesn't exist
12796:     if ($tmp!~/error: 2 /) {
12797:         if ((!defined($cached)) || ($tmp ne 'con_lost')) {
12798: 	    &logthis("<font color=\"blue\">WARNING:".
12799: 		     " Trying to get resource data for ".
12800: 		     $uname." at ".$udom.": ".
12801: 		     $tmp."</font>");
12802:         }
12803:     } elsif ($tmp=~/error: 2 /) {
12804: 	#&EXT_cache_set($udom,$uname);
12805: 	&do_cache_new('userres',$hashid,undef,600);
12806: 	undef($tmp); # not really an error so don't send it back
12807:     }
12808:     return $tmp;
12809: }
12810: #----------------------------------------------- resdata - return resource data
12811: #  Purpose:
12812: #    Return resource data for either users or for a course.
12813: #  Parameters:
12814: #     $name      - Course/user name.
12815: #     $domain    - Name of the domain the user/course is registered on.
12816: #     $type      - Type of thing $name is (must be 'course' or 'user')
12817: #     $mapp      - decluttered URL of enclosing map  
12818: #     $recursed  - Ref to scalar -- set to 1, if nested maps have been recursed.
12819: #     $recurseup - Ref to array of map URLs, starting with map containing
12820: #                  $mapp up through hierarchy of nested maps to top level map.  
12821: #     $courseid  - CourseID (first part of param identifier).
12822: #     $modifier  - Middle part of param identifier.
12823: #     $what      - Last part of param identifier.
12824: #     @which     - Array of names of resources desired.
12825: #  Returns:
12826: #     The value of the first reasource in @which that is found in the
12827: #     resource hash.
12828: #  Exceptional Conditions:
12829: #     If the $type passed in is not valid (not the string 'course' or 
12830: #     'user', an undefined  reference is returned.
12831: #     If none of the resources are found, an undef is returned
12832: sub resdata {
12833:     my ($name,$domain,$type,$mapp,$recursed,$recurseup,$courseid,
12834:         $modifier,$what,@which)=@_;
12835:     my $result;
12836:     if ($type eq 'course') {
12837: 	$result=&get_courseresdata($name,$domain);
12838:     } elsif ($type eq 'user') {
12839: 	$result=&get_userresdata($name,$domain);
12840:     }
12841:     if (!ref($result)) { return $result; }    
12842:     foreach my $item (@which) {
12843:         if ($item->[1] eq 'course') {
12844:             if ((ref($recurseup) eq 'ARRAY') && (ref($recursed) eq 'SCALAR')) {
12845:                 unless ($$recursed) {
12846:                     @{$recurseup} = &get_map_hierarchy($mapp,$courseid);
12847:                     $$recursed = 1;
12848:                 }
12849:                 foreach my $item (@${recurseup}) {
12850:                     my $norecursechk=$courseid.$modifier.$item.'___(all).'.$what;
12851:                     last if (defined($result->{$norecursechk}));
12852:                     my $recursechk=$courseid.$modifier.$item.'___(rec).'.$what;
12853:                     if (defined($result->{$recursechk})) { return [$result->{$recursechk},'map']; }
12854:                 }
12855:             }
12856:         }
12857:         if (defined($result->{$item->[0]})) {
12858: 	    return [$result->{$item->[0]},$item->[1]];
12859: 	}
12860:     }
12861:     return undef;
12862: }
12863: 
12864: sub get_domain_lti {
12865:     my ($cdom,$context) = @_;
12866:     my ($name,$cachename,%lti);
12867:     if ($context eq 'consumer') {
12868:         $name = 'ltitools';
12869:     } elsif ($context eq 'provider') {
12870:         $name = 'lti';
12871:     } elsif ($context eq 'linkprot') {
12872:         $name = 'ltisec';
12873:     } else {
12874:         return %lti;
12875:     }
12876:     if ($context eq 'linkprot') {
12877:         $cachename = $context;
12878:     } else {
12879:         $cachename = $name;
12880:     }
12881:     my ($result,$cached)=&is_cached_new($cachename,$cdom);
12882:     if (defined($cached)) {
12883:         if (ref($result) eq 'HASH') {
12884:             %lti = %{$result};
12885:         }
12886:     } else {
12887:         my %domconfig = &get_dom('configuration',[$name],$cdom);
12888:         if (ref($domconfig{$name}) eq 'HASH') {
12889:             if ($context eq 'linkprot') {
12890:                 if (ref($domconfig{$name}{'linkprot'}) eq 'HASH') {
12891:                     %lti = %{$domconfig{$name}{'linkprot'}};
12892:                 }
12893:             } else {
12894:                 %lti = %{$domconfig{$name}};
12895:             }
12896:         }
12897:         my $cachetime = 24*60*60;
12898:         &do_cache_new($cachename,$cdom,\%lti,$cachetime);
12899:     }
12900:     return %lti;
12901: }
12902: 
12903: sub get_course_lti {
12904:     my ($cnum,$cdom,$context) = @_;
12905:     my ($name,$cachename,%lti);
12906:     if ($context eq 'consumer') {
12907:         $name = 'ltitools';
12908:         $cachename = 'courseltitools';
12909:     } elsif ($context eq 'provider') {
12910:         $name = 'lti';
12911:         $cachename = 'courselti';
12912:     } else {
12913:         return %lti;
12914:     }
12915:     my $hashid=$cdom.'_'.$cnum;
12916:     my ($result,$cached)=&is_cached_new($cachename,$hashid);
12917:     if (defined($cached)) {
12918:         if (ref($result) eq 'HASH') {
12919:             %lti = %{$result};
12920:         }
12921:     } else {
12922:         %lti = &dump($name,$cdom,$cnum,undef,undef,undef,1);
12923:         my $cachetime = 24*60*60;
12924:         &do_cache_new($cachename,$hashid,\%lti,$cachetime);
12925:     }
12926:     return %lti;
12927: }
12928: 
12929: sub courselti_itemid {
12930:     my ($cnum,$cdom,$url,$method,$params,$context) = @_;
12931:     my ($chome,$itemid);
12932:     $chome = &homeserver($cnum,$cdom);
12933:     return if ($chome eq 'no_host');
12934:     if (ref($params) eq 'HASH') {
12935:         my $rep;
12936:         if (grep { $_ eq $chome } current_machine_ids()) {
12937:             $rep = LONCAPA::Lond::crslti_itemid($cdom,$cnum,$url,$method,$params,$perlvar{'lonVersion'});
12938:         } else {
12939:             my $escurl = &escape($url);
12940:             my $escmethod = &escape($method);
12941:             my $items = &freeze_escape($params);
12942:             $rep = &reply("encrypt:lti:$cdom:$cnum:$context:$escurl:$escmethod:$items",$chome);
12943:         }
12944:         unless (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
12945:                 ($rep eq 'unknown_cmd')) {
12946:             $itemid = $rep;
12947:         }
12948:     }
12949:     return $itemid;
12950: }
12951: 
12952: sub domainlti_itemid {
12953:     my ($cdom,$url,$method,$params,$context) = @_;
12954:     my ($primary_id,$itemid);
12955:     $primary_id = &domain($cdom,'primary');
12956:     return if ($primary_id eq '');
12957:     if (ref($params) eq 'HASH') {
12958:         my $rep;
12959:         if (grep { $_ eq $primary_id } current_machine_ids()) {
12960:             $rep = LONCAPA::Lond::domlti_itemid($cdom,$context,$url,$method,$params,$perlvar{'lonVersion'});
12961:         } else {
12962:             my $cnum = '';
12963:             my $escurl = &escape($url);
12964:             my $escmethod = &escape($method);
12965:             my $items = &freeze_escape($params);
12966:             $rep = &reply("encrypt:lti:$cdom:$cnum:$context:$escurl:$escmethod:$items",$primary_id);
12967:         }
12968:         unless (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
12969:                 ($rep eq 'unknown_cmd')) {
12970:             $itemid = $rep;
12971:         }
12972:     }
12973:     return $itemid;
12974: }
12975: 
12976: sub get_ltitools_id {
12977:     my ($context,$cdom,$cnum,$title) = @_;
12978:     my ($lockhash,$tries,$gotlock,$id,$error);
12979: 
12980:     # get lock on ltitools db
12981:     $lockhash = {
12982:                    lock => $env{'user.name'}.
12983:                            ':'.$env{'user.domain'},
12984:                 };
12985:     $tries = 0;
12986:     if ($context eq 'domain') {
12987:         $gotlock = &newput_dom('ltitools',$lockhash,$cdom);
12988:     } else {
12989:         $gotlock = &newput('ltitools',$lockhash,$cdom,$cnum);
12990:     }
12991:     while (($gotlock ne 'ok') && ($tries<10)) {
12992:         $tries ++;
12993:         sleep (0.1);
12994:         if ($context eq 'domain') {
12995:             $gotlock = &newput_dom('ltitools',$lockhash,$cdom);
12996:         } else {
12997:             $gotlock = &newput('ltitools',$lockhash,$cdom,$cnum);
12998:         }
12999:     }
13000:     if ($gotlock eq 'ok') {
13001:         my %currids;
13002:         if ($context eq 'domain') {
13003:             %currids = &dump_dom('ltitools',$cdom);
13004:         } else {
13005:             %currids = &dump('ltitools',$cdom,$cnum);
13006:         }
13007:         if ($currids{'lock'}) {
13008:             delete($currids{'lock'});
13009:             if (keys(%currids)) {
13010:                 my @curr = sort { $a <=> $b } keys(%currids);
13011:                 if ($curr[-1] =~ /^\d+$/) {
13012:                     $id = 1 + $curr[-1];
13013:                 }
13014:             } else {
13015:                 $id = 1;
13016:             }
13017:             if ($id) {
13018:                 if ($context eq 'domain') {
13019:                     unless (&newput_dom('ltitools',{ $id => $title },$cdom) eq 'ok') {
13020:                         $error = 'nostore';
13021:                     }
13022:                 } else {
13023:                     unless (&newput('ltitools',{ $id => $title },$cdom,$cnum) eq 'ok') {
13024:                         $error = 'nostore';
13025:                     }
13026:                 }
13027:             } else {
13028:                 $error = 'nonumber';
13029:             }
13030:         }
13031:         my $dellockoutcome;
13032:         if ($context eq 'domain') {
13033:             $dellockoutcome = &del_dom('ltitools',['lock'],$cdom);
13034:         } else {
13035:             $dellockoutcome = &del('ltitools',['lock'],$cdom,$cnum);
13036:         }
13037:     } else {
13038:         $error = 'nolock';
13039:     }
13040:     return ($id,$error);
13041: }
13042: 
13043: sub count_supptools {
13044:     my ($cnum,$cdom,$ignorecache,$reload)=@_;
13045:     my $hashid=$cnum.':'.$cdom;
13046:     my ($numexttools,$cached);
13047:     unless ($ignorecache) {
13048:         ($numexttools,$cached) = &is_cached_new('supptools',$hashid);
13049:     }
13050:     unless (defined($cached)) {
13051:         my $chome=&homeserver($cnum,$cdom);
13052:         $numexttools = 0;
13053:         unless ($chome eq 'no_host') {
13054:             my ($supplemental) = &Apache::loncommon::get_supplemental($cnum,$cdom,$reload);
13055:             if (ref($supplemental) eq 'HASH') {
13056:                 if ((ref($supplemental->{'ids'}) eq 'HASH') && (ref($supplemental->{'hidden'}) eq 'HASH')) {
13057:                     foreach my $key (keys(%{$supplemental->{'ids'}})) {
13058:                         if ($key =~ m{^/adm/$cdom/$cnum/\d+/ext\.tool$}) {
13059:                             $numexttools ++;
13060:                         }
13061:                     }
13062:                 }
13063:             }
13064:         }
13065:         &do_cache_new('supptools',$hashid,$numexttools,600);
13066:     }
13067:     return $numexttools;
13068: }
13069: 
13070: sub has_unhidden_suppfiles {
13071:     my ($cnum,$cdom,$ignorecache,$possdel)=@_;
13072:     my $hashid=$cnum.':'.$cdom;
13073:     my ($showsupp,$cached);
13074:     unless ($ignorecache) {
13075:         ($showsupp,$cached) = &is_cached_new('showsupp',$hashid);
13076:     }
13077:     unless (defined($cached)) {
13078:         my $chome=&homeserver($cnum,$cdom);
13079:         unless ($chome eq 'no_host') {
13080:             my ($supplemental) = &Apache::loncommon::get_supplemental($cnum,$cdom,$ignorecache,$possdel);
13081:             if (ref($supplemental) eq 'HASH') {
13082:                 if ((ref($supplemental->{'ids'}) eq 'HASH') && (ref($supplemental->{'hidden'}) eq 'HASH')) {
13083:                     foreach my $key (keys(%{$supplemental->{'ids'}})) {
13084:                         next if ($key =~ /\.sequence$/);
13085:                         if (ref($supplemental->{'ids'}->{$key}) eq 'ARRAY') {
13086:                             foreach my $id (@{$supplemental->{'ids'}->{$key}}) {
13087:                                 unless ($supplemental->{'hidden'}->{$id}) {
13088:                                     $showsupp = 1;
13089:                                     last;
13090:                                 }
13091:                             }
13092:                         }
13093:                         last if ($showsupp);
13094:                     }
13095:                 }
13096:             }
13097:         }
13098:         &do_cache_new('showsupp',$hashid,$showsupp,600);
13099:     }
13100:     return $showsupp;
13101: }
13102: 
13103: #
13104: # EXT resource caching routines
13105: #
13106: 
13107: {
13108: # Cache (5 seconds) of map hierarchy for speedup of navmaps display
13109: #
13110: # The course for which we cache
13111: my $cachedmapkey='';
13112: # The cached recursive maps for this course
13113: my %cachedmaps=();
13114: # When this was last done
13115: my $cachedmaptime='';
13116: 
13117: sub clear_EXT_cache_status {
13118:     &delenv('cache.EXT.');
13119: }
13120: 
13121: sub EXT_cache_status {
13122:     my ($target_domain,$target_user) = @_;
13123:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
13124:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
13125:         # We know already the user has no data
13126:         return 1;
13127:     } else {
13128:         return 0;
13129:     }
13130: }
13131: 
13132: sub EXT_cache_set {
13133:     my ($target_domain,$target_user) = @_;
13134:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
13135:     #&appenv({$cachename => time});
13136: }
13137: 
13138: # --------------------------------------------------------- Value of a Variable
13139: sub EXT {
13140: 
13141:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse,$cid,$recurseupref)=@_;
13142:     unless ($varname) { return ''; }
13143:     #get real user name/domain, courseid and symb
13144:     my $courseid;
13145:     my $publicuser;
13146:     if ($symbparm) {
13147: 	$symbparm=&get_symb_from_alias($symbparm);
13148:     }
13149:     if (!($uname && $udom)) {
13150:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
13151:       if (!$symbparm) {	$symbparm=$cursymb; }
13152:     } else {
13153: 	$courseid=$env{'request.course.id'};
13154:     }
13155:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
13156:     my $rest;
13157:     if (defined($therest[0])) {
13158:        $rest=join('.',@therest);
13159:     } else {
13160:        $rest='';
13161:     }
13162: 
13163:     my $qualifierrest=$qualifier;
13164:     if ($rest) { $qualifierrest.='.'.$rest; }
13165:     my $spacequalifierrest=$space;
13166:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
13167:     if ($realm eq 'user') {
13168: # --------------------------------------------------------------- user.resource
13169: 	if ($space eq 'resource') {
13170: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
13171: 		  || defined($Apache::lonhomework::parsing_a_task))
13172: 		 &&
13173: 		 ($symbparm eq &symbread()) ) {
13174: 		# if we are in the middle of processing the resource the
13175: 		# get the value we are planning on committing
13176:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
13177:                     return $Apache::lonhomework::results{$qualifierrest};
13178:                 } else {
13179:                     return $Apache::lonhomework::history{$qualifierrest};
13180:                 }
13181: 	    } else {
13182: 		my %restored;
13183: 		if ($publicuser || $env{'request.state'} eq 'construct') {
13184: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
13185: 		} else {
13186: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
13187: 		}
13188: 		return $restored{$qualifierrest};
13189: 	    }
13190: # ----------------------------------------------------------------- user.access
13191:         } elsif ($space eq 'access') {
13192: 	    # FIXME - not supporting calls for a specific user
13193:             return &allowed($qualifier,$rest);
13194: # ------------------------------------------ user.preferences, user.environment
13195:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
13196: 	    if (($uname eq $env{'user.name'}) &&
13197: 		($udom eq $env{'user.domain'})) {
13198: 		return $env{join('.',('environment',$qualifierrest))};
13199: 	    } else {
13200: 		my %returnhash;
13201: 		if (!$publicuser) {
13202: 		    %returnhash=&userenvironment($udom,$uname,
13203: 						 $qualifierrest);
13204: 		}
13205: 		return $returnhash{$qualifierrest};
13206: 	    }
13207: # ----------------------------------------------------------------- user.course
13208:         } elsif ($space eq 'course') {
13209: 	    # FIXME - not supporting calls for a specific user
13210:             return $env{join('.',('request.course',$qualifier))};
13211: # ------------------------------------------------------------------- user.role
13212:         } elsif ($space eq 'role') {
13213: 	    # FIXME - not supporting calls for a specific user
13214:             my ($role,$where)=split(/\./,$env{'request.role'});
13215:             if ($qualifier eq 'value') {
13216: 		return $role;
13217:             } elsif ($qualifier eq 'extent') {
13218:                 return $where;
13219:             }
13220: # ----------------------------------------------------------------- user.domain
13221:         } elsif ($space eq 'domain') {
13222:             return $udom;
13223: # ------------------------------------------------------------------- user.name
13224:         } elsif ($space eq 'name') {
13225:             return $uname;
13226: # ---------------------------------------------------- Any other user namespace
13227:         } else {
13228: 	    my %reply;
13229: 	    if (!$publicuser) {
13230: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
13231: 	    }
13232: 	    return $reply{$qualifierrest};
13233:         }
13234:     } elsif ($realm eq 'query') {
13235: # ---------------------------------------------- pull stuff out of query string
13236:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
13237: 						[$spacequalifierrest]);
13238: 	return $env{'form.'.$spacequalifierrest}; 
13239:    } elsif ($realm eq 'request') {
13240: # ------------------------------------------------------------- request.browser
13241:         if ($space eq 'browser') {
13242:             return $env{'browser.'.$qualifier};
13243: # ------------------------------------------------------------ request.filename
13244:         } else {
13245:             return $env{'request.'.$spacequalifierrest};
13246:         }
13247:     } elsif ($realm eq 'course') {
13248: # ---------------------------------------------------------- course.description
13249:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
13250:     } elsif ($realm eq 'resource') {
13251: 
13252: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
13253: 	    if (!$symbparm) { $symbparm=&symbread(); }
13254: 	}
13255: 
13256:         if ($qualifier eq '') {
13257: 	    if ($space eq 'title') {
13258: 	        if (!$symbparm) { $symbparm = $env{'request.filename'}; }
13259: 	        return &gettitle($symbparm);
13260: 	    }
13261: 	
13262: 	    if ($space eq 'map') {
13263: 	        my ($map) = &decode_symb($symbparm);
13264: 	        return &symbread($map);
13265: 	    }
13266:             if ($space eq 'maptitle') {
13267:                 my ($map) = &decode_symb($symbparm);
13268:                 return &gettitle($map);
13269:             }
13270: 	    if ($space eq 'filename') {
13271: 	        if ($symbparm) {
13272: 		    return &clutter((&decode_symb($symbparm))[2]);
13273: 	        }
13274: 	        return &hreflocation('',$env{'request.filename'});
13275: 	    }
13276: 
13277:             if ((defined($courseid)) && ($courseid eq $env{'request.course.id'}) && $symbparm) {
13278:                 if ($space eq 'visibleparts') {
13279:                     my $navmap = Apache::lonnavmaps::navmap->new();
13280:                     my $item;
13281:                     if (ref($navmap)) {
13282:                         my $res = $navmap->getBySymb($symbparm);
13283:                         my $parts = $res->parts();
13284:                         if (ref($parts) eq 'ARRAY') {
13285:                             $item = join(',',@{$parts});
13286:                         }
13287:                         undef($navmap);
13288:                     }
13289:                     return $item;
13290:                 }
13291:             }
13292:         }
13293: 
13294: 	my ($section, $group, @groups, @recurseup, $recursed);
13295:         if (ref($recurseupref) eq 'ARRAY') {
13296:             @recurseup = @{$recurseupref};
13297:             $recursed = 1;
13298:         }
13299: 	my ($courselevelm,$courseleveli,$courselevel,$mapp);
13300:         if (($courseid eq '') && ($cid)) {
13301:             $courseid = $cid;
13302:         }
13303: 	if (($symbparm && $courseid) && 
13304: 	    (($courseid eq $env{'request.course.id'}) || ($courseid eq $cid)))  {
13305: 
13306: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
13307: 
13308: # ----------------------------------------------------- Cascading lookup scheme
13309: 	    my $symbp=$symbparm;
13310: 	    $mapp=&deversion((&decode_symb($symbp))[0]);
13311: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
13312:             my $recurseparm=$mapp.'___(rec).'.$spacequalifierrest;
13313: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
13314: 	    if (($env{'user.name'} eq $uname) &&
13315: 		($env{'user.domain'} eq $udom)) {
13316: 		$section=$env{'request.course.sec'};
13317:                 @groups = split(/:/,$env{'request.course.groups'});  
13318:                 @groups=&sort_course_groups($courseid,@groups); 
13319: 	    } else {
13320: 		if (! defined($usection)) {
13321: 		    $section=&getsection($udom,$uname,$courseid);
13322: 		} else {
13323: 		    $section = $usection;
13324: 		}
13325:                 @groups = &get_users_groups($udom,$uname,$courseid);
13326: 	    }
13327: 
13328: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
13329: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
13330:             my $secleveli=$courseid.'.['.$section.'].'.$recurseparm;
13331: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
13332: 
13333: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
13334: 	    my $courselevelr=$courseid.'.'.$symbparm;
13335:             $courseleveli=$courseid.'.'.$recurseparm;
13336: 	    $courselevelm=$courseid.'.'.$mapparm;
13337: 
13338: # ----------------------------------------------------------- first, check user
13339: 
13340: 	    my $userreply=&resdata($uname,$udom,'user',$mapp,\$recursed,
13341:                                    \@recurseup,$courseid,'.',$spacequalifierrest, 
13342: 				       ([$courselevelr,'resource'],
13343: 					[$courselevelm,'map'     ],
13344:                                         [$courseleveli,'map'     ],
13345: 					[$courselevel, 'course'  ]));
13346: 	    if (defined($userreply)) { return &get_reply($userreply); }
13347: 
13348: # ------------------------------------------------ second, check some of course
13349:             my $coursereply;
13350:             if (@groups > 0) {
13351:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
13352:                                        $recurseparm,$mapparm,$spacequalifierrest,
13353:                                        $mapp,\$recursed,\@recurseup);
13354:                 if (defined($coursereply)) { return &get_reply($coursereply); } 
13355:             }
13356: 
13357: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
13358: 				  $env{'course.'.$courseid.'.domain'},
13359: 				  'course',$mapp,\$recursed,\@recurseup,
13360:                                   $courseid,'.['.$section.'].',$spacequalifierrest,
13361: 				  ([$seclevelr,   'resource'],
13362: 				   [$seclevelm,   'map'     ],
13363:                                    [$secleveli,   'map'     ],
13364: 				   [$seclevel,    'course'  ],
13365: 				   [$courselevelr,'resource']));
13366: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
13367: 
13368: # ------------------------------------------------------ third, check map parms
13369: 	    my %parmhash=();
13370: 	    my $thisparm='';
13371: 	    if (tie(%parmhash,'GDBM_File',
13372: 		    $env{'request.course.fn'}.'_parms.db',
13373: 		    &GDBM_READER(),0640)) {
13374: 		$thisparm=$parmhash{$symbparm};
13375: 		untie(%parmhash);
13376: 	    }
13377: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
13378: 	}
13379: # ------------------------------------------ fourth, look in resource metadata
13380:  
13381:         my $what = $spacequalifierrest;
13382: 	$what=~s/\./\_/;
13383: 	my $filename;
13384: 	if (!$symbparm) { $symbparm=&symbread(); }
13385: 	if ($symbparm) {
13386: 	    $filename=(&decode_symb($symbparm))[2];
13387: 	} else {
13388: 	    $filename=$env{'request.filename'};
13389: 	}
13390:         my $toolsymb;
13391:         if (($filename =~ /ext\.tool$/) && ($what ne '0_gradable')) {
13392:             $toolsymb = $symbparm;
13393:         }
13394: 	my $metadata=&metadata($filename,$what,$toolsymb);
13395: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
13396: 	$metadata=&metadata($filename,'parameter_'.$what,$toolsymb);
13397: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
13398: 
13399: # ----------------------------------------------- fifth, look in rest of course
13400: 	if ($symbparm && defined($courseid) && 
13401: 	    $courseid eq $env{'request.course.id'}) {
13402: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
13403: 				     $env{'course.'.$courseid.'.domain'},
13404: 				     'course',$mapp,\$recursed,\@recurseup,
13405:                                      $courseid,'.',$spacequalifierrest,
13406: 				     ([$courselevelm,'map'   ],
13407:                                       [$courseleveli,'map'   ],
13408: 				      [$courselevel, 'course']));
13409: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
13410: 	}
13411: # ------------------------------------------------------------------ Cascade up
13412: 	unless ($space eq '0') {
13413: 	    my @parts=split(/_/,$space);
13414: 	    my $id=pop(@parts);
13415: 	    my $part=join('_',@parts);
13416: 	    if ($part eq '') { $part='0'; }
13417: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
13418: 				 $symbparm,$udom,$uname,$section,1);
13419: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
13420: 	}
13421: 	if ($recurse) { return undef; }
13422: 	my $pack_def=&packages_tab_default($filename,$varname,$toolsymb);
13423: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
13424: # ---------------------------------------------------- Any other user namespace
13425:     } elsif ($realm eq 'environment') {
13426: # ----------------------------------------------------------------- environment
13427: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
13428: 	    return $env{'environment.'.$spacequalifierrest};
13429: 	} else {
13430: 	    if ($uname eq 'anonymous' && $udom eq '') {
13431: 		return '';
13432: 	    }
13433: 	    my %returnhash=&userenvironment($udom,$uname,
13434: 					    $spacequalifierrest);
13435: 	    return $returnhash{$spacequalifierrest};
13436: 	}
13437:     } elsif ($realm eq 'system') {
13438: # ----------------------------------------------------------------- system.time
13439: 	if ($space eq 'time') {
13440: 	    return time;
13441:         }
13442:     } elsif ($realm eq 'server') {
13443: # ----------------------------------------------------------------- system.time
13444: 	if ($space eq 'name') {
13445: 	    return $ENV{'SERVER_NAME'};
13446:         }
13447:     } elsif ($realm eq 'client') {
13448:         if ($space eq 'remote_addr') {
13449:             return &get_requestor_ip();
13450:         }
13451:     }
13452:     return '';
13453: }
13454: 
13455: sub get_reply {
13456:     my ($reply_value) = @_;
13457:     if (ref($reply_value) eq 'ARRAY') {
13458:         if (wantarray) {
13459: 	    return @$reply_value;
13460:         }
13461:         return $reply_value->[0];
13462:     } else {
13463:         return $reply_value;
13464:     }
13465: }
13466: 
13467: sub check_group_parms {
13468:     my ($courseid,$groups,$symbparm,$recurseparm,$mapparm,$what,$mapp,
13469:         $recursed,$recurseupref) = @_;
13470:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$recurseparm,'map'],
13471:                   [$what,'course']);
13472:     my $coursereply;
13473:     foreach my $group (@{$groups}) {
13474:         my @groupitems = ();
13475:         foreach my $level (@levels) {
13476:              my $item = $courseid.'.['.$group.'].'.$level->[0];
13477:              push(@groupitems,[$item,$level->[1]]);
13478:         }
13479:         my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
13480:                                    $env{'course.'.$courseid.'.domain'},
13481:                                    'course',$mapp,$recursed,$recurseupref,
13482:                                    $courseid,'.['.$group.'].',$what,
13483:                                    @groupitems);
13484:         last if (defined($coursereply));
13485:     }
13486:     return $coursereply;
13487: }
13488: 
13489: sub get_map_hierarchy {
13490:     my ($mapname,$courseid) = @_;
13491:     my @recurseup = ();
13492:     if ($mapname) {
13493:         if (($cachedmapkey eq $courseid) &&
13494:             (abs($cachedmaptime-time)<5)) {
13495:             if (ref($cachedmaps{$mapname}) eq 'ARRAY') {
13496:                 return @{$cachedmaps{$mapname}};
13497:             }
13498:         }
13499:         my $navmap = Apache::lonnavmaps::navmap->new();
13500:         if (ref($navmap)) {
13501:             @recurseup = $navmap->recurseup_maps($mapname);
13502:             undef($navmap);
13503:             $cachedmaps{$mapname} = \@recurseup;
13504:             $cachedmaptime=time;
13505:             $cachedmapkey=$courseid;
13506:         }
13507:     }
13508:     return @recurseup;
13509: }
13510: 
13511: }
13512: 
13513: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
13514:     my ($courseid,@groups) = @_;
13515:     @groups = sort(@groups);
13516:     return @groups;
13517: }
13518: 
13519: sub packages_tab_default {
13520:     my ($uri,$varname,$toolsymb)=@_;
13521:     my (undef,$part,$name)=split(/\./,$varname);
13522: 
13523:     my (@extension,@specifics,$do_default);
13524:     foreach my $package (split(/,/,&metadata($uri,'packages',$toolsymb))) {
13525: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
13526: 	if ($pack_type eq 'default') {
13527: 	    $do_default=1;
13528: 	} elsif ($pack_type eq 'extension') {
13529: 	    push(@extension,[$package,$pack_type,$pack_part]);
13530: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
13531: 	    # only look at packages defaults for packages that this id is
13532: 	    push(@specifics,[$package,$pack_type,$pack_part]);
13533: 	}
13534:     }
13535:     # first look for a package that matches the requested part id
13536:     foreach my $package (@specifics) {
13537: 	my (undef,$pack_type,$pack_part)=@{$package};
13538: 	next if ($pack_part ne $part);
13539: 	if (defined($packagetab{"$pack_type&$name&default"})) {
13540: 	    return $packagetab{"$pack_type&$name&default"};
13541: 	}
13542:     }
13543:     # look for any possible matching non extension_ package
13544:     foreach my $package (@specifics) {
13545: 	my (undef,$pack_type,$pack_part)=@{$package};
13546: 	if (defined($packagetab{"$pack_type&$name&default"})) {
13547: 	    return $packagetab{"$pack_type&$name&default"};
13548: 	}
13549: 	if ($pack_type eq 'part') { $pack_part='0'; }
13550: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
13551: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
13552: 	}
13553:     }
13554:     # look for any posible extension_ match
13555:     foreach my $package (@extension) {
13556: 	my ($package,$pack_type)=@{$package};
13557: 	if (defined($packagetab{"$pack_type&$name&default"})) {
13558: 	    return $packagetab{"$pack_type&$name&default"};
13559: 	}
13560: 	if (defined($packagetab{$package."&$name&default"})) {
13561: 	    return $packagetab{$package."&$name&default"};
13562: 	}
13563:     }
13564:     # look for a global default setting
13565:     if ($do_default && defined($packagetab{"default&$name&default"})) {
13566: 	return $packagetab{"default&$name&default"};
13567:     }
13568:     return undef;
13569: }
13570: 
13571: sub add_prefix_and_part {
13572:     my ($prefix,$part)=@_;
13573:     my $keyroot;
13574:     if (defined($prefix) && $prefix !~ /^__/) {
13575: 	# prefix that has a part already
13576: 	$keyroot=$prefix;
13577:     } elsif (defined($prefix)) {
13578: 	# prefix that is missing a part
13579: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
13580:     } else {
13581: 	# no prefix at all
13582: 	if (defined($part)) { $keyroot='_'.$part; }
13583:     }
13584:     return $keyroot;
13585: }
13586: 
13587: # ---------------------------------------------------------------- Get metadata
13588: 
13589: my %metaentry;
13590: my %importedpartids;
13591: my %importedrespids;
13592: sub metadata {
13593:     my ($uri,$what,$toolsymb,$liburi,$prefix,$depthcount)=@_;
13594:     $uri=&declutter($uri);
13595:     # if it is a non metadata possible uri return quickly
13596:     if (($uri eq '') || 
13597: 	(($uri =~ m|^/*adm/|) && 
13598: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard|ext\.tool)$})) ||
13599:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
13600: 	return undef;
13601:     }
13602:     if (($uri =~ /^priv/ || $uri=~m{^home/httpd/html/priv}) 
13603: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
13604: 	return undef;
13605:     }
13606:     my $filename=$uri;
13607:     $uri=~s/\.meta$//;
13608: #
13609: # Is the metadata already cached?
13610: # Look at timestamp of caching
13611: # Everything is cached by the main uri, libraries are never directly cached
13612: #
13613:     if (!defined($liburi)) {
13614: 	my ($result,$cached)=&is_cached_new('meta',$uri);
13615: 	if (defined($cached)) { return $result->{':'.$what}; }
13616:     }
13617: 
13618: #
13619: # If the uri is for an external tool the file from
13620: # which metadata should be retrieved depends on whether
13621: # the tool had been configured to be gradable (set in the Course
13622: # Editor or Resource Editor).
13623: #
13624: # If a valid symb has been included as the third arg in the call
13625: # to &metadata() that can be used to retrieve the value of
13626: # parameter_0_gradable set for the resource, and included in the
13627: # uploaded map containing the tool. The value is retrieved via
13628: # &EXT(), if a valid symb is available.  Otherwise the value of
13629: # gradable in the exttool_$marker.db file for the tool instance
13630: # is retrieved via &get().
13631: #
13632: # When lonuserstate::traceroute() calls lonnet::EXT() for 
13633: # hiddenresource and encrypturl (during course initialization)
13634: # the map-level parameter for resource.0.gradable included in the 
13635: # uploaded map containing the tool will not yet have been stored
13636: # in the user_course_parms.db file for the user's session, so in 
13637: # this case fall back to retrieving gradable status from the
13638: # exttool_$marker.db file.
13639: #
13640: # In order to avoid an infinite loop, &metadata() will return
13641: # before a call to &EXT(), if the uri is for an external tool
13642: # and the $what for which metadata is being requested is
13643: # parameter_0_gradable or 0_gradable.
13644: #
13645: 
13646:     if ($uri =~ /ext\.tool$/) {
13647:         if (($what eq 'parameter_0_gradable') || ($what eq '0_gradable')) {
13648:             return;
13649:         } else {
13650:             my ($checked,$use_passback);
13651:             if ($toolsymb ne '') {
13652:                 (undef,undef,my $tooluri) = &decode_symb($toolsymb);
13653:                 if (($tooluri eq $uri) && (&EXT('resource.0.gradable',$toolsymb))) {
13654:                     $checked = 1;
13655:                     if (&EXT('resource.0.gradable',$toolsymb) =~ /^yes$/i) {
13656:                         $use_passback = 1;
13657:                     }
13658:                 }
13659:             }
13660:             unless ($checked) {
13661:                 my ($ignore,$cdom,$cnum,$marker) = split(m{/},$uri);
13662:                 $marker=~s/\D//g;
13663:                 if ($marker) {
13664:                     my %toolsettings=&get('exttool_'.$marker,['gradable'],$cdom,$cnum);
13665:                     $use_passback = $toolsettings{'gradable'};
13666:                 }
13667:             }
13668:             if ($use_passback) {
13669:                 $filename = '/home/httpd/html/res/lib/templates/LTIpassback.tool';
13670:             } else {
13671:                 $filename = '/home/httpd/html/res/lib/templates/LTIstandard.tool';
13672:             }
13673:         }
13674:     }
13675: 
13676:     {
13677: # Imported parts would go here
13678:         my @origfiletagids=();
13679:         my $importedparts=0;
13680: 
13681: # Imported responseids would go here
13682:         my $importedresponses=0;
13683: #
13684: # Is this a recursive call for a library?
13685: #
13686: #	if (! exists($metacache{$uri})) {
13687: #	    $metacache{$uri}={};
13688: #	}
13689: 	my $cachetime = 60*60;
13690:         if ($liburi) {
13691: 	    $liburi=&declutter($liburi);
13692:             $filename=$liburi;
13693:         } else {
13694: 	    &devalidate_cache_new('meta',$uri);
13695: 	    undef(%metaentry);
13696: 	}
13697:         my %metathesekeys=();
13698:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
13699: 	my $metastring;
13700: 	if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
13701: 	    my $which = &hreflocation('','/'.($liburi || $uri));
13702: 	    $metastring = 
13703: 		&Apache::lonnet::ssi_body($which,
13704: 					  ('grade_target' => 'meta'));
13705: 	    $cachetime = 1; # only want this cached in the child not long term
13706: 	} elsif (($uri !~ m -^(editupload)/-) && 
13707:                  ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
13708: 	    my $file=&filelocation('',&clutter($filename));
13709: 	    #push(@{$metaentry{$uri.'.file'}},$file);
13710: 	    $metastring=&getfile($file);
13711: 	}
13712:         my $parser=HTML::LCParser->new(\$metastring);
13713:         my $token;
13714:         undef %metathesekeys;
13715:         while ($token=$parser->get_token) {
13716: 	    if ($token->[0] eq 'S') {
13717: 		if (defined($token->[2]->{'package'})) {
13718: #
13719: # This is a package - get package info
13720: #
13721: 		    my $package=$token->[2]->{'package'};
13722: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
13723: 		    if (defined($token->[2]->{'id'})) { 
13724: 			$keyroot.='_'.$token->[2]->{'id'}; 
13725: 		    }
13726: 		    if ($metaentry{':packages'}) {
13727: 			$metaentry{':packages'}.=','.$package.$keyroot;
13728: 		    } else {
13729: 			$metaentry{':packages'}=$package.$keyroot;
13730: 		    }
13731: 		    foreach my $pack_entry (keys(%packagetab)) {
13732: 			my $part=$keyroot;
13733: 			$part=~s/^\_//;
13734: 			if ($pack_entry=~/^\Q$package\E\&/ || 
13735: 			    $pack_entry=~/^\Q$package\E_0\&/) {
13736: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
13737: 			    # ignore package.tab specified default values
13738:                             # here &package_tab_default() will fetch those
13739: 			    if ($subp eq 'default') { next; }
13740: 			    my $value=$packagetab{$pack_entry};
13741: 			    my $unikey;
13742: 			    if ($pack =~ /_0$/) {
13743: 				$unikey='parameter_0_'.$name;
13744: 				$part=0;
13745: 			    } else {
13746: 				$unikey='parameter'.$keyroot.'_'.$name;
13747: 			    }
13748: 			    if ($subp eq 'display') {
13749: 				$value.=' [Part: '.$part.']';
13750: 			    }
13751: 			    $metaentry{':'.$unikey.'.part'}=$part;
13752: 			    $metathesekeys{$unikey}=1;
13753: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
13754: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
13755: 			    }
13756: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
13757: 				$metaentry{':'.$unikey}=
13758: 				    $metaentry{':'.$unikey.'.default'};
13759: 			    }
13760: 			}
13761: 		    }
13762: 		} else {
13763: #
13764: # This is not a package - some other kind of start tag
13765: #
13766: 		    my $entry=$token->[1];
13767: 		    my $unikey='';
13768: 
13769: 		    if ($entry eq 'import') {
13770: #
13771: # Importing a library here
13772: #
13773:                         my $location=$parser->get_text('/import');
13774:                         my $dir=$filename;
13775:                         $dir=~s|[^/]*$||;
13776:                         $location=&filelocation($dir,$location);
13777: 
13778:                         my $importid=$token->[2]->{'id'};
13779:                         my $importmode=$token->[2]->{'importmode'};
13780: #
13781: # Check metadata for imported file to
13782: # see if it contained response items
13783: #
13784:                         my ($origfile,@libfilekeys);
13785:                         my %currmetaentry = %metaentry;
13786:                         @libfilekeys = split(/,/,&metadata($location,'keys',undef,undef,undef,
13787:                                                            $depthcount+1));
13788:                         if (grep(/^responseorder$/,@libfilekeys)) {
13789:                             my $libresponseorder = &metadata($location,'responseorder',undef,undef,
13790:                                                              undef,$depthcount+1);
13791:                             if ($libresponseorder ne '') {
13792:                                 if ($#origfiletagids<0) {
13793:                                     undef(%importedrespids);
13794:                                     undef(%importedpartids);
13795:                                 }
13796:                                 my @respids = split(/\s*,\s*/,$libresponseorder);
13797:                                 if (@respids) {
13798:                                     $importedrespids{$importid} = join(',',map { $importid.'_'.$_ } @respids);
13799:                                 }
13800:                                 if ($importedrespids{$importid} ne '') {
13801:                                     $importedresponses = 1;
13802: # We need to get the original file and the imported file to get the response order correct
13803: # Load and inspect original file
13804:                                     if ($#origfiletagids<0) {
13805:                                         my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
13806:                                         $origfile=&getfile($origfilelocation);
13807:                                         @origfiletagids=($origfile=~/<((?:\w+)response|import|part)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
13808:                                     }
13809:                                 }
13810:                             }
13811:                         }
13812: # Do not overwrite contents of %metaentry hash for resource itself with 
13813: # hash populated for imported library file
13814:                         %metaentry = %currmetaentry;
13815:                         undef(%currmetaentry);
13816:                         if ($importmode eq 'part') {
13817: # Import as part(s)
13818:                            $importedparts=1;
13819: # We need to get the original file and the imported file to get the part order correct
13820: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
13821: # Load and inspect original file if we didn't do that already
13822:                            if ($#origfiletagids<0) {
13823:                                undef(%importedrespids);
13824:                                undef(%importedpartids);
13825:                                if ($origfile eq '') {
13826:                                    my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
13827:                                    $origfile=&getfile($origfilelocation);
13828:                                    @origfiletagids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
13829:                                }
13830:                            }
13831:                            my @impfilepartids;
13832: # If <partorder> tag is included in metadata for the imported file
13833: # get the parts in the imported file from that.
13834:                            if (grep(/^partorder$/,@libfilekeys)) {
13835:                                %currmetaentry = %metaentry;
13836:                                my $libpartorder = &metadata($location,'partorder',undef,undef,undef,
13837:                                                             $depthcount+1);
13838:                                %metaentry = %currmetaentry;
13839:                                undef(%currmetaentry);
13840:                                if ($libpartorder ne '') {
13841:                                    @impfilepartids=split(/\s*,\s*/,$libpartorder);
13842:                                }
13843:                            } else {
13844: # If no <partorder> tag available, load and inspect imported file
13845:                                my $impfile=&getfile($location);
13846:                                @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
13847:                            }
13848:                            if ($#impfilepartids>=0) {
13849: # This problem had parts
13850:                                $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
13851:                            } else {
13852: # Importing by turning a single problem into a problem part
13853: # It gets the import-tags ID as part-ID
13854:                                $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
13855:                                $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
13856:                            }
13857:                         } else {
13858: # Import as problem or as normal import
13859:                             $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
13860:                             unless ($importmode eq 'problem') {
13861: # Normal import
13862:                                 if (defined($token->[2]->{'id'})) {
13863:                                     $unikey.='_'.$token->[2]->{'id'};
13864:                                 }
13865:                             }
13866: # Check metadata for imported file to
13867: # see if it contained parts
13868:                             if (grep(/^partorder$/,@libfilekeys)) {
13869:                                 %currmetaentry = %metaentry;
13870:                                 my $libpartorder = &metadata($location,'partorder',undef,undef,undef,
13871:                                                              $depthcount+1);
13872:                                 %metaentry = %currmetaentry;
13873:                                 undef(%currmetaentry);
13874:                                 if ($libpartorder ne '') {
13875:                                     $importedparts = 1;
13876:                                     $importedpartids{$token->[2]->{'id'}}=$libpartorder;
13877:                                 }
13878:                             }
13879:                         }
13880: 			if ($depthcount<20) {
13881: 			    my $metadata = 
13882: 				&metadata($uri,'keys',$toolsymb,$location,$unikey,
13883: 					  $depthcount+1);
13884: 			    foreach my $meta (split(',',$metadata)) {
13885: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
13886: 				$metathesekeys{$meta}=1;
13887: 			    }
13888:                         }
13889: 		    } else {
13890: #
13891: # Not importing, some other kind of non-package, non-library start tag
13892: # 
13893:                         $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
13894:                         if (defined($token->[2]->{'id'})) {
13895:                             $unikey.='_'.$token->[2]->{'id'};
13896:                         }
13897: 			if (defined($token->[2]->{'name'})) { 
13898: 			    $unikey.='_'.$token->[2]->{'name'}; 
13899: 			}
13900: 			$metathesekeys{$unikey}=1;
13901: 			foreach my $param (@{$token->[3]}) {
13902: 			    $metaentry{':'.$unikey.'.'.$param} =
13903: 				$token->[2]->{$param};
13904: 			}
13905: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
13906: 			my $default=$metaentry{':'.$unikey.'.default'};
13907: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
13908: 		 # only ws inside the tag, and not in default, so use default
13909: 		 # as value
13910: 			    $metaentry{':'.$unikey}=$default;
13911: 			} elsif ( $internaltext =~ /\S/ ) {
13912: 		  # something interesting inside the tag
13913: 			    $metaentry{':'.$unikey}=$internaltext;
13914: 			} else {
13915: 		  # no interesting values, don't set a default
13916: 			}
13917: # end of not-a-package not-a-library import
13918: 		    }
13919: # end of not-a-package start tag
13920: 		}
13921: # the next is the end of "start tag"
13922: 	    }
13923: 	}
13924: 	my ($extension) = ($uri =~ /\.(\w+)$/);
13925: 	$extension = lc($extension);
13926: 	if ($extension eq 'htm') { $extension='html'; }
13927: 
13928: 	foreach my $key (keys(%packagetab)) {
13929: 	    #no specific packages #how's our extension
13930: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
13931: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
13932: 					 \%metathesekeys);
13933: 	}
13934: 
13935: 	if (!exists($metaentry{':packages'})
13936: 	    || $packagetab{"import_defaults&extension_$extension"}) {
13937: 	    foreach my $key (keys(%packagetab)) {
13938: 		#no specific packages well let's get default then
13939: 		if ($key!~/^default&/) { next; }
13940: 		&metadata_create_package_def($uri,$key,'default',
13941: 					     \%metathesekeys);
13942: 	    }
13943: 	}
13944: # are there custom rights to evaluate
13945: 	if ($metaentry{':copyright'} eq 'custom') {
13946: 
13947:     #
13948:     # Importing a rights file here
13949:     #
13950: 	    unless ($depthcount) {
13951: 		my $location=$metaentry{':customdistributionfile'};
13952: 		my $dir=$filename;
13953: 		$dir=~s|[^/]*$||;
13954: 		$location=&filelocation($dir,$location);
13955: 		my $rights_metadata =
13956: 		    &metadata($uri,'keys',$toolsymb,$location,'_rights',
13957: 			      $depthcount+1);
13958: 		foreach my $rights (split(',',$rights_metadata)) {
13959: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
13960: 		    $metathesekeys{$rights}=1;
13961: 		}
13962: 	    }
13963: 	}
13964: 	# uniqifiy package listing
13965: 	my %seen;
13966: 	my @uniq_packages =
13967: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
13968: 	$metaentry{':packages'} = join(',',@uniq_packages);
13969: 
13970:         if (($importedresponses) || ($importedparts)) {
13971:             if ($importedparts) {
13972: # We had imported parts and need to rebuild partorder
13973:                 $metaentry{':partorder'}='';
13974:                 $metathesekeys{'partorder'}=1;
13975:             }
13976:             if ($importedresponses) {
13977: # We had imported responses and need to rebuil responseorder
13978:                 $metaentry{':responseorder'}='';
13979:                 $metathesekeys{'responseorder'}=1;
13980:             }
13981:             for (my $index=0;$index<$#origfiletagids;$index+=2) {
13982:                 my $origid = $origfiletagids[$index+1];
13983:                 if ($origfiletagids[$index] eq 'part') {
13984: # Original part, part of the problem
13985:                     if ($importedparts) {
13986:                         $metaentry{':partorder'}.=','.$origid;
13987:                     }
13988:                 } elsif ($origfiletagids[$index] eq 'import') {
13989:                     if ($importedparts) {
13990: # We have imported parts at this position
13991:                         if ($importedpartids{$origid} ne '') {
13992:                             $metaentry{':partorder'}.=','.$importedpartids{$origid};
13993:                         }
13994:                     }
13995:                     if ($importedresponses) {
13996: # We have imported responses at this position
13997:                         if ($importedrespids{$origid} ne '') {
13998:                             $metaentry{':responseorder'}.=','.$importedrespids{$origid};
13999:                         }
14000:                     }
14001:                 } else {
14002: # Original response item, part of the problem
14003:                     if ($importedresponses) {
14004:                         $metaentry{':responseorder'}.=','.$origid;
14005:                     }
14006:                 }
14007:             }
14008:             if ($importedparts) {
14009:                 $metaentry{':partorder'}=~s/^\,//;
14010:             }
14011:             if ($importedresponses) {
14012:                 $metaentry{':responseorder'}=~s/^\,//;
14013:             }
14014:         }
14015: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
14016: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
14017: 	$metaentry{':allpossiblekeys'}=join(',',keys(%metathesekeys));
14018:         unless ($liburi) {
14019: 	    &do_cache_new('meta',$uri,\%metaentry,$cachetime);
14020:         }
14021: # this is the end of "was not already recently cached
14022:     }
14023:     return $metaentry{':'.$what};
14024: }
14025: 
14026: sub metadata_create_package_def {
14027:     my ($uri,$key,$package,$metathesekeys)=@_;
14028:     my ($pack,$name,$subp)=split(/\&/,$key);
14029:     if ($subp eq 'default') { next; }
14030:     
14031:     if (defined($metaentry{':packages'})) {
14032: 	$metaentry{':packages'}.=','.$package;
14033:     } else {
14034: 	$metaentry{':packages'}=$package;
14035:     }
14036:     my $value=$packagetab{$key};
14037:     my $unikey;
14038:     $unikey='parameter_0_'.$name;
14039:     $metaentry{':'.$unikey.'.part'}=0;
14040:     $$metathesekeys{$unikey}=1;
14041:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
14042: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
14043:     }
14044:     if (defined($metaentry{':'.$unikey.'.default'})) {
14045: 	$metaentry{':'.$unikey}=
14046: 	    $metaentry{':'.$unikey.'.default'};
14047:     }
14048: }
14049: 
14050: sub metadata_generate_part0 {
14051:     my ($metadata,$metacache,$uri) = @_;
14052:     my %allnames;
14053:     foreach my $metakey (keys(%$metadata)) {
14054: 	if ($metakey=~/^parameter\_(.*)/) {
14055: 	  my $part=$$metacache{':'.$metakey.'.part'};
14056: 	  my $name=$$metacache{':'.$metakey.'.name'};
14057: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
14058: 	    $allnames{$name}=$part;
14059: 	  }
14060: 	}
14061:     }
14062:     foreach my $name (keys(%allnames)) {
14063:       $$metadata{"parameter_0_$name"}=1;
14064:       my $key=":parameter_0_$name";
14065:       $$metacache{"$key.part"}='0';
14066:       $$metacache{"$key.name"}=$name;
14067:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
14068: 					   $allnames{$name}.'_'.$name.
14069: 					   '.type'};
14070:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
14071: 			     '.display'};
14072:       my $expr='[Part: '.$allnames{$name}.']';
14073:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
14074:       $$metacache{"$key.display"}=$olddis;
14075:     }
14076: }
14077: 
14078: # ------------------------------------------------------ Devalidate title cache
14079: 
14080: sub devalidate_title_cache {
14081:     my ($url)=@_;
14082:     if (!$env{'request.course.id'}) { return; }
14083:     my $symb=&symbread($url);
14084:     if (!$symb) { return; }
14085:     my $key=$env{'request.course.id'}."\0".$symb;
14086:     &devalidate_cache_new('title',$key);
14087: }
14088: 
14089: # ------------------------------------------------- Get the title of a course
14090: 
14091: sub current_course_title {
14092:     return $env{ 'course.' . $env{'request.course.id'} . '.description' };
14093: }
14094: # ------------------------------------------------- Get the title of a resource
14095: 
14096: sub gettitle {
14097:     my $urlsymb=shift;
14098:     my $symb=&symbread($urlsymb);
14099:     if ($symb) {
14100: 	my $key=$env{'request.course.id'}."\0".$symb;
14101: 	my ($result,$cached)=&is_cached_new('title',$key);
14102: 	if (defined($cached)) { 
14103: 	    return $result;
14104: 	}
14105: 	my ($map,$resid,$url)=&decode_symb($symb);
14106: 	my $title='';
14107: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
14108: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
14109: 	} else {
14110: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
14111: 		    &GDBM_READER(),0640)) {
14112: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
14113: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
14114: 		untie(%bighash);
14115: 	    }
14116: 	}
14117: 	$title=~s/\&colon\;/\:/gs;
14118: 	if ($title) {
14119: # Remember both $symb and $title for dynamic metadata
14120:             $accesshash{$symb.'___crstitle'}=$title;
14121:             $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
14122: # Cache this title and then return it
14123: 	    return &do_cache_new('title',$key,$title,600);
14124: 	}
14125: 	$urlsymb=$url;
14126:     }
14127:     my $title=&metadata($urlsymb,'title');
14128:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
14129:     return $title;
14130: }
14131: 
14132: sub get_slot {
14133:     my ($which,$cnum,$cdom)=@_;
14134:     if (!$cnum || !$cdom) {
14135: 	(undef,my $courseid)=&whichuser();
14136: 	$cdom=$env{'course.'.$courseid.'.domain'};
14137: 	$cnum=$env{'course.'.$courseid.'.num'};
14138:     }
14139:     my $key=join("\0",'slots',$cdom,$cnum,$which);
14140:     my %slotinfo;
14141:     if (exists($remembered{$key})) {
14142: 	$slotinfo{$which} = $remembered{$key};
14143:     } else {
14144: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
14145: 	&Apache::lonhomework::showhash(%slotinfo);
14146: 	my ($tmp)=keys(%slotinfo);
14147: 	if ($tmp=~/^error:/) { return (); }
14148: 	$remembered{$key} = $slotinfo{$which};
14149:     }
14150:     if (ref($slotinfo{$which}) eq 'HASH') {
14151: 	return %{$slotinfo{$which}};
14152:     }
14153:     return $slotinfo{$which};
14154: }
14155: 
14156: sub get_reservable_slots {
14157:     my ($cnum,$cdom,$uname,$udom) = @_;
14158:     my $now = time;
14159:     my $reservable_info;
14160:     my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
14161:     if (exists($remembered{$key})) {
14162:         $reservable_info = $remembered{$key};
14163:     } else {
14164:         my %resv;
14165:         ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
14166:         &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
14167:         $reservable_info = \%resv;
14168:         $remembered{$key} = $reservable_info;
14169:     }
14170:     return $reservable_info;
14171: }
14172: 
14173: sub get_course_slots {
14174:     my ($cnum,$cdom) = @_;
14175:     my $hashid=$cnum.':'.$cdom;
14176:     my ($result,$cached) = &is_cached_new('allslots',$hashid);
14177:     if (defined($cached)) {
14178:         if (ref($result) eq 'HASH') {
14179:             return %{$result};
14180:         }
14181:     } else {
14182:         my %slots=&dump('slots',$cdom,$cnum);
14183:         my ($tmp) = keys(%slots);
14184:         if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
14185:             &do_cache_new('allslots',$hashid,\%slots,600);
14186:             return %slots;
14187:         }
14188:     }
14189:     return;
14190: }
14191: 
14192: sub devalidate_slots_cache {
14193:     my ($cnum,$cdom)=@_;
14194:     my $hashid=$cnum.':'.$cdom;
14195:     &devalidate_cache_new('allslots',$hashid);
14196: }
14197: 
14198: sub get_coursechange {
14199:     my ($cdom,$cnum) = @_;
14200:     if ($cdom eq '' || $cnum eq '') {
14201:         return unless ($env{'request.course.id'});
14202:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
14203:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
14204:     }
14205:     my $hashid=$cdom.'_'.$cnum;
14206:     my ($change,$cached)=&is_cached_new('crschange',$hashid);
14207:     if ((defined($cached)) && ($change ne '')) {
14208:         return $change;
14209:     } else {
14210:         my %crshash;
14211:         %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
14212:         if ($crshash{'internal.contentchange'} eq '') {
14213:             $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
14214:             if ($change eq '') {
14215:                 %crshash = &get('environment',['internal.created'],$cdom,$cnum);
14216:                 $change = $crshash{'internal.created'};
14217:             }
14218:         } else {
14219:             $change = $crshash{'internal.contentchange'};
14220:         }
14221:         my $cachetime = 600;
14222:         &do_cache_new('crschange',$hashid,$change,$cachetime);
14223:     }
14224:     return $change;
14225: }
14226: 
14227: sub devalidate_coursechange_cache {
14228:     my ($cdom,$cnum)=@_;
14229:     my $hashid=$cdom.'_'.$cnum;
14230:     &devalidate_cache_new('crschange',$hashid);
14231: }
14232: 
14233: sub get_suppchange {
14234:     my ($cdom,$cnum) = @_;
14235:     if ($cdom eq '' || $cnum eq '') {
14236:         return unless ($env{'request.course.id'});
14237:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
14238:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
14239:     }
14240:     my $hashid=$cdom.'_'.$cnum;
14241:     my ($change,$cached)=&is_cached_new('suppchange',$hashid);
14242:     if ((defined($cached)) && ($change ne '')) {
14243:         return $change;
14244:     } else {
14245:         my %crshash = &get('environment',['internal.supplementalchange'],$cdom,$cnum);
14246:         if ($crshash{'internal.supplementalchange'} eq '') {
14247:             $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
14248:             if ($change eq '') {
14249:                 %crshash = &get('environment',['internal.created'],$cdom,$cnum);
14250:                 $change = $crshash{'internal.created'};
14251:             }
14252:         } else {
14253:             $change = $crshash{'internal.supplementalchange'};
14254:         }
14255:         my $cachetime = 600;
14256:         &do_cache_new('suppchange',$hashid,$change,$cachetime);
14257:     }
14258:     return $change;
14259: }
14260: 
14261: sub devalidate_suppchange_cache {
14262:     my ($cdom,$cnum)=@_;
14263:     my $hashid=$cdom.'_'.$cnum;
14264:     &devalidate_cache_new('suppchange',$hashid);
14265: }
14266: 
14267: sub update_supp_caches {
14268:     my ($cdom,$cnum) = @_;
14269:     my %servers = &internet_dom_servers($cdom);
14270:     my @ids=&current_machine_ids();
14271:     foreach my $server (keys(%servers)) {
14272:         next if (grep(/^\Q$server\E$/,@ids));
14273:         my $hashid=$cnum.':'.$cdom;
14274:         my $cachekey = &escape('showsupp').':'.&escape($hashid);
14275:         &remote_devalidate_cache($server,[$cachekey]);
14276:     }
14277:     &has_unhidden_suppfiles($cnum,$cdom,1,1);
14278:     &count_supptools($cnum,$cdom,1);
14279:     my $now = time;
14280:     if ($env{'request.course.id'} eq $cdom.'_'.$cnum) {
14281:         &Apache::lonnet::appenv({'request.course.suppupdated' => $now});
14282:     }
14283:     &put('environment',{'internal.supplementalchange' => $now},
14284:          $cdom,$cnum);
14285:     &Apache::lonnet::appenv(
14286:         {'course.'.$cdom.'_'.$cnum.'.internal.supplementalchange' => $now});
14287:     &do_cache_new('suppchange',$cdom.'_'.$cnum,$now,600);
14288: }
14289: 
14290: # ------------------------------------------------- Update symbolic store links
14291: 
14292: sub symblist {
14293:     my ($mapname,%newhash)=@_;
14294:     $mapname=&deversion(&declutter($mapname));
14295:     my %hash;
14296:     if (($env{'request.course.fn'}) && (%newhash)) {
14297:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
14298:                       &GDBM_WRCREAT(),0640)) {
14299: 	    foreach my $url (keys(%newhash)) {
14300: 		next if ($url eq 'last_known'
14301: 			 && $env{'form.no_update_last_known'});
14302: 		$hash{declutter($url)}=&encode_symb($mapname,
14303: 						    $newhash{$url}->[1],
14304: 						    $newhash{$url}->[0]);
14305:             }
14306:             if (untie(%hash)) {
14307: 		return 'ok';
14308:             }
14309:         }
14310:     }
14311:     return 'error';
14312: }
14313: 
14314: # --------------------------------------------------------------- Verify a symb
14315: 
14316: sub symbverify {
14317:     my ($symb,$thisurl,$encstate)=@_;
14318:     my $thisfn=$thisurl;
14319:     $thisfn=&declutter($thisfn);
14320: # direct jump to resource in page or to a sequence - will construct own symbs
14321:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
14322: # check URL part
14323:     my ($map,$resid,$url)=&decode_symb($symb);
14324: 
14325:     unless ($url eq $thisfn) { return 0; }
14326: 
14327:     $symb=&symbclean($symb);
14328:     $thisurl=&deversion($thisurl);
14329:     $thisfn=&deversion($thisfn);
14330: 
14331:     my %bighash;
14332:     my $okay=0;
14333: 
14334:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
14335:                             &GDBM_READER(),0640)) {
14336:         if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
14337:             $thisurl =~ s/\?.+$//;
14338:             if ($map =~ m{^uploaded/.+\.page$}) {
14339:                 $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
14340:                 $thisurl =~ s{^\Qhttp://https://\E}{https://};
14341:             }
14342:         }
14343:         my $ids;
14344:         if ($map =~ m{^uploaded/.+\.page$}) {
14345:             $ids=$bighash{'ids_'.&clutter_with_no_wrapper($thisurl)};
14346:         } else {
14347:             $ids=$bighash{'ids_'.&clutter($thisurl)};
14348:         }
14349:         unless ($ids) {
14350:             my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;  
14351:             $ids=$bighash{$idkey};
14352:         }
14353:         if ($ids) {
14354: # ------------------------------------------------------------------- Has ID(s)
14355:             if ($thisfn =~ m{^/adm/wrapper/ext/}) {
14356:                 $symb =~ s/\?.+$//;
14357:             }
14358: 	    foreach my $id (split(/\,/,$ids)) {
14359: 	       my ($mapid,$resid)=split(/\./,$id);
14360:                if (
14361:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
14362:    eq $symb) {
14363:                    if (ref($encstate)) {
14364:                        $$encstate = $bighash{'encrypted_'.$id};
14365:                    }
14366: 		   if (($env{'request.role.adv'}) ||
14367: 		       ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
14368:                        ($thisurl eq '/adm/navmaps')) {
14369: 		       $okay=1;
14370:                        last;
14371: 		   }
14372: 	       }
14373: 	   }
14374:         }
14375: 	untie(%bighash);
14376:     }
14377:     return $okay;
14378: }
14379: 
14380: # --------------------------------------------------------------- Clean-up symb
14381: 
14382: sub symbclean {
14383:     my $symb=shift;
14384:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
14385: # remove version from map
14386:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
14387: 
14388: # remove version from URL
14389:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
14390: 
14391: # remove wrapper
14392: 
14393:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
14394:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
14395:     return $symb;
14396: }
14397: 
14398: # ---------------------------------------------- Split symb to find map and url
14399: 
14400: sub encode_symb {
14401:     my ($map,$resid,$url)=@_;
14402:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
14403: }
14404: 
14405: sub decode_symb {
14406:     my $symb=shift;
14407:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
14408:     my ($map,$resid,$url)=split(/___/,$symb);
14409:     return (&fixversion($map),$resid,&fixversion($url));
14410: }
14411: 
14412: sub fixversion {
14413:     my $fn=shift;
14414:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
14415:     my %bighash;
14416:     my $uri=&clutter($fn);
14417:     my $key=$env{'request.course.id'}.'_'.$uri;
14418: # is this cached?
14419:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
14420:     if (defined($cached)) { return $result; }
14421: # unfortunately not cached, or expired
14422:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
14423: 	    &GDBM_READER(),0640)) {
14424:  	if ($bighash{'version_'.$uri}) {
14425:  	    my $version=$bighash{'version_'.$uri};
14426:  	    unless (($version eq 'mostrecent') || 
14427: 		    ($version==&getversion($uri))) {
14428:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
14429:  	    }
14430:  	}
14431:  	untie %bighash;
14432:     }
14433:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
14434: }
14435: 
14436: sub deversion {
14437:     my $url=shift;
14438:     $url=~s/\.\d+\.(\w+)$/\.$1/;
14439:     return $url;
14440: }
14441: 
14442: # ------------------------------------------------------ Return symb list entry
14443: 
14444: sub symbread {
14445:     my ($thisfn,$donotrecurse,$ignorecachednull,$checkforblock,$possibles,
14446:         $ignoresymbdb,$noenccheck)=@_;
14447:     my $cache_str='request.symbread.cached.'.$thisfn;
14448:     if (defined($env{$cache_str})) {
14449:         unless (ref($possibles) eq 'HASH') {
14450:             if ($ignorecachednull) {
14451:                 return $env{$cache_str} unless ($env{$cache_str} eq '');
14452:             } else {
14453:                 return $env{$cache_str};
14454:             }
14455:         }
14456:     }
14457: # no filename provided? try from environment
14458:     unless ($thisfn) {
14459:         if ($env{'request.symb'}) {
14460:             return $env{$cache_str}=&symbclean($env{'request.symb'});
14461: 	}
14462: 	$thisfn=$env{'request.filename'};
14463:     }
14464:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
14465: # is that filename actually a symb? Verify, clean, and return
14466:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
14467: 	if (&symbverify($thisfn,$1)) {
14468: 	    return $env{$cache_str}=&symbclean($thisfn);
14469: 	}
14470:     }
14471:     $thisfn=declutter($thisfn);
14472:     my %hash;
14473:     my %bighash;
14474:     my $syval='';
14475:     if (($env{'request.course.fn'}) && ($thisfn)) {
14476:         unless ($ignoresymbdb) {
14477:             if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
14478:                           &GDBM_READER(),0640)) {
14479: 	        $syval=$hash{$thisfn};
14480:                 untie(%hash);
14481:             }
14482:             if ($syval && $checkforblock) {
14483:                 my @blockers = &has_comm_blocking('bre',$syval,$thisfn,$ignoresymbdb,$noenccheck);
14484:                 if (@blockers) {
14485:                     $syval='';
14486:                 }
14487:             }
14488:         }
14489: # ---------------------------------------------------------- There was an entry
14490:         if ($syval) {
14491: 	    #unless ($syval=~/\_\d+$/) {
14492: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
14493: 		    #&appenv({'request.ambiguous' => $thisfn});
14494: 		    #return $env{$cache_str}='';
14495: 		#}    
14496: 		#$syval.=$1;
14497: 	    #}
14498:         } else {
14499: # ------------------------------------------------------- Was not in symb table
14500:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
14501:                             &GDBM_READER(),0640)) {
14502: # ---------------------------------------------- Get ID(s) for current resource
14503:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
14504:               unless ($ids) { 
14505:                  $ids=$bighash{'ids_/'.$thisfn};
14506:               }
14507:               unless ($ids) {
14508: # alias?
14509: 		  $ids=$bighash{'mapalias_'.$thisfn};
14510:               }
14511:               if ($ids) {
14512: # ------------------------------------------------------------------- Has ID(s)
14513:                  my @possibilities=split(/\,/,$ids);
14514:                  if ($#possibilities==0) {
14515: # ----------------------------------------------- There is only one possibility
14516: 		     my ($mapid,$resid)=split(/\./,$ids);
14517: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
14518: 						    $resid,$thisfn);
14519:                      if (ref($possibles) eq 'HASH') {
14520:                          unless ($bighash{'randomout_'.$ids} || $env{'request.role.adv'}) {
14521:                              $possibles->{$syval} = 1;
14522:                          }
14523:                      }
14524:                      if ($checkforblock) {
14525:                          unless ($bighash{'randomout_'.$ids} || $env{'request.role.adv'}) {
14526:                              my @blockers = &has_comm_blocking('bre',$syval,$bighash{'src_'.$ids},'',$noenccheck);
14527:                              if (@blockers) {
14528:                                  $syval = '';
14529:                                  untie(%bighash);
14530:                                  return $env{$cache_str}='';
14531:                              }
14532:                          }
14533:                      }
14534:                  } elsif ((!$donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) { 
14535: # ------------------------------------------ There is more than one possibility
14536:                      my $realpossible=0;
14537:                      foreach my $id (@possibilities) {
14538: 			 my $file=$bighash{'src_'.$id};
14539:                          my $canaccess;
14540:                          if (($donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
14541:                              $canaccess = 1;
14542:                          } else { 
14543:                              $canaccess = &allowed('bre',$file);
14544:                          }
14545:                          if ($canaccess) {
14546:          		     my ($mapid,$resid)=split(/\./,$id);
14547:                              if ($bighash{'map_type_'.$mapid} ne 'page') {
14548:                                  my $poss_syval=&encode_symb($bighash{'map_id_'.$mapid},
14549: 						             $resid,$thisfn);
14550:                                  next if ($bighash{'randomout_'.$id} && !$env{'request.role.adv'});
14551:                                  next unless (($noenccheck) || ($bighash{'encrypted_'.$id} eq $env{'request.enc'}));
14552:                                  if ($checkforblock) {
14553:                                      my @blockers = &has_comm_blocking('bre',$poss_syval,$file,'',$noenccheck);
14554:                                      if (@blockers > 0) {
14555:                                          $syval = '';
14556:                                      } else {
14557:                                          $syval = $poss_syval;
14558:                                          $realpossible++;
14559:                                      }
14560:                                  } else {
14561:                                      $syval = $poss_syval;
14562:                                      $realpossible++;
14563:                                  }
14564:                                  if ($syval) {
14565:                                      if (ref($possibles) eq 'HASH') {
14566:                                          $possibles->{$syval} = 1;
14567:                                      }
14568:                                  }
14569:                              }
14570: 			 }
14571:                      }
14572: 		     if ($realpossible!=1) { $syval=''; }
14573:                  } else {
14574:                      $syval='';
14575:                  }
14576: 	      }
14577:               untie(%bighash);
14578:            }
14579:         }
14580:         if ($syval) {
14581: 	    return $env{$cache_str}=$syval;
14582:         }
14583:     }
14584:     &appenv({'request.ambiguous' => $thisfn});
14585:     return $env{$cache_str}='';
14586: }
14587: 
14588: # ---------------------------------------------------------- Return random seed
14589: 
14590: sub numval {
14591:     my $txt=shift;
14592:     $txt=~tr/A-J/0-9/;
14593:     $txt=~tr/a-j/0-9/;
14594:     $txt=~tr/K-T/0-9/;
14595:     $txt=~tr/k-t/0-9/;
14596:     $txt=~tr/U-Z/0-5/;
14597:     $txt=~tr/u-z/0-5/;
14598:     $txt=~s/\D//g;
14599:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
14600:     return int($txt);
14601: }
14602: 
14603: sub numval2 {
14604:     my $txt=shift;
14605:     $txt=~tr/A-J/0-9/;
14606:     $txt=~tr/a-j/0-9/;
14607:     $txt=~tr/K-T/0-9/;
14608:     $txt=~tr/k-t/0-9/;
14609:     $txt=~tr/U-Z/0-5/;
14610:     $txt=~tr/u-z/0-5/;
14611:     $txt=~s/\D//g;
14612:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
14613:     my $total;
14614:     foreach my $val (@txts) { $total+=$val; }
14615:     if ($_64bit) { if ($total > 2**32) { return -1; } }
14616:     return int($total);
14617: }
14618: 
14619: sub numval3 {
14620:     use integer;
14621:     my $txt=shift;
14622:     $txt=~tr/A-J/0-9/;
14623:     $txt=~tr/a-j/0-9/;
14624:     $txt=~tr/K-T/0-9/;
14625:     $txt=~tr/k-t/0-9/;
14626:     $txt=~tr/U-Z/0-5/;
14627:     $txt=~tr/u-z/0-5/;
14628:     $txt=~s/\D//g;
14629:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
14630:     my $total;
14631:     foreach my $val (@txts) { $total+=$val; }
14632:     if ($_64bit) { $total=(($total<<32)>>32); }
14633:     return $total;
14634: }
14635: 
14636: sub digest {
14637:     my ($data)=@_;
14638:     my $digest=&Digest::MD5::md5($data);
14639:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
14640:     my ($e,$f);
14641:     {
14642:         use integer;
14643:         $e=($a+$b);
14644:         $f=($c+$d);
14645:         if ($_64bit) {
14646:             $e=(($e<<32)>>32);
14647:             $f=(($f<<32)>>32);
14648:         }
14649:     }
14650:     if (wantarray) {
14651: 	return ($e,$f);
14652:     } else {
14653: 	my $g;
14654: 	{
14655: 	    use integer;
14656: 	    $g=($e+$f);
14657: 	    if ($_64bit) {
14658: 		$g=(($g<<32)>>32);
14659: 	    }
14660: 	}
14661: 	return $g;
14662:     }
14663: }
14664: 
14665: sub latest_rnd_algorithm_id {
14666:     return '64bit5';
14667: }
14668: 
14669: sub get_rand_alg {
14670:     my ($courseid)=@_;
14671:     if (!$courseid) { $courseid=(&whichuser())[1]; }
14672:     if ($courseid) {
14673: 	return $env{"course.$courseid.rndseed"};
14674:     }
14675:     return &latest_rnd_algorithm_id();
14676: }
14677: 
14678: sub validCODE {
14679:     my ($CODE)=@_;
14680:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
14681:     return 0;
14682: }
14683: 
14684: sub getCODE {
14685:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
14686:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
14687: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
14688: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
14689: 	return $Apache::lonhomework::history{'resource.CODE'};
14690:     }
14691:     return undef;
14692: }
14693: #
14694: #  Determines the random seed for a specific context:
14695: #
14696: # parameters:
14697: #   symb      - in course context the symb for the seed.
14698: #   course_id - The course id of the form domain_coursenum.
14699: #   domain    - Domain for the user.
14700: #   course    - Course for the user.
14701: #   cenv      - environment of the course.
14702: #
14703: # NOTE:
14704: #   All parameters are picked out of the environment if missing
14705: #   or not defined.
14706: #   If a symb cannot be determined the current time is used instead.
14707: #
14708: #  For a given well defined symb, courside, domain, username,
14709: #  and course environment, the seed is reproducible.
14710: #
14711: sub rndseed {
14712:     my ($symb,$courseid,$domain,$username, $cenv)=@_;
14713:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
14714:     if (!defined($symb)) {
14715: 	unless ($symb=$wsymb) { return time; }
14716:     }
14717:     if (!defined $courseid) { 
14718: 	$courseid=$wcourseid; 
14719:     }
14720:     if (!defined $domain) { $domain=$wdomain; }
14721:     if (!defined $username) { $username=$wusername }
14722: 
14723:     my $which;
14724:     if (defined($cenv->{'rndseed'})) {
14725: 	$which = $cenv->{'rndseed'};
14726:     } else {
14727: 	$which =&get_rand_alg($courseid);
14728:     }
14729:     if (defined(&getCODE())) {
14730: 
14731: 	if ($which eq '64bit5') {
14732: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
14733: 	} elsif ($which eq '64bit4') {
14734: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
14735: 	} else {
14736: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
14737: 	}
14738:     } elsif ($which eq '64bit5') {
14739: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
14740:     } elsif ($which eq '64bit4') {
14741: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
14742:     } elsif ($which eq '64bit3') {
14743: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
14744:     } elsif ($which eq '64bit2') {
14745: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
14746:     } elsif ($which eq '64bit') {
14747: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
14748:     }
14749:     return &rndseed_32bit($symb,$courseid,$domain,$username);
14750: }
14751: 
14752: sub rndseed_32bit {
14753:     my ($symb,$courseid,$domain,$username)=@_;
14754:     {
14755: 	use integer;
14756: 	my $symbchck=unpack("%32C*",$symb) << 27;
14757: 	my $symbseed=numval($symb) << 22;
14758: 	my $namechck=unpack("%32C*",$username) << 17;
14759: 	my $nameseed=numval($username) << 12;
14760: 	my $domainseed=unpack("%32C*",$domain) << 7;
14761: 	my $courseseed=unpack("%32C*",$courseid);
14762: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
14763: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
14764: 	#&logthis("rndseed :$num:$symb");
14765: 	if ($_64bit) { $num=(($num<<32)>>32); }
14766: 	return $num;
14767:     }
14768: }
14769: 
14770: sub rndseed_64bit {
14771:     my ($symb,$courseid,$domain,$username)=@_;
14772:     {
14773: 	use integer;
14774: 	my $symbchck=unpack("%32S*",$symb) << 21;
14775: 	my $symbseed=numval($symb) << 10;
14776: 	my $namechck=unpack("%32S*",$username);
14777: 	
14778: 	my $nameseed=numval($username) << 21;
14779: 	my $domainseed=unpack("%32S*",$domain) << 10;
14780: 	my $courseseed=unpack("%32S*",$courseid);
14781: 	
14782: 	my $num1=$symbchck+$symbseed+$namechck;
14783: 	my $num2=$nameseed+$domainseed+$courseseed;
14784: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
14785: 	#&logthis("rndseed :$num:$symb");
14786: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
14787: 	return "$num1,$num2";
14788:     }
14789: }
14790: 
14791: sub rndseed_64bit2 {
14792:     my ($symb,$courseid,$domain,$username)=@_;
14793:     {
14794: 	use integer;
14795: 	# strings need to be an even # of cahracters long, it it is odd the
14796:         # last characters gets thrown away
14797: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
14798: 	my $symbseed=numval($symb) << 10;
14799: 	my $namechck=unpack("%32S*",$username.' ');
14800: 	
14801: 	my $nameseed=numval($username) << 21;
14802: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
14803: 	my $courseseed=unpack("%32S*",$courseid.' ');
14804: 	
14805: 	my $num1=$symbchck+$symbseed+$namechck;
14806: 	my $num2=$nameseed+$domainseed+$courseseed;
14807: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
14808: 	#&logthis("rndseed :$num:$symb");
14809: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
14810: 	return "$num1,$num2";
14811:     }
14812: }
14813: 
14814: sub rndseed_64bit3 {
14815:     my ($symb,$courseid,$domain,$username)=@_;
14816:     {
14817: 	use integer;
14818: 	# strings need to be an even # of cahracters long, it it is odd the
14819:         # last characters gets thrown away
14820: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
14821: 	my $symbseed=numval2($symb) << 10;
14822: 	my $namechck=unpack("%32S*",$username.' ');
14823: 	
14824: 	my $nameseed=numval2($username) << 21;
14825: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
14826: 	my $courseseed=unpack("%32S*",$courseid.' ');
14827: 	
14828: 	my $num1=$symbchck+$symbseed+$namechck;
14829: 	my $num2=$nameseed+$domainseed+$courseseed;
14830: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
14831: 	#&logthis("rndseed :$num1:$num2:$_64bit");
14832: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
14833: 	
14834: 	return "$num1:$num2";
14835:     }
14836: }
14837: 
14838: sub rndseed_64bit4 {
14839:     my ($symb,$courseid,$domain,$username)=@_;
14840:     {
14841: 	use integer;
14842: 	# strings need to be an even # of cahracters long, it it is odd the
14843:         # last characters gets thrown away
14844: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
14845: 	my $symbseed=numval3($symb) << 10;
14846: 	my $namechck=unpack("%32S*",$username.' ');
14847: 	
14848: 	my $nameseed=numval3($username) << 21;
14849: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
14850: 	my $courseseed=unpack("%32S*",$courseid.' ');
14851: 	
14852: 	my $num1=$symbchck+$symbseed+$namechck;
14853: 	my $num2=$nameseed+$domainseed+$courseseed;
14854: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
14855: 	#&logthis("rndseed :$num1:$num2:$_64bit");
14856: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
14857: 	
14858: 	return "$num1:$num2";
14859:     }
14860: }
14861: 
14862: sub rndseed_64bit5 {
14863:     my ($symb,$courseid,$domain,$username)=@_;
14864:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
14865:     return "$num1:$num2";
14866: }
14867: 
14868: sub rndseed_CODE_64bit {
14869:     my ($symb,$courseid,$domain,$username)=@_;
14870:     {
14871: 	use integer;
14872: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
14873: 	my $symbseed=numval2($symb);
14874: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
14875: 	my $CODEseed=numval(&getCODE());
14876: 	my $courseseed=unpack("%32S*",$courseid.' ');
14877: 	my $num1=$symbseed+$CODEchck;
14878: 	my $num2=$CODEseed+$courseseed+$symbchck;
14879: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
14880: 	#&logthis("rndseed :$num1:$num2:$symb");
14881: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
14882: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
14883: 	return "$num1:$num2";
14884:     }
14885: }
14886: 
14887: sub rndseed_CODE_64bit4 {
14888:     my ($symb,$courseid,$domain,$username)=@_;
14889:     {
14890: 	use integer;
14891: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
14892: 	my $symbseed=numval3($symb);
14893: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
14894: 	my $CODEseed=numval3(&getCODE());
14895: 	my $courseseed=unpack("%32S*",$courseid.' ');
14896: 	my $num1=$symbseed+$CODEchck;
14897: 	my $num2=$CODEseed+$courseseed+$symbchck;
14898: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
14899: 	#&logthis("rndseed :$num1:$num2:$symb");
14900: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
14901: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
14902: 	return "$num1:$num2";
14903:     }
14904: }
14905: 
14906: sub rndseed_CODE_64bit5 {
14907:     my ($symb,$courseid,$domain,$username)=@_;
14908:     my $code = &getCODE();
14909:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
14910:     return "$num1:$num2";
14911: }
14912: 
14913: sub setup_random_from_rndseed {
14914:     my ($rndseed)=@_;
14915:     if ($rndseed =~/([,:])/) {
14916:         my ($num1,$num2) = map { abs($_); } (split(/[,:]/,$rndseed));
14917:         if ((!$num1) || (!$num2) || ($num1 > 2147483562) || ($num2 > 2147483398)) {
14918:             &Math::Random::random_set_seed_from_phrase($rndseed);
14919:         } else {
14920:             &Math::Random::random_set_seed($num1,$num2);
14921:         }
14922:     } else {
14923: 	&Math::Random::random_set_seed_from_phrase($rndseed);
14924:     }
14925: }
14926: 
14927: sub latest_receipt_algorithm_id {
14928:     return 'receipt3';
14929: }
14930: 
14931: sub recunique {
14932:     my $fucourseid=shift;
14933:     my $unique;
14934:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
14935: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
14936: 	$unique=$env{"course.$fucourseid.internal.encseed"};
14937:     } else {
14938: 	$unique=$perlvar{'lonReceipt'};
14939:     }
14940:     return unpack("%32C*",$unique);
14941: }
14942: 
14943: sub recprefix {
14944:     my $fucourseid=shift;
14945:     my $prefix;
14946:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
14947: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
14948: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
14949:     } else {
14950: 	$prefix=$perlvar{'lonHostID'};
14951:     }
14952:     return unpack("%32C*",$prefix);
14953: }
14954: 
14955: sub ireceipt {
14956:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
14957: 
14958:     my $return =&recprefix($fucourseid).'-';
14959: 
14960:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
14961: 	$env{'request.state'} eq 'construct') {
14962: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
14963: 	return $return;
14964:     }
14965: 
14966:     my $cuname=unpack("%32C*",$funame);
14967:     my $cudom=unpack("%32C*",$fudom);
14968:     my $cucourseid=unpack("%32C*",$fucourseid);
14969:     my $cusymb=unpack("%32C*",$fusymb);
14970:     my $cunique=&recunique($fucourseid);
14971:     my $cpart=unpack("%32S*",$part);
14972:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
14973: 
14974: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
14975: 			       
14976: 	$return.= ($cunique%$cuname+
14977: 		   $cunique%$cudom+
14978: 		   $cusymb%$cuname+
14979: 		   $cusymb%$cudom+
14980: 		   $cucourseid%$cuname+
14981: 		   $cucourseid%$cudom+
14982: 		   $cpart%$cuname+
14983: 		   $cpart%$cudom);
14984:     } else {
14985: 	$return.= ($cunique%$cuname+
14986: 		   $cunique%$cudom+
14987: 		   $cusymb%$cuname+
14988: 		   $cusymb%$cudom+
14989: 		   $cucourseid%$cuname+
14990: 		   $cucourseid%$cudom);
14991:     }
14992:     return $return;
14993: }
14994: 
14995: sub receipt {
14996:     my ($part)=@_;
14997:     my ($symb,$courseid,$domain,$name) = &whichuser();
14998:     return &ireceipt($name,$domain,$courseid,$symb,$part);
14999: }
15000: 
15001: sub whichuser {
15002:     my ($passedsymb)=@_;
15003:     my ($symb,$courseid,$domain,$name,$publicuser);
15004:     if (defined($env{'form.grade_symb'})) {
15005: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
15006: 	my $allowed=&allowed('vgr',$tmp_courseid);
15007: 	if (!$allowed &&
15008: 	    exists($env{'request.course.sec'}) &&
15009: 	    $env{'request.course.sec'} !~ /^\s*$/) {
15010: 	    $allowed=&allowed('vgr',$tmp_courseid.
15011: 			      '/'.$env{'request.course.sec'});
15012: 	}
15013: 	if ($allowed) {
15014: 	    ($symb)=&get_env_multiple('form.grade_symb');
15015: 	    $courseid=$tmp_courseid;
15016: 	    ($domain)=&get_env_multiple('form.grade_domain');
15017: 	    ($name)=&get_env_multiple('form.grade_username');
15018: 	    return ($symb,$courseid,$domain,$name,$publicuser);
15019: 	}
15020:     }
15021:     if (!$passedsymb) {
15022: 	$symb=&symbread();
15023:     } else {
15024: 	$symb=$passedsymb;
15025:     }
15026:     $courseid=$env{'request.course.id'};
15027:     $domain=$env{'user.domain'};
15028:     $name=$env{'user.name'};
15029:     if ($name eq 'public' && $domain eq 'public') {
15030: 	if (!defined($env{'form.username'})) {
15031: 	    $env{'form.username'}.=time.rand(10000000);
15032: 	}
15033: 	$name.=$env{'form.username'};
15034:     }
15035:     return ($symb,$courseid,$domain,$name,$publicuser);
15036: 
15037: }
15038: 
15039: # ------------------------------------------------------------ Serves up a file
15040: # returns either the contents of the file or 
15041: # -1 if the file doesn't exist
15042: #
15043: # if the target is a file that was uploaded via DOCS, 
15044: # a check will be made to see if a current copy exists on the local server,
15045: # if it does this will be served, otherwise a copy will be retrieved from
15046: # the home server for the course and stored in /home/httpd/html/userfiles on
15047: # the local server.   
15048: 
15049: sub getfile {
15050:     my ($file) = @_;
15051:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
15052:     &repcopy($file);
15053:     return &readfile($file);
15054: }
15055: 
15056: sub repcopy_userfile {
15057:     my ($file)=@_;
15058:     my $londocroot = $perlvar{'lonDocRoot'};
15059:     if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
15060:     if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
15061:     my ($cdom,$cnum,$filename) = 
15062: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
15063:     my $uri="/uploaded/$cdom/$cnum/$filename";
15064:     if (-e "$file") {
15065: # we already have a local copy, check it out
15066: 	my @fileinfo = stat($file);
15067: 	my $rtncode;
15068: 	my $info;
15069: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
15070: 	if ($lwpresp ne 'ok') {
15071: # there is no such file anymore, even though we had a local copy
15072: 	    if ($rtncode eq '404') {
15073: 		unlink($file);
15074: 	    }
15075: 	    return -1;
15076: 	}
15077: 	if ($info < $fileinfo[9]) {
15078: # nice, the file we have is up-to-date, just say okay
15079: 	    return 'ok';
15080: 	} else {
15081: # the file is outdated, get rid of it
15082: 	    unlink($file);
15083: 	}
15084:     }
15085: # one way or the other, at this point, we don't have the file
15086: # construct the correct path for the file
15087:     my @parts = ($cdom,$cnum); 
15088:     if ($filename =~ m|^(.+)/[^/]+$|) {
15089: 	push @parts, split(/\//,$1);
15090:     }
15091:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
15092:     foreach my $part (@parts) {
15093: 	$path .= '/'.$part;
15094: 	if (!-e $path) {
15095: 	    mkdir($path,0770);
15096: 	}
15097:     }
15098: # now the path exists for sure
15099: # get a user agent
15100:     my $transferfile=$file.'.in.transfer';
15101: # FIXME: this should flock
15102:     if (-e $transferfile) { return 'ok'; }
15103:     my $request;
15104:     $uri=~s/^\///;
15105:     my $homeserver = &homeserver($cnum,$cdom);
15106:     my $hostname = &hostname($homeserver);
15107:     my $protocol = $protocol{$homeserver};
15108:     $protocol = 'http' if ($protocol ne 'https');
15109:     $request=new HTTP::Request('GET',$protocol.'://'.$hostname.'/raw/'.$uri);
15110:     my $response = &LONCAPA::LWPReq::makerequest($homeserver,$request,$transferfile,\%perlvar,'',0,1);
15111: # did it work?
15112:     if ($response->is_error()) {
15113: 	unlink($transferfile);
15114: 	&logthis("Userfile repcopy failed for $uri");
15115: 	return -1;
15116:     }
15117: # worked, rename the transfer file
15118:     rename($transferfile,$file);
15119:     return 'ok';
15120: }
15121: 
15122: sub tokenwrapper {
15123:     my $uri=shift;
15124:     $uri=~s|^https?\://([^/]+)||;
15125:     $uri=~s|^/||;
15126:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
15127:     my $token=$1;
15128:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
15129:     if ($udom && $uname && $file) {
15130: 	$file=~s|(\?\.*)*$||;
15131:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
15132:         my $homeserver = &homeserver($uname,$udom);
15133:         my $hostname = &hostname($homeserver);
15134:         my $protocol = $protocol{$homeserver};
15135:         $protocol = 'http' if ($protocol ne 'https');
15136:         return $protocol.'://'.$hostname.'/'.$uri.
15137:                (($uri=~/\?/)?'&':'?').'token='.$token.
15138:                                '&tokenissued='.$perlvar{'lonHostID'};
15139:     } else {
15140:         return '/adm/notfound.html';
15141:     }
15142: }
15143: 
15144: # call with reqtype HEAD: get last modification time
15145: # call with reqtype GET: get the file contents
15146: # Do not call this with reqtype GET for large files! It loads everything into memory
15147: #
15148: sub getuploaded {
15149:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
15150:     $uri=~s/^\///;
15151:     my $homeserver = &homeserver($cnum,$cdom);
15152:     my $hostname = &hostname($homeserver);
15153:     my $protocol = $protocol{$homeserver};
15154:     $protocol = 'http' if ($protocol ne 'https');
15155:     $uri = $protocol.'://'.$hostname.'/raw/'.$uri;
15156:     my $request=new HTTP::Request($reqtype,$uri);
15157:     my $response=&LONCAPA::LWPReq::makerequest($homeserver,$request,'',\%perlvar,'',0,1);
15158:     $$rtncode = $response->code;
15159:     if (! $response->is_success()) {
15160: 	return 'failed';
15161:     }      
15162:     if ($reqtype eq 'HEAD') {
15163: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
15164:     } elsif ($reqtype eq 'GET') {
15165: 	$$info = $response->content;
15166:     }
15167:     return 'ok';
15168: }
15169: 
15170: sub readfile {
15171:     my $file = shift;
15172:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
15173:     my $fh;
15174:     open($fh,"<",$file);
15175:     my $a='';
15176:     while (my $line = <$fh>) { $a .= $line; }
15177:     return $a;
15178: }
15179: 
15180: sub filelocation {
15181:     my ($dir,$file) = @_;
15182:     my $location;
15183:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
15184: 
15185:     if ($file =~ m-^/adm/-) {
15186: 	$file=~s-^/adm/wrapper/-/-;
15187: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
15188:     }
15189: 
15190:     if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
15191:         $location = $file;
15192:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
15193:         my ($udom,$uname,$filename)=
15194:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
15195:         my $home=&homeserver($uname,$udom);
15196:         my $is_me=0;
15197:         my @ids=&current_machine_ids();
15198:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
15199:         if ($is_me) {
15200:   	    $location=propath($udom,$uname).'/userfiles/'.$filename;
15201:         } else {
15202:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
15203:   	      $udom.'/'.$uname.'/'.$filename;
15204:         }
15205:     } elsif ($file =~ m-^/adm/-) {
15206: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
15207:     } else {
15208:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
15209:         $file=~s:^/(res|priv)/:/:;
15210:         my $space=$1;
15211:         if ( !( $file =~ m:^/:) ) {
15212:             $location = $dir. '/'.$file;
15213:         } else {
15214:             $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
15215:         }
15216:     }
15217:     $location=~s://+:/:g; # remove duplicate /
15218:     while ($location=~m{/\.\./}) {
15219: 	if ($location =~ m{/[^/]+/\.\./}) {
15220: 	    $location=~ s{/[^/]+/\.\./}{/}g;
15221: 	} else {
15222: 	    $location=~ s{/\.\./}{/}g;
15223: 	}
15224:     } #remove dir/..
15225:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
15226:     return $location;
15227: }
15228: 
15229: sub hreflocation {
15230:     my ($dir,$file)=@_;
15231:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
15232: 	$file=filelocation($dir,$file);
15233:     } elsif ($file=~m-^/adm/-) {
15234: 	$file=~s-^/adm/wrapper/-/-;
15235: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
15236:     }
15237:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
15238: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
15239:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
15240: 	$file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
15241: 	        {/uploaded/$1/$2/}x;
15242:     }
15243:     if ($file=~ m{^/userfiles/}) {
15244: 	$file =~ s{^/userfiles/}{/uploaded/};
15245:     }
15246:     return $file;
15247: }
15248: 
15249: 
15250: 
15251: 
15252: 
15253: sub current_machine_domains {
15254:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
15255: }
15256: 
15257: sub machine_domains {
15258:     my ($hostname) = @_;
15259:     my @domains;
15260:     my %hostname = &all_hostnames();
15261:     while( my($id, $name) = each(%hostname)) {
15262: #	&logthis("-$id-$name-$hostname-");
15263: 	if ($hostname eq $name) {
15264: 	    push(@domains,&host_domain($id));
15265: 	}
15266:     }
15267:     return @domains;
15268: }
15269: 
15270: sub current_machine_ids {
15271:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
15272: }
15273: 
15274: sub machine_ids {
15275:     my ($hostname) = @_;
15276:     $hostname ||= &hostname($perlvar{'lonHostID'});
15277:     my @ids;
15278:     my %name_to_host = &all_names();
15279:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
15280: 	return @{ $name_to_host{$hostname} };
15281:     }
15282:     return;
15283: }
15284: 
15285: sub additional_machine_domains {
15286:     my @domains;
15287:     if (-e "$perlvar{'lonTabDir'}/expected_domains.tab") {
15288:         if (open(my $fh,"<","$perlvar{'lonTabDir'}/expected_domains.tab")) {
15289:             while (my $line = <$fh>) {
15290:                 chomp($line);           
15291:                 $line =~ s/\s//g;
15292:                 push(@domains,$line);
15293:             }
15294:             close($fh);
15295:         }
15296:     }
15297:     return @domains;
15298: }
15299: 
15300: sub default_login_domain {
15301:     my $domain = $perlvar{'lonDefDomain'};
15302:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
15303:     foreach my $posdom (&current_machine_domains(),
15304:                         &additional_machine_domains()) {
15305:         if (lc($posdom) eq lc($testdomain)) {
15306:             $domain=$posdom;
15307:             last;
15308:         }
15309:     }
15310:     return $domain;
15311: }
15312: 
15313: sub shared_institution {
15314:     my ($dom,$lonhost) = @_;
15315:     if ($lonhost eq '') {
15316:         $lonhost = $perlvar{'lonHostID'};
15317:     }
15318:     my $same_intdom;
15319:     my $hostintdom = &internet_dom($lonhost);
15320:     if ($hostintdom ne '') {
15321:         my %iphost = &get_iphost();
15322:         my $primary_id = &domain($dom,'primary');
15323:         my $primary_ip = &get_host_ip($primary_id);
15324:         if (ref($iphost{$primary_ip}) eq 'ARRAY') {
15325:             foreach my $id (@{$iphost{$primary_ip}}) {
15326:                 my $intdom = &internet_dom($id);
15327:                 if ($intdom eq $hostintdom) {
15328:                     $same_intdom = 1;
15329:                     last;
15330:                 }
15331:             }
15332:         }
15333:     }
15334:     return $same_intdom;
15335: }
15336: 
15337: sub uses_sts {
15338:     my ($ignore_cache) = @_;
15339:     my $lonhost = $perlvar{'lonHostID'};
15340:     my $hostname = &hostname($lonhost);
15341:     my $sts_on;
15342:     if ($protocol{$lonhost} eq 'https') {
15343:         my $cachetime = 12*3600;
15344:         if (!$ignore_cache) {
15345:             ($sts_on,my $cached)=&is_cached_new('stspolicy',$lonhost);
15346:             if (defined($cached)) {
15347:                 return $sts_on;
15348:             }
15349:         }
15350:         my $url = $protocol{$lonhost}.'://'.$hostname.'/index.html';
15351:         my $request=new HTTP::Request('HEAD',$url);
15352:         my $response=&LONCAPA::LWPReq::makerequest($lonhost,$request,'',\%perlvar,'','','',1);
15353:         if ($response->is_success) {
15354:             my $has_sts = $response->header('Strict-Transport-Security');
15355:             if ($has_sts eq '') {
15356:                 $sts_on = 0;
15357:             } else {
15358:                 if ($has_sts =~ /\Qmax-age=\E(\d+)/) {
15359:                     my $maxage = $1;
15360:                     if ($maxage) {
15361:                         $sts_on = 1;
15362:                     } else {
15363:                         $sts_on = 0;
15364:                     }
15365:                 } else {
15366:                     $sts_on = 0;
15367:                 }
15368:             }
15369:             return &do_cache_new('stspolicy',$lonhost,$sts_on,$cachetime);
15370:         }
15371:     }
15372:     return;
15373: }
15374: 
15375: sub waf_allssl {
15376:     my ($host_name) = @_;
15377:     my $alias = &get_proxy_alias();
15378:     if ($host_name eq '') {
15379:         $host_name = $ENV{'SERVER_NAME'};
15380:     }
15381:     if (($host_name ne '') && ($alias eq $host_name)) {
15382:         my $serverhomedom = &host_domain($perlvar{'lonHostID'});
15383:         my %defdomdefaults = &get_domain_defaults($serverhomedom);
15384:         if ($defdomdefaults{'waf_sslopt'}) {
15385:             return $defdomdefaults{'waf_sslopt'};
15386:         }
15387:     }
15388:     return;
15389: }
15390: 
15391: sub get_requestor_ip {
15392:     my ($r,$nolookup,$noproxy) = @_;
15393:     my $from_ip;
15394:     if (ref($r)) {
15395:         if ($r->can('useragent_ip')) {
15396:             if ($noproxy && $r->can('client_ip')) {
15397:                 $from_ip = $r->client_ip();
15398:             } else {
15399:                 $from_ip = $r->useragent_ip();
15400:             }
15401:         } elsif ($r->connection->can('remote_ip')) {
15402:             $from_ip = $r->connection->remote_ip();
15403:         } else {
15404:             $from_ip = $r->get_remote_host($nolookup);
15405:         }
15406:     } else {
15407:         $from_ip = $ENV{'REMOTE_ADDR'};
15408:     }
15409:     return $from_ip if ($noproxy); 
15410:     # Who controls proxy settings for server
15411:     my $dom_in_use = $Apache::lonnet::perlvar{'lonDefDomain'};
15412:     my $proxyinfo = &get_proxy_settings($dom_in_use);
15413:     if ((ref($proxyinfo) eq 'HASH') && ($from_ip)) {
15414:         if ($proxyinfo->{'vpnint'}) {
15415:             if (&ip_match($from_ip,$proxyinfo->{'vpnint'})) {
15416:                 return $from_ip;
15417:             }
15418:         }
15419:         if ($proxyinfo->{'trusted'}) {
15420:             if (&ip_match($from_ip,$proxyinfo->{'trusted'})) {
15421:                 my $ipheader = $proxyinfo->{'ipheader'};
15422:                 my ($ip,$xfor);
15423:                 if (ref($r)) {
15424:                     if ($ipheader) {
15425:                         $ip = $r->headers_in->{$ipheader};
15426:                     }
15427:                     $xfor = $r->headers_in->{'X-Forwarded-For'};
15428:                 } else {
15429:                     if ($ipheader) {
15430:                         $ip = $ENV{'HTTP_'.uc($ipheader)};
15431:                     }
15432:                     $xfor = $ENV{'HTTP_X_FORWARDED_FOR'};
15433:                 }
15434:                 if (($ip eq '') && ($xfor ne '')) {
15435:                     foreach my $poss_ip (reverse(split(/\s*,\s*/,$xfor))) {
15436:                         unless (&ip_match($poss_ip,$proxyinfo->{'trusted'})) {
15437:                             $ip = $poss_ip;
15438:                             last;
15439:                         }
15440:                     }
15441:                 }
15442:                 if ($ip ne '') {
15443:                     return $ip;
15444:                 }
15445:             }
15446:         }
15447:     }
15448:     return $from_ip;
15449: }
15450: 
15451: sub get_proxy_settings {
15452:     my ($dom_in_use) = @_;
15453:     my %domdefaults = &get_domain_defaults($dom_in_use);
15454:     my $proxyinfo = {
15455:                        ipheader => $domdefaults{'waf_ipheader'},
15456:                        trusted  => $domdefaults{'waf_trusted'},
15457:                        vpnint   => $domdefaults{'waf_vpnint'},
15458:                        vpnext   => $domdefaults{'waf_vpnext'},
15459:                        sslopt   => $domdefaults{'waf_sslopt'},
15460:                     };
15461:     return $proxyinfo;
15462: }
15463: 
15464: sub ip_match {
15465:     my ($ip,$pattern_str) = @_;
15466:     $ip=Net::CIDR::cidrvalidate($ip);
15467:     if ($ip) {
15468:         return Net::CIDR::cidrlookup($ip,split(/\s*,\s*/,$pattern_str));
15469:     }
15470:     return;
15471: }
15472: 
15473: sub get_proxy_alias {
15474:     my ($lonid) = @_;
15475:     if ($lonid eq '') {
15476:         $lonid = $perlvar{'lonHostID'};
15477:     }
15478:     if (!defined(&hostname($lonid))) {
15479:         return;
15480:     }
15481:     if ($lonid ne '') {
15482:         my ($alias,$cached) = &is_cached_new('proxyalias',$lonid);
15483:         if ($cached) {
15484:             return $alias;
15485:         }
15486:         my $dom = &host_domain($lonid);
15487:         if ($dom ne '') {
15488:             my $cachetime = 60*60*24;
15489:             my %domconfig =
15490:                 &get_dom('configuration',['wafproxy'],$dom);
15491:             if (ref($domconfig{'wafproxy'}) eq 'HASH') {
15492:                 if (ref($domconfig{'wafproxy'}{'alias'}) eq 'HASH') {
15493:                     $alias = $domconfig{'wafproxy'}{'alias'}{$lonid};
15494:                 }
15495:             }
15496:             return &do_cache_new('proxyalias',$lonid,$alias,$cachetime);
15497:         }
15498:     }
15499:     return;
15500: }
15501: 
15502: sub use_proxy_alias {
15503:     my ($r,$lonid) = @_;
15504:     my $alias = &get_proxy_alias($lonid);
15505:     if ($alias) {
15506:         my $dom = &host_domain($lonid);
15507:         if ($dom ne '') {
15508:             my $proxyinfo = &get_proxy_settings($dom);
15509:             my ($vpnint,$remote_ip);
15510:             if (ref($proxyinfo) eq 'HASH') {
15511:                 $vpnint = $proxyinfo->{'vpnint'};
15512:                 if ($vpnint) {
15513:                     $remote_ip = &get_requestor_ip($r,1,1);
15514:                 }
15515:             }
15516:             unless ($vpnint && &ip_match($remote_ip,$vpnint)) {
15517:                 return $alias;
15518:             }
15519:         }
15520:     }
15521:     return;
15522: }
15523: 
15524: sub alias_sso {
15525:     my ($lonid) = @_;
15526:     if ($lonid eq '') {
15527:         $lonid = $perlvar{'lonHostID'};
15528:     }
15529:     if (!defined(&hostname($lonid))) {
15530:         return;
15531:     }
15532:     if ($lonid ne '') {
15533:         my ($use_alias,$cached) = &is_cached_new('proxysaml',$lonid);
15534:         if ($cached) {
15535:             return $use_alias;
15536:         }
15537:         my $dom = &host_domain($lonid);
15538:         if ($dom ne '') {
15539:             my $cachetime = 60*60*24;
15540:             my %domconfig =
15541:                 &get_dom('configuration',['wafproxy'],$dom);
15542:             if (ref($domconfig{'wafproxy'}) eq 'HASH') {
15543:                 if (ref($domconfig{'wafproxy'}{'saml'}) eq 'HASH') {
15544:                     $use_alias = $domconfig{'wafproxy'}{'saml'}{$lonid};
15545:                 }
15546:             }
15547:             return &do_cache_new('proxysaml',$lonid,$use_alias,$cachetime);
15548:         }
15549:     }
15550:     return;
15551: }
15552: 
15553: sub get_saml_landing {
15554:     my ($lonid) = @_;
15555:     if ($lonid eq '') {
15556:         my $defdom = &default_login_domain();
15557:         my @hosts = &current_machine_ids();
15558:         if (@hosts > 1) {
15559:             foreach my $hostid (@hosts) {
15560:                 if (&host_domain($hostid) eq $defdom) {
15561:                     $lonid = $hostid;
15562:                     last;
15563:                 }
15564:             }
15565:         } else {
15566:             $lonid = $perlvar{'lonHostID'};
15567:         }
15568:         if ($lonid) {
15569:             unless (&host_domain($lonid) eq $defdom) {
15570:                 return;
15571:             }
15572:         } else {
15573:             return;
15574:         }
15575:     } elsif (!defined(&hostname($lonid))) {
15576:         return;
15577:     }
15578:     my ($landing,$cached) = &is_cached_new('samllanding',$lonid);
15579:     if ($cached) {
15580:         return $landing;
15581:     }
15582:     my $dom = &host_domain($lonid);
15583:     if ($dom ne '') {
15584:         my $cachetime = 60*60*24;
15585:         my %domconfig =
15586:             &get_dom('configuration',['login'],$dom);
15587:         if (ref($domconfig{'login'}) eq 'HASH') {
15588:             if (ref($domconfig{'login'}{'saml'}) eq 'HASH') {
15589:                 if (ref($domconfig{'login'}{'saml'}{$lonid}) eq 'HASH') {
15590:                     $landing = 1;
15591:                 }
15592:             }
15593:         }
15594:         return &do_cache_new('samllanding',$lonid,$landing,$cachetime);
15595:     }
15596:     return;
15597: }
15598: 
15599: # ------------------------------------------------------------- Declutters URLs
15600: 
15601: sub declutter {
15602:     my $thisfn=shift;
15603:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
15604:     unless ($thisfn=~m{^/home/httpd/html/priv/}) {
15605:         $thisfn=~s{^/home/httpd/html}{};
15606:     }
15607:     $thisfn=~s/^\///;
15608:     $thisfn=~s|^adm/wrapper/||;
15609:     $thisfn=~s|^adm/coursedocs/showdoc/||;
15610:     $thisfn=~s/^res\///;
15611:     $thisfn=~s/^priv\///;
15612:     unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
15613:         $thisfn=~s/\?.+$//;
15614:     }
15615:     return $thisfn;
15616: }
15617: 
15618: # ------------------------------------------------------------- Clutter up URLs
15619: 
15620: sub clutter {
15621:     my $thisfn='/'.&declutter(shift);
15622:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
15623: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
15624:        $thisfn='/res'.$thisfn; 
15625:     }
15626:     if ($thisfn !~m|^/adm|) {
15627: 	if ($thisfn =~ m|^/ext/|) {
15628: 	    $thisfn='/adm/wrapper'.$thisfn;
15629: 	} else {
15630: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
15631: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
15632: 	    if ($embstyle eq 'ssi'
15633: 		|| ($embstyle eq 'hdn')
15634: 		|| ($embstyle eq 'rat')
15635: 		|| ($embstyle eq 'prv')
15636: 		|| ($embstyle eq 'ign')) {
15637: 		#do nothing with these
15638: 	    } elsif (($embstyle eq 'img') 
15639: 		|| ($embstyle eq 'emb')
15640: 		|| ($embstyle eq 'wrp')) {
15641: 		$thisfn='/adm/wrapper'.$thisfn;
15642: 	    } elsif ($embstyle eq 'unk'
15643: 		     && $thisfn!~/\.(sequence|page)$/) {
15644: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
15645: 	    } else {
15646: #		&logthis("Got a blank emb style");
15647: 	    }
15648: 	}
15649:     } elsif ($thisfn =~ m{^/adm/$match_domain/$match_courseid/\d+/ext\.tool$}) {
15650:         $thisfn='/adm/wrapper'.$thisfn;
15651:     }
15652:     return $thisfn;
15653: }
15654: 
15655: sub clutter_with_no_wrapper {
15656:     my $uri = &clutter(shift);
15657:     if ($uri =~ m-^/adm/-) {
15658: 	$uri =~ s-^/adm/wrapper/-/-;
15659: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
15660:     }
15661:     return $uri;
15662: }
15663: 
15664: sub freeze_escape {
15665:     my ($value)=@_;
15666:     if (ref($value)) {
15667: 	$value=&nfreeze($value);
15668: 	return '__FROZEN__'.&escape($value);
15669:     }
15670:     return &escape($value);
15671: }
15672: 
15673: 
15674: sub thaw_unescape {
15675:     my ($value)=@_;
15676:     if ($value =~ /^__FROZEN__/) {
15677: 	substr($value,0,10,undef);
15678: 	$value=&unescape($value);
15679: 	return &thaw($value);
15680:     }
15681:     return &unescape($value);
15682: }
15683: 
15684: sub correct_line_ends {
15685:     my ($result)=@_;
15686:     $$result =~s/\r\n/\n/mg;
15687:     $$result =~s/\r/\n/mg;
15688: }
15689: # ================================================================ Main Program
15690: 
15691: sub goodbye {
15692:    &logthis("Starting Shut down");
15693: #not converted to using infrastruture and probably shouldn't be
15694:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
15695: #converted
15696: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
15697:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
15698: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
15699: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
15700: #1.1 only
15701: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
15702: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
15703: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
15704: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
15705:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
15706:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
15707:    &logthis(sprintf("%-20s is %s",'hits',$hits));
15708:    &flushcourselogs();
15709:    &logthis("Shutting down");
15710: }
15711: 
15712: sub get_dns {
15713:     my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
15714:     if (!$ignore_cache) {
15715: 	my ($content,$cached)=
15716: 	    &is_cached_new('dns',$url);
15717: 	if ($cached) {
15718: 	    &$func($content,$hashref);
15719: 	    return;
15720: 	}
15721:     }
15722: 
15723:     my %alldns;
15724:     if (open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab")) {
15725:         foreach my $dns (<$config>) {
15726: 	    next if ($dns !~ /^\^(\S*)/x);
15727:             my $line = $1;
15728:             my ($host,$protocol) = split(/:/,$line);
15729:             if ($protocol ne 'https') {
15730:                 $protocol = 'http';
15731:             }
15732: 	    $alldns{$host} = $protocol;
15733:         }
15734:         close($config);
15735:     }
15736:     while (%alldns) {
15737: 	my ($dns) = sort { $b cmp $a } keys(%alldns);
15738:         my ($contents,@content);
15739:         if ($dns eq Sys::Hostname::FQDN::fqdn()) {
15740:             my $command = (split('/',$url))[3];
15741:             my ($dir,$file) = &parse_getdns_url($command,$url);
15742:             delete($alldns{$dns});
15743:             next if (($dir eq '') || ($file eq ''));
15744:             if (open(my $config,'<',"$dir/$file")) {
15745:                 @content = <$config>;
15746:                 close($config);
15747:             }
15748:             if ($url eq '/adm/dns/loncapaCRL') {
15749:                 $contents = join('',@content);
15750:             }
15751:         } else {
15752: 	    my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
15753:             my $response = &LONCAPA::LWPReq::makerequest('',$request,'',\%perlvar,30,0);
15754:             delete($alldns{$dns});
15755: 	    next if ($response->is_error());
15756:             if ($url eq '/adm/dns/loncapaCRL') {
15757:                 $contents = $response->content;
15758:             } else {
15759:                 @content = split("\n",$response->content);
15760:             }
15761:         }
15762:         if ($url eq '/adm/dns/loncapaCRL') {
15763:             return &$func($contents);
15764:         } else {
15765: 	    unless ($nocache) {
15766: 	        &do_cache_new('dns',$url,\@content,30*24*60*60);
15767: 	    }
15768: 	    &$func(\@content,$hashref);
15769:             return;
15770:         }
15771:     }
15772:     my $which = (split('/',$url,4))[3];
15773:     if ($which eq 'loncapaCRL') {
15774:         my $diskfile = "$perlvar{'lonCertificateDirectory'}/$perlvar{'lonnetCertRevocationList'}";
15775:         if (-e $diskfile) {
15776:             &logthis("unable to contact DNS, on disk file $diskfile not updated");
15777:         } else {
15778:             &logthis("unable to contact DNS, no on disk file $diskfile available");
15779:         }
15780:     } else {
15781:         &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
15782:         if (open(my $config,"<","$perlvar{'lonTabDir'}/dns_$which.tab")) {
15783:             my @content = <$config>;
15784:             close($config);
15785:             &$func(\@content,$hashref);
15786:         }
15787:     }
15788:     return;
15789: }
15790: 
15791: # ------------------------------------------------------Get DNS checksums file
15792: sub parse_dns_checksums_tab {
15793:     my ($lines,$hashref) = @_;
15794:     my $lonhost = $perlvar{'lonHostID'};
15795:     my $machine_dom = &host_domain($lonhost);
15796:     my $loncaparev = &get_server_loncaparev($machine_dom);
15797:     my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
15798:     my $webconfdir = '/etc/httpd/conf';
15799:     if ($distro =~ /^(ubuntu|debian)(\d+)$/) {
15800:         $webconfdir = '/etc/apache2';
15801:     } elsif ($distro =~ /^sles(\d+)$/) {
15802:         if ($1 >= 10) {
15803:             $webconfdir = '/etc/apache2';
15804:         }
15805:     } elsif ($distro =~ /^suse(\d+\.\d+)$/) {
15806:         if ($1 >= 10.0) {
15807:             $webconfdir = '/etc/apache2';
15808:         }
15809:     }
15810:     my ($release,$timestamp) = split(/\-/,$loncaparev);
15811:     my (%chksum,%revnum);
15812:     if (ref($lines) eq 'ARRAY') {
15813:         chomp(@{$lines});
15814:         my $version = shift(@{$lines});
15815:         if ($version eq $release) {  
15816:             foreach my $line (@{$lines}) {
15817:                 my ($file,$version,$shasum) = split(/,/,$line);
15818:                 if ($file =~ m{^/etc/httpd/conf}) {
15819:                     if ($webconfdir eq '/etc/apache2') {
15820:                         $file =~ s{^\Q/etc/httpd/conf/\E}{$webconfdir/};
15821:                     }
15822:                 }
15823:                 $chksum{$file} = $shasum;
15824:                 $revnum{$file} = $version;
15825:             }
15826:             if (ref($hashref) eq 'HASH') {
15827:                 %{$hashref} = (
15828:                                 sums     => \%chksum,
15829:                                 versions => \%revnum,
15830:                               );
15831:             }
15832:         }
15833:     }
15834:     return;
15835: }
15836: 
15837: sub fetch_dns_checksums {
15838:     my %checksums;
15839:     my $machine_dom = &host_domain($perlvar{'lonHostID'});
15840:     my $loncaparev = &get_server_loncaparev($machine_dom,$perlvar{'lonHostID'});
15841:     my ($release,$timestamp) = split(/\-/,$loncaparev);
15842:     &get_dns("/adm/dns/checksums/$release",\&parse_dns_checksums_tab,1,1,
15843:              \%checksums);
15844:     return \%checksums;
15845: }
15846: 
15847: sub fetch_crl_pemfile {
15848:     return &get_dns("/adm/dns/loncapaCRL",\&save_crl_pem,1,1);
15849: }
15850: 
15851: sub save_crl_pem {
15852:     my ($content) = @_;
15853:     my ($msg,$hadchanges);
15854:     if ($content ne '') {
15855:         my $now = time;
15856:         my $lonca = $perlvar{'lonCertificateDirectory'}.'/'.$perlvar{'lonnetCertificateAuthority'};
15857:         my $tmpcrl = $tmpdir.'/'.$perlvar{'lonnetCertRevocationList'}.'_'.$now.'.'.$$.'.tmp';
15858:         if (open(my $fh,'>',"$tmpcrl")) {
15859:             print $fh $content;
15860:             close($fh);
15861:             if (-e $lonca) {
15862:                 if (open(PIPE,"openssl crl -in $tmpcrl -inform pem -CAfile $lonca -noout 2>&1 |")) {
15863:                     my $check = <PIPE>;
15864:                     close(PIPE);
15865:                     chomp($check);
15866:                     if ($check eq 'verify OK') {
15867:                         my $dest = "$perlvar{'lonCertificateDirectory'}/$perlvar{'lonnetCertRevocationList'}";
15868:                         my $backup;
15869:                         if (-e $dest) {
15870:                             if (&File::Copy::move($dest,"$dest.bak")) {
15871:                                 $backup = 'ok';
15872:                             }
15873:                         }
15874:                         if (&File::Copy::move($tmpcrl,$dest)) {
15875:                             $msg = 'ok';
15876:                             if ($backup) {
15877:                                 my (%oldnums,%newnums);
15878:                                 if (open(PIPE, "openssl crl -inform PEM -text -noout -in $dest.bak |grep 'Serial Number' |")) {
15879:                                     while (<PIPE>) {
15880:                                         $oldnums{(split(/:/))[1]} = 1;
15881:                                     }
15882:                                     close(PIPE);
15883:                                 }
15884:                                 if (open(PIPE, "openssl crl -inform PEM -text -noout -in $dest |grep 'Serial Number' |")) {
15885:                                     while(<PIPE>) {
15886:                                         $newnums{(split(/:/))[1]} = 1;
15887:                                     }
15888:                                     close(PIPE);
15889:                                 }
15890:                                 foreach my $key (sort {$b <=> $a } (keys(%newnums))) {
15891:                                     unless (exists($oldnums{$key})) {
15892:                                         $hadchanges = 1;
15893:                                         last;
15894:                                     }
15895:                                 }
15896:                                 unless ($hadchanges) {
15897:                                     foreach my $key (sort {$b <=> $a } (keys(%oldnums))) {
15898:                                         unless (exists($newnums{$key})) {
15899:                                             $hadchanges = 1;
15900:                                             last;
15901:                                         }
15902:                                     }
15903:                                 }
15904:                             }
15905:                         }
15906:                     } else {
15907:                         unlink($tmpcrl);
15908:                     }
15909:                 } else {
15910:                     unlink($tmpcrl);
15911:                 }
15912:             } else {
15913:                 unlink($tmpcrl);
15914:             }
15915:         }
15916:     }
15917:     return ($msg,$hadchanges);
15918: }
15919: 
15920: sub parse_getdns_url {
15921:     my ($command,$url) = @_;
15922:     my $dir = $perlvar{'lonTabDir'};
15923:     my $file;
15924:     if ($command eq 'hosts') {
15925:         $file = 'dns_hosts.tab';
15926:     } elsif ($command eq 'domain') {
15927:         $file = 'dns_domain.tab';
15928:     } elsif ($command eq 'checksums') {
15929:         my $version = (split('/',$url))[4];
15930:         $file = "dns_checksums/$version.tab",
15931:     } elsif ($command eq 'loncapaCRL') {
15932:         $dir = $perlvar{'lonCertificateDirectory'};
15933:         $file = $perlvar{'lonnetCertRevocationList'};
15934:     }
15935:     return ($dir,$file);
15936: }
15937: 
15938: # ------------------------------------------------------------ Read domain file
15939: {
15940:     my $loaded;
15941:     my %domain;
15942: 
15943:     sub parse_domain_tab {
15944: 	my ($lines) = @_;
15945: 	foreach my $line (@$lines) {
15946: 	    next if ($line =~ /^(\#|\s*$ )/x);
15947: 
15948: 	    chomp($line);
15949: 	    my ($name,@elements) = split(/:/,$line,9);
15950: 	    my %this_domain;
15951: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
15952: 			       'lang_def', 'city', 'longi', 'lati',
15953: 			       'primary') {
15954: 		$this_domain{$field} = shift(@elements);
15955: 	    }
15956: 	    $domain{$name} = \%this_domain;
15957: 	}
15958:     }
15959: 
15960:     sub reset_domain_info {
15961: 	undef($loaded);
15962: 	undef(%domain);
15963:     }
15964: 
15965:     sub load_domain_tab {
15966: 	my ($ignore_cache,$nocache) = @_;
15967: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache,$nocache);
15968: 	my $fh;
15969: 	if (open($fh,"<",$perlvar{'lonTabDir'}.'/domain.tab')) {
15970: 	    my @lines = <$fh>;
15971: 	    &parse_domain_tab(\@lines);
15972: 	}
15973: 	close($fh);
15974: 	$loaded = 1;
15975:     }
15976: 
15977:     sub domain {
15978: 	&load_domain_tab() if (!$loaded);
15979: 
15980: 	my ($name,$what) = @_;
15981: 	return if ( !exists($domain{$name}) );
15982: 
15983: 	if (!$what) {
15984: 	    return $domain{$name}{'description'};
15985: 	}
15986: 	return $domain{$name}{$what};
15987:     }
15988: 
15989:     sub domain_info {
15990:         &load_domain_tab() if (!$loaded);
15991:         return %domain;
15992:     }
15993: 
15994: }
15995: 
15996: 
15997: # ------------------------------------------------------------- Read hosts file
15998: {
15999:     my %hostname;
16000:     my %hostdom;
16001:     my %libserv;
16002:     my $loaded;
16003:     my %name_to_host;
16004:     my %internetdom;
16005:     my %LC_dns_serv;
16006: 
16007:     sub parse_hosts_tab {
16008: 	my ($file) = @_;
16009: 	foreach my $configline (@$file) {
16010: 	    next if ($configline =~ /^(\#|\s*$ )/x);
16011:             chomp($configline);
16012: 	    if ($configline =~ /^\^/) {
16013:                 if ($configline =~ /^\^([\w.\-]+)/) {
16014:                     $LC_dns_serv{$1} = 1;
16015:                 }
16016:                 next;
16017:             }
16018: 	    my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
16019: 	    $name=~s/\s//g;
16020: 	    if ($id && $domain && $role && $name) {
16021:                 if ((exists($hostname{$id})) && ($hostname{$id} ne '')) {
16022:                     my $curr = $hostname{$id};
16023:                     my $skip;
16024:                     if (ref($name_to_host{$curr}) eq 'ARRAY') {
16025:                         if (($curr eq $name) && (@{$name_to_host{$curr}} == 1)) {
16026:                             $skip = 1;
16027:                         } else {
16028:                             @{$name_to_host{$curr}} = grep { $_ ne $id } @{$name_to_host{$curr}};
16029:                         }
16030:                     }
16031:                     unless ($skip) {
16032:                         push(@{$name_to_host{$name}},$id);
16033:                     }
16034:                 } else {
16035:                     push(@{$name_to_host{$name}},$id);
16036:                 }
16037: 		$hostname{$id}=$name;
16038: 		$hostdom{$id}=$domain;
16039: 		if ($role eq 'library') { $libserv{$id}=$name; }
16040:                 if (defined($protocol)) {
16041:                     if ($protocol eq 'https') {
16042:                         $protocol{$id} = $protocol;
16043:                     } else {
16044:                         $protocol{$id} = 'http'; 
16045:                     }
16046:                 } else {
16047:                     $protocol{$id} = 'http';
16048:                 }
16049:                 if (defined($intdom)) {
16050:                     $internetdom{$id} = $intdom;
16051:                 }
16052: 	    }
16053: 	}
16054:     }
16055:     
16056:     sub reset_hosts_info {
16057: 	&purge_remembered();
16058: 	&reset_domain_info();
16059: 	&reset_hosts_ip_info();
16060:         undef(%internetdom);
16061: 	undef(%name_to_host);
16062: 	undef(%hostname);
16063: 	undef(%hostdom);
16064: 	undef(%libserv);
16065: 	undef($loaded);
16066:     }
16067: 
16068:     sub load_hosts_tab {
16069: 	my ($ignore_cache,$nocache) = @_;
16070: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache,$nocache);
16071: 	open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab");
16072: 	my @config = <$config>;
16073: 	&parse_hosts_tab(\@config);
16074: 	close($config);
16075: 	$loaded=1;
16076:     }
16077: 
16078:     sub hostname {
16079: 	&load_hosts_tab() if (!$loaded);
16080: 
16081: 	my ($lonid) = @_;
16082: 	return $hostname{$lonid};
16083:     }
16084: 
16085:     sub all_hostnames {
16086: 	&load_hosts_tab() if (!$loaded);
16087: 
16088: 	return %hostname;
16089:     }
16090: 
16091:     sub all_names {
16092:         my ($ignore_cache,$nocache) = @_;
16093: 	&load_hosts_tab($ignore_cache,$nocache) if (!$loaded);
16094: 
16095: 	return %name_to_host;
16096:     }
16097: 
16098:     sub all_host_domain {
16099:         &load_hosts_tab() if (!$loaded);
16100:         return %hostdom;
16101:     }
16102: 
16103:     sub all_host_intdom {
16104:         &load_hosts_tab() if (!$loaded);
16105:         return %internetdom;
16106:     }
16107: 
16108:     sub is_library {
16109: 	&load_hosts_tab() if (!$loaded);
16110: 
16111: 	return exists($libserv{$_[0]});
16112:     }
16113: 
16114:     sub all_library {
16115: 	&load_hosts_tab() if (!$loaded);
16116: 
16117: 	return %libserv;
16118:     }
16119: 
16120:     sub unique_library {
16121: 	#2x reverse removes all hostnames that appear more than once
16122:         my %unique = reverse &all_library();
16123:         return reverse %unique;
16124:     }
16125: 
16126:     sub get_servers {
16127: 	&load_hosts_tab() if (!$loaded);
16128: 
16129: 	my ($domain,$type) = @_;
16130: 	my %possible_hosts = ($type eq 'library') ? %libserv
16131: 	                                          : %hostname;
16132: 	my %result;
16133: 	if (ref($domain) eq 'ARRAY') {
16134: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
16135: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
16136: 		    $result{$host} = $hostname;
16137: 		}
16138: 	    }
16139: 	} else {
16140: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
16141: 		if ($hostdom{$host} eq $domain) {
16142: 		    $result{$host} = $hostname;
16143: 		}
16144: 	    }
16145: 	}
16146: 	return %result;
16147:     }
16148: 
16149:     sub get_unique_servers {
16150:         my %unique = reverse &get_servers(@_);
16151: 	return reverse %unique;
16152:     }
16153: 
16154:     sub host_domain {
16155: 	&load_hosts_tab() if (!$loaded);
16156: 
16157: 	my ($lonid) = @_;
16158: 	return $hostdom{$lonid};
16159:     }
16160: 
16161:     sub all_domains {
16162: 	&load_hosts_tab() if (!$loaded);
16163: 
16164: 	my %seen;
16165: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
16166: 	return @uniq;
16167:     }
16168: 
16169:     sub internet_dom {
16170:         &load_hosts_tab() if (!$loaded);
16171: 
16172:         my ($lonid) = @_;
16173:         return $internetdom{$lonid};
16174:     }
16175: 
16176:     sub is_LC_dns {
16177:         &load_hosts_tab() if (!$loaded);
16178: 
16179:         my ($hostname) = @_;
16180:         return exists($LC_dns_serv{$hostname});
16181:     }
16182: 
16183: }
16184: 
16185: { 
16186:     my %iphost;
16187:     my %name_to_ip;
16188:     my %lonid_to_ip;
16189: 
16190:     sub get_hosts_from_ip {
16191: 	my ($ip) = @_;
16192: 	my %iphosts = &get_iphost();
16193: 	if (ref($iphosts{$ip})) {
16194: 	    return @{$iphosts{$ip}};
16195: 	}
16196: 	return;
16197:     }
16198:     
16199:     sub reset_hosts_ip_info {
16200: 	undef(%iphost);
16201: 	undef(%name_to_ip);
16202: 	undef(%lonid_to_ip);
16203:     }
16204: 
16205:     sub get_host_ip {
16206: 	my ($lonid) = @_;
16207: 	if (exists($lonid_to_ip{$lonid})) {
16208: 	    return $lonid_to_ip{$lonid};
16209: 	}
16210: 	my $name=&hostname($lonid);
16211:    	my $ip = gethostbyname($name);
16212: 	return if (!$ip || length($ip) ne 4);
16213: 	$ip=inet_ntoa($ip);
16214: 	$name_to_ip{$name}   = $ip;
16215: 	$lonid_to_ip{$lonid} = $ip;
16216: 	return $ip;
16217:     }
16218:     
16219:     sub get_iphost {
16220: 	my ($ignore_cache,$nocache) = @_;
16221: 
16222: 	if (!$ignore_cache) {
16223: 	    if (%iphost) {
16224: 		return %iphost;
16225: 	    }
16226: 	    my ($ip_info,$cached)=
16227: 		&is_cached_new('iphost','iphost');
16228: 	    if ($cached) {
16229: 		%iphost      = %{$ip_info->[0]};
16230: 		%name_to_ip  = %{$ip_info->[1]};
16231: 		%lonid_to_ip = %{$ip_info->[2]};
16232: 		return %iphost;
16233: 	    }
16234: 	}
16235: 
16236: 	# get yesterday's info for fallback
16237: 	my %old_name_to_ip;
16238: 	my ($ip_info,$cached)=
16239: 	    &is_cached_new('iphost','iphost');
16240: 	if ($cached) {
16241: 	    %old_name_to_ip = %{$ip_info->[1]};
16242: 	}
16243: 
16244: 	my %name_to_host = &all_names($ignore_cache,$nocache);
16245: 	foreach my $name (keys(%name_to_host)) {
16246: 	    my $ip;
16247: 	    if (!exists($name_to_ip{$name})) {
16248: 		$ip = gethostbyname($name);
16249: 		if (!$ip || length($ip) ne 4) {
16250: 		    if (defined($old_name_to_ip{$name})) {
16251: 			$ip = $old_name_to_ip{$name};
16252: 			&logthis("Can't find $name defaulting to old $ip");
16253: 		    } else {
16254: 			&logthis("Name $name no IP found");
16255: 			next;
16256: 		    }
16257: 		} else {
16258: 		    $ip=inet_ntoa($ip);
16259: 		}
16260: 		$name_to_ip{$name} = $ip;
16261: 	    } else {
16262: 		$ip = $name_to_ip{$name};
16263: 	    }
16264: 	    foreach my $id (@{ $name_to_host{$name} }) {
16265: 		$lonid_to_ip{$id} = $ip;
16266: 	    }
16267: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
16268: 	}
16269:         unless ($nocache) {
16270: 	    &do_cache_new('iphost','iphost',
16271: 		          [\%iphost,\%name_to_ip,\%lonid_to_ip],
16272: 		          48*60*60);
16273:         }
16274: 
16275: 	return %iphost;
16276:     }
16277: 
16278:     #
16279:     #  Given a DNS returns the loncapa host name for that DNS 
16280:     # 
16281:     sub host_from_dns {
16282:         my ($dns) = @_;
16283:         my @hosts;
16284:         my $ip;
16285: 
16286:         if (exists($name_to_ip{$dns})) {
16287:             $ip = $name_to_ip{$dns};
16288:         }
16289:         if (!$ip) {
16290:             $ip = gethostbyname($dns); # Initial translation to IP is in net order.
16291:             if (length($ip) == 4) { 
16292: 	        $ip   = &IO::Socket::inet_ntoa($ip);
16293:             }
16294:         }
16295:         if ($ip) {
16296: 	    @hosts = get_hosts_from_ip($ip);
16297: 	    return $hosts[0];
16298:         }
16299:         return undef;
16300:     }
16301: 
16302:     sub get_internet_names {
16303:         my ($lonid) = @_;
16304:         return if ($lonid eq '');
16305:         my ($idnref,$cached)=
16306:             &is_cached_new('internetnames',$lonid);
16307:         if ($cached) {
16308:             return $idnref;
16309:         }
16310:         my $ip = &get_host_ip($lonid);
16311:         my @hosts = &get_hosts_from_ip($ip);
16312:         my %iphost = &get_iphost();
16313:         my (@idns,%seen);
16314:         foreach my $id (@hosts) {
16315:             my $dom = &host_domain($id);
16316:             my $prim_id = &domain($dom,'primary');
16317:             my $prim_ip = &get_host_ip($prim_id);
16318:             next if ($seen{$prim_ip});
16319:             if (ref($iphost{$prim_ip}) eq 'ARRAY') {
16320:                 foreach my $id (@{$iphost{$prim_ip}}) {
16321:                     my $intdom = &internet_dom($id);
16322:                     unless (grep(/^\Q$intdom\E$/,@idns)) {
16323:                         push(@idns,$intdom);
16324:                     }
16325:                 }
16326:             }
16327:             $seen{$prim_ip} = 1;
16328:         }
16329:         return &do_cache_new('internetnames',$lonid,\@idns,12*60*60);
16330:     }
16331: 
16332: }
16333: 
16334: sub all_loncaparevs {
16335:     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);
16336: }
16337: 
16338: # ---------------------------------------------------------- Read loncaparev table
16339: {
16340:     sub load_loncaparevs { 
16341:         if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
16342:             if (open(my $config,"<","$perlvar{'lonTabDir'}/loncaparevs.tab")) {
16343:                 while (my $configline=<$config>) {
16344:                     chomp($configline);
16345:                     my ($hostid,$loncaparev)=split(/:/,$configline);
16346:                     $loncaparevs{$hostid}=$loncaparev;
16347:                 }
16348:                 close($config);
16349:             }
16350:         }
16351:     }
16352: }
16353: 
16354: # ---------------------------------------------------------- Read serverhostID table
16355: {
16356:     sub load_serverhomeIDs {
16357:         if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
16358:             if (open(my $config,"<","$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
16359:                 while (my $configline=<$config>) {
16360:                     chomp($configline);
16361:                     my ($name,$id)=split(/:/,$configline);
16362:                     $serverhomeIDs{$name}=$id;
16363:                 }
16364:                 close($config);
16365:             }
16366:         }
16367:     }
16368: }
16369: 
16370: 
16371: BEGIN {
16372: 
16373: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
16374:     unless ($readit) {
16375: {
16376:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
16377:     %perlvar = (%perlvar,%{$configvars});
16378: }
16379: 
16380: 
16381: # ------------------------------------------------------ Read spare server file
16382: {
16383:     open(my $config,"<","$perlvar{'lonTabDir'}/spare.tab");
16384: 
16385:     while (my $configline=<$config>) {
16386:        chomp($configline);
16387:        if ($configline) {
16388: 	   my ($host,$type) = split(':',$configline,2);
16389: 	   if (!defined($type) || $type eq '') { $type = 'default' };
16390: 	   push(@{ $spareid{$type} }, $host);
16391:        }
16392:     }
16393:     close($config);
16394: }
16395: # ------------------------------------------------------------ Read permissions
16396: {
16397:     open(my $config,"<","$perlvar{'lonTabDir'}/roles.tab");
16398: 
16399:     while (my $configline=<$config>) {
16400: 	chomp($configline);
16401: 	if ($configline) {
16402: 	    my ($role,$perm)=split(/ /,$configline);
16403: 	    if ($perm ne '') { $pr{$role}=$perm; }
16404: 	}
16405:     }
16406:     close($config);
16407: }
16408: 
16409: # -------------------------------------------- Read plain texts for permissions
16410: {
16411:     open(my $config,"<","$perlvar{'lonTabDir'}/rolesplain.tab");
16412: 
16413:     while (my $configline=<$config>) {
16414: 	chomp($configline);
16415: 	if ($configline) {
16416: 	    my ($short,@plain)=split(/:/,$configline);
16417:             %{$prp{$short}} = ();
16418: 	    if (@plain > 0) {
16419:                 $prp{$short}{'std'} = $plain[0];
16420:                 for (my $i=1; $i<@plain; $i++) {
16421:                     $prp{$short}{'alt'.$i} = $plain[$i];  
16422:                 }
16423:             }
16424: 	}
16425:     }
16426:     close($config);
16427: }
16428: 
16429: # ---------------------------------------------------------- Read package table
16430: {
16431:     open(my $config,"<","$perlvar{'lonTabDir'}/packages.tab");
16432: 
16433:     while (my $configline=<$config>) {
16434: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
16435: 	chomp($configline);
16436: 	my ($short,$plain)=split(/:/,$configline);
16437: 	my ($pack,$name)=split(/\&/,$short);
16438: 	if ($plain ne '') {
16439: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
16440: 	    $packagetab{$short}=$plain; 
16441: 	}
16442:     }
16443:     close($config);
16444: }
16445: 
16446: # ---------------------------------------------------------- Read loncaparev table
16447: 
16448: &load_loncaparevs();
16449: 
16450: # ---------------------------------------------------------- Read serverhostID table
16451: 
16452: &load_serverhomeIDs();
16453: 
16454: # ---------------------------------------------------------- Read releaseslist XML
16455: {
16456:     my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
16457:     if (-e $file) {
16458:         my $parser = HTML::LCParser->new($file);
16459:         while (my $token = $parser->get_token()) {
16460:             if ($token->[0] eq 'S') {
16461:                 my $item = $token->[1];
16462:                 my $name = $token->[2]{'name'};
16463:                 my $value = $token->[2]{'value'};
16464:                 my $valuematch = $token->[2]{'valuematch'};
16465:                 my $namematch = $token->[2]{'namematch'};
16466:                 if ($item eq 'parameter') {
16467:                     if (($namematch ne '') || (($name ne '') && ($value ne '' || $valuematch ne ''))) {
16468:                         my $release = $parser->get_text();
16469:                         $release =~ s/(^\s*|\s*$ )//gx;
16470:                         $needsrelease{$item.':'.$name.':'.$value.':'.$valuematch.':'.$namematch} = $release;
16471:                     }
16472:                 } elsif ($item ne '' && $name ne '') {
16473:                     my $release = $parser->get_text();
16474:                     $release =~ s/(^\s*|\s*$ )//gx;
16475:                     $needsrelease{$item.':'.$name.':'.$value} = $release;
16476:                 }
16477:             }
16478:         }
16479:     }
16480: }
16481: 
16482: # ---------------------------------------------------------- Read managers table
16483: {
16484:     if (-e "$perlvar{'lonTabDir'}/managers.tab") {
16485:         if (open(my $config,"<","$perlvar{'lonTabDir'}/managers.tab")) {
16486:             while (my $configline=<$config>) {
16487:                 chomp($configline);
16488:                 next if ($configline =~ /^\#/);
16489:                 if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
16490:                     $managerstab{$configline} = 1;
16491:                 }
16492:             }
16493:             close($config);
16494:         }
16495:     }
16496: }
16497: 
16498: # ------------- set up temporary directory
16499: {
16500:     $tmpdir = LONCAPA::tempdir();
16501: 
16502: }
16503: 
16504: # ------------- set default texengine (domain default overrides this)
16505: {
16506:     $deftex = LONCAPA::texengine();
16507: }
16508: 
16509: # ------------- set default minimum length for passwords for internal auth users
16510: {
16511:     $passwdmin = LONCAPA::passwd_min();
16512: }
16513: 
16514: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
16515: 				'compress_threshold'=> 20_000,
16516:  			        });
16517: 
16518: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
16519: $dumpcount=0;
16520: $locknum=0;
16521: 
16522: &logtouch();
16523: &logthis('<font color="yellow">INFO: Read configuration</font>');
16524: $readit=1;
16525:     {
16526: 	use integer;
16527: 	my $test=(2**32)+1;
16528: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
16529: 	&logthis(" Detected 64bit platform ($_64bit)");
16530:     }
16531: }
16532: }
16533: 
16534: 1;
16535: __END__
16536: 
16537: =pod
16538: 
16539: =head1 NAME
16540: 
16541: Apache::lonnet - Subroutines to ask questions about things in the network.
16542: 
16543: =head1 SYNOPSIS
16544: 
16545: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
16546: 
16547:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
16548: 
16549: Common parameters:
16550: 
16551: =over 4
16552: 
16553: =item *
16554: 
16555: $uname : an internal username (if $cname expecting a course Id specifically)
16556: 
16557: =item *
16558: 
16559: $udom : a domain (if $cdom expecting a course's domain specifically)
16560: 
16561: =item *
16562: 
16563: $symb : a resource instance identifier
16564: 
16565: =item *
16566: 
16567: $namespace : the name of a .db file that contains the data needed or
16568: being set.
16569: 
16570: =back
16571: 
16572: =head1 OVERVIEW
16573: 
16574: lonnet provides subroutines which interact with the
16575: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
16576: about classes, users, and resources.
16577: 
16578: For many of these objects you can also use this to store data about
16579: them or modify them in various ways.
16580: 
16581: =head2 Symbs
16582: 
16583: To identify a specific instance of a resource, LON-CAPA uses symbols
16584: or "symbs"X<symb>. These identifiers are built from the URL of the
16585: map, the resource number of the resource in the map, and the URL of
16586: the resource itself. The latter is somewhat redundant, but might help
16587: if maps change.
16588: 
16589: An example is
16590: 
16591:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
16592: 
16593: The respective map entry is
16594: 
16595:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
16596:   title="Problem 2">
16597:  </resource>
16598: 
16599: Symbs are used by the random number generator, as well as to store and
16600: restore data specific to a certain instance of for example a problem.
16601: 
16602: =head2 Storing And Retrieving Data
16603: 
16604: X<store()>X<cstore()>X<restore()>Three of the most important functions
16605: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
16606: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
16607: is is the non-critical message twin of cstore. These functions are for
16608: handlers to store a perl hash to a user's permanent data space in an
16609: easy manner, and to retrieve it again on another call. It is expected
16610: that a handler would use this once at the beginning to retrieve data,
16611: and then again once at the end to send only the new data back.
16612: 
16613: The data is stored in the user's data directory on the user's
16614: homeserver under the ID of the course.
16615: 
16616: The hash that is returned by restore will have all of the previous
16617: value for all of the elements of the hash.
16618: 
16619: Example:
16620: 
16621:  #creating a hash
16622:  my %hash;
16623:  $hash{'foo'}='bar';
16624: 
16625:  #storing it
16626:  &Apache::lonnet::cstore(\%hash);
16627: 
16628:  #changing a value
16629:  $hash{'foo'}='notbar';
16630: 
16631:  #adding a new value
16632:  $hash{'bar'}='foo';
16633:  &Apache::lonnet::cstore(\%hash);
16634: 
16635:  #retrieving the hash
16636:  my %history=&Apache::lonnet::restore();
16637: 
16638:  #print the hash
16639:  foreach my $key (sort(keys(%history))) {
16640:    print("\%history{$key} = $history{$key}");
16641:  }
16642: 
16643: Will print out:
16644: 
16645:  %history{1:foo} = bar
16646:  %history{1:keys} = foo:timestamp
16647:  %history{1:timestamp} = 990455579
16648:  %history{2:bar} = foo
16649:  %history{2:foo} = notbar
16650:  %history{2:keys} = foo:bar:timestamp
16651:  %history{2:timestamp} = 990455580
16652:  %history{bar} = foo
16653:  %history{foo} = notbar
16654:  %history{timestamp} = 990455580
16655:  %history{version} = 2
16656: 
16657: Note that the special hash entries C<keys>, C<version> and
16658: C<timestamp> were added to the hash. C<version> will be equal to the
16659: total number of versions of the data that have been stored. The
16660: C<timestamp> attribute will be the UNIX time the hash was
16661: stored. C<keys> is available in every historical section to list which
16662: keys were added or changed at a specific historical revision of a
16663: hash.
16664: 
16665: B<Warning>: do not store the hash that restore returns directly. This
16666: will cause a mess since it will restore the historical keys as if the
16667: were new keys. I.E. 1:foo will become 1:1:foo etc.
16668: 
16669: Calling convention:
16670: 
16671:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname);
16672:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$laststore);
16673: 
16674: For more detailed information, see lonnet specific documentation.
16675: 
16676: =head1 RETURN MESSAGES
16677: 
16678: =over 4
16679: 
16680: =item * B<con_lost>: unable to contact remote host
16681: 
16682: =item * B<con_delayed>: unable to contact remote host, message will be delivered
16683: when the connection is brought back up
16684: 
16685: =item * B<con_failed>: unable to contact remote host and unable to save message
16686: for later delivery
16687: 
16688: =item * B<error:>: an error a occurred, a description of the error follows the :
16689: 
16690: =item * B<no_such_host>: unable to fund a host associated with the user/domain
16691: that was requested
16692: 
16693: =back
16694: 
16695: =head1 PUBLIC SUBROUTINES
16696: 
16697: =head2 Session Environment Functions
16698: 
16699: =over 4
16700: 
16701: =item * 
16702: X<appenv()>
16703: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
16704: the user envirnoment file, and will be restored for each access this
16705: user makes during this session, also modifies the %env for the current
16706: process. Optional rolesarrayref - if defined contains a reference to an array
16707: of roles which are exempt from the restriction on modifying user.role entries 
16708: in the user's environment.db and in %env.    
16709: 
16710: =item *
16711: X<delenv()>
16712: B<delenv($delthis,$regexp)>: removes all items from the session
16713: environment file that begin with $delthis. If the 
16714: optional second arg - $regexp - is true, $delthis is treated as a 
16715: regular expression, otherwise \Q$delthis\E is used. 
16716: The values are also deleted from the current processes %env.
16717: 
16718: =item * get_env_multiple($name) 
16719: 
16720: gets $name from the %env hash, it seemlessly handles the cases where multiple
16721: values may be defined and end up as an array ref.
16722: 
16723: returns an array of values
16724: 
16725: =back
16726: 
16727: =head2 User Information
16728: 
16729: =over 4
16730: 
16731: =item *
16732: X<queryauthenticate()>
16733: B<queryauthenticate($uname,$udom)>: try to determine user's current 
16734: authentication scheme
16735: 
16736: =item *
16737: X<authenticate()>
16738: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
16739: authenticate user from domain's lib servers (first use the current
16740: one). C<$upass> should be the users password.
16741: $checkdefauth is optional (value is 1 if a check should be made to
16742:    authenticate user using default authentication method, and allow
16743:    account creation if username does not have account in the domain).
16744: $clientcancheckhost is optional (value is 1 if checking whether the
16745:    server can host will occur on the client side in lonauth.pm).   
16746: 
16747: =item *
16748: X<homeserver()>
16749: B<homeserver($uname,$udom)>: find the server which has
16750: the user's directory and files (there must be only one), this caches
16751: the answer, and also caches if there is a borken connection.
16752: 
16753: =item *
16754: X<idget()>
16755: B<idget($udom,$idsref,$namespace)>: find the usernames behind either 
16756: a list of student/employee IDs or clicker IDs
16757: (student/employee IDs are a unique resource in a domain, there must be 
16758: only 1 ID per username, and only 1 username per ID in a specific domain).
16759: clickerIDs are not necessarily unique, as students might share clickers.
16760: (returns hash: id=>name,id=>name)
16761: 
16762: =item *
16763: X<idrget()>
16764: B<idrget($udom,@unames)>: find the IDs behind a list of
16765: usernames (returns hash: name=>id,name=>id)
16766: 
16767: =item *
16768: X<idput()>
16769: B<idput($udom,$idsref,$uhome,$namespace)>: store away a list of 
16770: names and associated student/employee IDs or clicker IDs.
16771: 
16772: =item *
16773: X<iddel()>
16774: B<iddel($udom,$idshashref,$uhome,$namespace)>: delete unwanted 
16775: student/employee ID or clicker ID username look-ups from domain.
16776: The homeserver ($uhome) and namespace ($namespace) are optional.
16777: If no $uhome is provided, it will be determined usig &homeserver()
16778: for each user.  If no $namespace is provided, the default is ids.
16779: 
16780: =item *
16781: X<updateclickers()>
16782: B<updateclickers($udom,$action,$idshashref,$uhome,$critical)>: update 
16783: clicker ID-to-username look-ups in clickers.db on library server.
16784: Permitted actions are add or del (i.e., add or delete). The 
16785: clickers.db contains clickerID as keys (escaped), and each corresponding
16786: value is an escaped comma-separated list of usernames (for whom the
16787: library server is the homeserver), who registered that particular ID.
16788: If $critical is true, the update will be sent via &critical, otherwise
16789: &reply() will be used.
16790: 
16791: =item *
16792: X<rolesinit()>
16793: B<rolesinit($udom,$username)>: get user privileges.
16794: returns user role, first access and timer interval hashes
16795: 
16796: =item *
16797: X<privileged()>
16798: B<privileged($username,$domain)>: returns a true if user has a
16799: privileged and active role (i.e. su or dc), false otherwise.
16800: 
16801: =item *
16802: X<getsection()>
16803: B<getsection($udom,$uname,$cname)>: finds the section of student in the
16804: course $cname, return section name/number or '' for "not in course"
16805: and '-1' for "no section"
16806: 
16807: =item *
16808: X<userenvironment()>
16809: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
16810: passed in @what from the requested user's environment, returns a hash
16811: 
16812: =item * 
16813: X<userlog_query()>
16814: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
16815: activity.log file. %filters defines filters applied when parsing the
16816: log file. These can be start or end timestamps, or the type of action
16817: - log to look for Login or Logout events, check for Checkin or
16818: Checkout, role for role selection. The response is in the form
16819: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
16820: escaped strings of the action recorded in the activity.log file.
16821: 
16822: =back
16823: 
16824: =head2 User Roles
16825: 
16826: =over 4
16827: 
16828: =item *
16829: 
16830: allowed($priv,$uri,$symb,$role,$clientip,$noblockcheck) : check for a user privilege; 
16831: returns codes for allowed actions.
16832: 
16833: The first argument is required, all others are optional.
16834: 
16835: $priv is the privilege being checked.
16836: $uri contains additional information about what is being checked for access (e.g.,
16837: URL, course ID etc.). 
16838: $symb is the unique resource instance identifier in a course; if needed,
16839: but not provided, it will be retrieved via a call to &symbread(). 
16840: $role is the role for which a priv is being checked (only used if priv is evb). 
16841: $clientip is the user's IP address (only used when checking for access to portfolio 
16842: files).
16843: $noblockcheck, if true, skips calls to &has_comm_blocking() for the bre priv. This 
16844: prevents recursive calls to &allowed.
16845: 
16846:  F: full access
16847:  U,I,K: authentication modes (cxx only)
16848:  '': forbidden
16849:  1: user needs to choose course
16850:  2: browse allowed
16851:  A: passphrase authentication needed
16852:  B: access temporarily blocked because of a blocking event in a course.
16853:  D: access blocked because access is required via session initiated via deep-link 
16854: 
16855: =item *
16856: 
16857: constructaccess($url,$setpriv) : check for access to construction space URL
16858: 
16859: See if the owner domain and name in the URL match those in the
16860: expected environment.  If so, return three element list
16861: ($ownername,$ownerdomain,$ownerhome).
16862: 
16863: Otherwise return the null string.
16864: 
16865: If second argument 'setpriv' is true, it assigns the privileges,
16866: and returns the same three element list, unless the owner has
16867: blocked "ad hoc" Domain Coordinator access to the Author Space,
16868: in which case the null string is returned.
16869: 
16870: =item *
16871: 
16872: definerole($rolename,$sysrole,$domrole,$courole,$uname,$udom) : define role;
16873: define a custom role rolename set privileges in format of lonTabs/roles.tab
16874: for system, domain, and course level. $uname and $udom are optional (current
16875: user's username and domain will be used when either of $uname or $udom are absent.
16876: 
16877: =item *
16878: 
16879: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
16880: (rolesplain.tab); plain text explanation of a user role term.
16881: $type is Course (default) or Community.
16882: If $forcedefault evaluates to true, text returned will be default 
16883: text for $type. Otherwise, if this is a course, the text returned 
16884: will be a custom name for the role (if defined in the course's 
16885: environment).  If no custom name is defined the default is returned.
16886:    
16887: =item *
16888: 
16889: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv) :
16890: All arguments are optional. Returns a hash of a roles, either for
16891: co-author/assistant author roles for a user's Construction Space
16892: (default), or if $context is 'userroles', roles for the user himself,
16893: In the hash, keys are set to colon-separated $uname,$udom,$role, and
16894: (optionally) if $withsec is true, a fourth colon-separated item - $section.
16895: For each key, value is set to colon-separated start and end times for
16896: the role.  If no username and domain are specified, will default to
16897: current user/domain. Types, roles, and roledoms are references to arrays
16898: of role statuses (active, future or previous), roles 
16899: (e.g., cc,in, st etc.) and domains of the roles which can be used
16900: to restrict the list of roles reported. If no array ref is 
16901: provided for types, will default to return only active roles.
16902: 
16903: =item *
16904: 
16905: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
16906: user: $uname:$udom has a role in the course: $cdom_$cnum. 
16907: 
16908: Additional optional arguments are: $type (if role checking is to be restricted 
16909: to certain user status types -- previous (expired roles), active (currently
16910: available roles) or future (roles available in the future), and
16911: $hideprivileged -- if true will not report course roles for users who
16912: have active Domain Coordinator role in course's domain or in additional
16913: domains (specified in 'Domains to check for privileged users' in course
16914: environment -- set via:  Course Settings -> Classlists and staff listing).
16915: 
16916: =item *
16917: 
16918: privileged($username,$domain,$possdomains,$possroles) : returns 1 if user
16919: $username:$domain is a privileged user (e.g., Domain Coordinator or Super User)
16920: $possdomains and $possroles are optional array refs -- to domains to check and
16921: roles to check.  If $possdomains is not specified, a dump will be done of the
16922: users' roles.db to check for a dc or su role in any domain. This can be
16923: time consuming if &privileged is called repeatedly (e.g., when displaying a
16924: classlist), so in such cases, supplying a $possdomains array is preferred, as
16925: this then allows &privileged_by_domain() to be used, which caches the identity
16926: of privileged users, eliminating the need for repeated calls to &dump().
16927: 
16928: =item *
16929: 
16930: privileged_by_domain($possdomains,$roles) : returns a hash of a hash of a hash,
16931: where the outer hash keys are domains specified in the $possdomains array ref,
16932: next inner hash keys are privileged roles specified in the $roles array ref,
16933: and the innermost hash contains key = value pairs for username:domain = end:start
16934: for active or future "privileged" users with that role in that domain. To avoid
16935: repeated dumps of domain roles -- via &get_domain_roles() -- contents of the
16936: innerhash are cached using priv_$role and $dom as the identifiers.
16937: 
16938: =back
16939: 
16940: =head2 User Modification
16941: 
16942: =over 4
16943: 
16944: =item *
16945: 
16946: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
16947: user for the level given by URL.  Optional start and end dates (leave empty
16948: string or zero for "no date")
16949: 
16950: =item *
16951: 
16952: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
16953: change a users, password, possible return values are: ok,
16954: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
16955: refused
16956: 
16957: =item *
16958: 
16959: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
16960: 
16961: =item *
16962: 
16963: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
16964:            $forceid,$desiredhome,$email,$inststatus,$candelete) :
16965: 
16966: will update user information (firstname,middlename,lastname,generation,
16967: permanentemail), and if forceid is true, student/employee ID also.
16968: A user's institutional affiliation(s) can also be updated.
16969: User information fields will not be overwritten with empty entries 
16970: unless the field is included in the $candelete array reference.
16971: This array is included when a single user is modified via "Manage Users",
16972: or when Autoupdate.pl is run by cron in a domain.
16973: 
16974: =item *
16975: 
16976: modifystudent
16977: 
16978: modify a student's enrollment and identification information.
16979: The course id is resolved based on the current user's environment.  
16980: This means the invoking user must be a course coordinator or otherwise
16981: associated with a course.
16982: 
16983: This call is essentially a wrapper for lonnet::modifyuser and
16984: lonnet::modify_student_enrollment
16985: 
16986: Inputs: 
16987: 
16988: =over 4
16989: 
16990: =item B<$udom> Student's loncapa domain
16991: 
16992: =item B<$uname> Student's loncapa login name
16993: 
16994: =item B<$uid> Student/Employee ID
16995: 
16996: =item B<$umode> Student's authentication mode
16997: 
16998: =item B<$upass> Student's password
16999: 
17000: =item B<$first> Student's first name
17001: 
17002: =item B<$middle> Student's middle name
17003: 
17004: =item B<$last> Student's last name
17005: 
17006: =item B<$gene> Student's generation
17007: 
17008: =item B<$usec> Student's section in course
17009: 
17010: =item B<$end> Unix time of the roles expiration
17011: 
17012: =item B<$start> Unix time of the roles start date
17013: 
17014: =item B<$forceid> If defined, allow $uid to be changed
17015: 
17016: =item B<$desiredhome> server to use as home server for student
17017: 
17018: =item B<$email> Student's permanent e-mail address
17019: 
17020: =item B<$type> Type of enrollment (auto or manual)
17021: 
17022: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
17023: 
17024: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
17025: 
17026: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
17027: 
17028: =item B<$context> role change context (shown in User Management Logs display in a course)
17029: 
17030: =item B<$inststatus> institutional status of user - : separated string of escaped status types
17031: 
17032: =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.
17033: 
17034: =back
17035: 
17036: =item *
17037: 
17038: modify_student_enrollment
17039: 
17040: Change a student's enrollment status in a class.  The environment variable
17041: 'role.request.course' must be defined for this function to proceed.
17042: 
17043: Inputs:
17044: 
17045: =over 4
17046: 
17047: =item $udom, student's domain
17048: 
17049: =item $uname, student's name
17050: 
17051: =item $uid, student's user id
17052: 
17053: =item $first, student's first name
17054: 
17055: =item $middle
17056: 
17057: =item $last
17058: 
17059: =item $gene
17060: 
17061: =item $usec
17062: 
17063: =item $end
17064: 
17065: =item $start
17066: 
17067: =item $type
17068: 
17069: =item $locktype
17070: 
17071: =item $cid
17072: 
17073: =item $selfenroll
17074: 
17075: =item $context
17076: 
17077: =item $credits, number of credits student will earn from this class
17078: 
17079: =item $instsec, institutional course section code for student
17080: 
17081: =back
17082: 
17083: 
17084: =item *
17085: 
17086: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
17087: custom role; give a custom role to a user for the level given by URL.  Specify
17088: name and domain of role author, and role name
17089: 
17090: =item *
17091: 
17092: revokerole($udom,$uname,$url,$role) : revoke a role for url
17093: 
17094: =item *
17095: 
17096: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
17097: 
17098: =back
17099: 
17100: =head2 Course Infomation
17101: 
17102: =over 4
17103: 
17104: =item *
17105: 
17106: coursedescription($courseid,$options) : returns a hash of information about the
17107: specified course id, including all environment settings for the
17108: course, the description of the course will be in the hash under the
17109: key 'description'
17110: 
17111: $options is an optional parameter that if supplied is a hash reference that controls
17112: what how this function works.  It has the following key/values:
17113: 
17114: =over 4
17115: 
17116: =item freshen_cache
17117: 
17118: If defined, and the environment cache for the course is valid, it is 
17119: returned in the returned hash.
17120: 
17121: =item one_time
17122: 
17123: If defined, the last cache time is set to _now_
17124: 
17125: =item user
17126: 
17127: If defined, the supplied username is used instead of the current user.
17128: 
17129: 
17130: =back
17131: 
17132: =item *
17133: 
17134: resdata($name,$domain,$type,@which) : request for current parameter
17135: setting for a specific $type, where $type is either 'course' or 'user',
17136: @what should be a list of parameters to ask about. This routine caches
17137: answers for 10 minutes.
17138: 
17139: =item *
17140: 
17141: get_courseresdata($courseid, $domain) : dump the entire course resource
17142: data base, returning a hash that is keyed by the resource name and has
17143: values that are the resource value.  I believe that the timestamps and
17144: versions are also returned.
17145: 
17146: =back
17147: 
17148: =head2 Course Modification
17149: 
17150: =over 4
17151: 
17152: =item *
17153: 
17154: writecoursepref($courseid,%prefs) : write preferences (environment
17155: database) for a course
17156: 
17157: =item *
17158: 
17159: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
17160: 
17161: =item *
17162: 
17163: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
17164: 
17165: =item *
17166: 
17167: is_course($courseid), is_course($cdom, $cnum)
17168: 
17169: Accepts either a combined $courseid (in the form of domain_courseid) or the
17170: two component version $cdom, $cnum. It checks if the specified course exists.
17171: 
17172: Returns:
17173:     undef if the course doesn't exist, otherwise
17174:     in scalar context the combined courseid.
17175:     in list context the two components of the course identifier, domain and 
17176:     courseid.    
17177: 
17178: =back
17179: 
17180: =head2 Bubblesheet Configuration
17181: 
17182: =over 4
17183: 
17184: =item *
17185: 
17186: get_scantron_config($which)
17187: 
17188: $which - the name of the configuration to parse from the file.
17189: 
17190: Parses and returns the bubblesheet configuration line selected as a
17191: hash of configuration file fields.
17192: 
17193: 
17194: Returns:
17195:     If the named configuration is not in the file, an empty
17196:     hash is returned.
17197: 
17198:     a hash with the fields
17199:       name         - internal name for the this configuration setup
17200:       description  - text to display to operator that describes this config
17201:       CODElocation - if 0 or the string 'none'
17202:                           - no CODE exists for this config
17203:                      if -1 || the string 'letter'
17204:                           - a CODE exists for this config and is
17205:                             a string of letters
17206:                      Unsupported value (but planned for future support)
17207:                           if a positive integer
17208:                                - The CODE exists as the first n items from
17209:                                  the question section of the form
17210:                           if the string 'number'
17211:                                - The CODE exists for this config and is
17212:                                  a string of numbers
17213:       CODEstart   - (only matter if a CODE exists) column in the line where
17214:                      the CODE starts
17215:       CODElength  - length of the CODE
17216:       IDstart     - column where the student/employee ID starts
17217:       IDlength    - length of the student/employee ID info
17218:       Qstart      - column where the information from the bubbled
17219:                     'questions' start
17220:       Qlength     - number of columns comprising a single bubble line from
17221:                     the sheet. (usually either 1 or 10)
17222:       Qon         - either a single character representing the character used
17223:                     to signal a bubble was chosen in the positional setup, or
17224:                     the string 'letter' if the letter of the chosen bubble is
17225:                     in the final, or 'number' if a number representing the
17226:                     chosen bubble is in the file (1->A 0->J)
17227:       Qoff        - the character used to represent that a bubble was
17228:                     left blank
17229:       PaperID     - if the scanning process generates a unique number for each
17230:                     sheet scanned the column that this ID number starts in
17231:       PaperIDlength - number of columns that comprise the unique ID number
17232:                       for the sheet of paper
17233:       FirstName   - column that the first name starts in
17234:       FirstNameLength - number of columns that the first name spans
17235:       LastName    - column that the last name starts in
17236:       LastNameLength - number of columns that the last name spans
17237:       BubblesPerRow - number of bubbles available in each row used to
17238:                       bubble an answer. (If not specified, 10 assumed).
17239: 
17240: 
17241: =item *
17242: 
17243: get_scantronformat_file($cdom)
17244: 
17245: $cdom - the course's domain (optional); if not supplied, uses
17246: domain for current $env{'request.course.id'}.
17247: 
17248: Returns an array containing lines from the scantron format file for
17249: the domain of the course.
17250: 
17251: If a url for a custom.tab file is listed in domain's configuration.db,
17252: lines are from this file.
17253: 
17254: Otherwise, if a default.tab has been published in RES space by the
17255: domainconfig user, lines are from this file.
17256: 
17257: Otherwise, fall back to getting lines from the legacy file on the
17258: local server:  /home/httpd/lonTabs/default_scantronformat.tab
17259: 
17260: =back
17261: 
17262: =head2 Resource Subroutines
17263: 
17264: =over 4
17265: 
17266: =item *
17267: 
17268: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
17269: 
17270: =item *
17271: 
17272: repcopy($filename) : subscribes to the requested file, and attempts to
17273: replicate from the owning library server, Might return
17274: 'unavailable', 'not_found', 'forbidden', 'ok', or
17275: 'bad_request', also attempts to grab the metadata for the
17276: resource. Expects the local filesystem pathname
17277: (/home/httpd/html/res/....)
17278: 
17279: =back
17280: 
17281: =head2 Resource Information
17282: 
17283: =over 4
17284: 
17285: =item *
17286: 
17287: EXT($varname,$symb,$udom,$uname,$usection,$recurse,$cid) : evaluates 
17288: and returns the value of a variety of different possible values,
17289: $varname should be a request string, and the other parameters can be
17290: used to specify who and what one is asking about. Ordinarily, $cid 
17291: does not need to be specified, as it is retrived from 
17292: $env{'request.course.id'}, but &Apache::lonnet::EXT() is called
17293: within lonuserstate::loadmap() when initializing a course, before
17294: $env{'request.course.id'} has been set, so it needs to be provided
17295: in that one case.
17296: 
17297: Possible values for $varname are environment.lastname (or other item
17298: from the envirnment hash), user.name (or someother aspect about the
17299: user), resource.0.maxtries (or some other part and parameter of a
17300: resource)
17301: 
17302: =item *
17303: 
17304: directcondval($number) : get current value of a condition; reads from a state
17305: string
17306: 
17307: =item *
17308: 
17309: condval($condidx) : value of condition index based on state
17310: 
17311: =item *
17312: 
17313: metadata($uri,$what,$toolsymb,$liburi,$prefix,$depthcount) : request a
17314: resource's metadata, $what should be either a specific key, or either
17315: 'keys' (to get a list of possible keys) or 'packages' to get a list of
17316: packages that this resource currently uses, the last 3 arguments are 
17317: only used internally for recursive metadata.
17318: 
17319: the toolsymb is only used where the uri is for an external tool (for which
17320: the uri as well as the symb are guaranteed to be unique).
17321: 
17322: this function automatically caches all requests except any made recursively
17323: to retrieve a list of metadata keys for an imported library file ($liburi is 
17324: defined).
17325: 
17326: =item *
17327: 
17328: metadata_query($query,$custom,$customshow) : make a metadata query against the
17329: network of library servers; returns file handle of where SQL and regex results
17330: will be stored for query
17331: 
17332: =item *
17333: 
17334: symbread($filename,$donotrecurse,$ignorecachednull,$checkforblock,$possibles) : 
17335: return symbolic list entry (all arguments optional). 
17336: 
17337: Args: filename is the filename (including path) for the file for which a symb 
17338: is required; donotrecurse, if true will prevent calls to allowed() being made 
17339: to check access status if more than one resource was found in the bighash 
17340: (see rev. 1.249) to avoid an infinite loop if an ambiguous resource is part of 
17341: a randompick); ignorecachednull, if true will prevent a symb of '' being 
17342: returned if $env{$cache_str} is defined as ''; checkforblock if true will
17343: cause possible symbs to be checked to determine if they are subject to content
17344: blocking, if so they will not be included as possible symbs; possibles is a
17345: ref to a hash, which, as a side effect, will be populated with all possible 
17346: symbs (content blocking not tested).
17347:  
17348: returns the data handle
17349: 
17350: =item *
17351: 
17352: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
17353: and is a possible symb for the URL in $thisfn, and if is an encrypted
17354: resource that the user accessed using /enc/ returns a 1 on success, 0
17355: on failure, user must be in a course, as it assumes the existence of
17356: the course initial hash, and uses $env('request.course.id'}.  The third
17357: arg is an optional reference to a scalar.  If this arg is passed in the 
17358: call to symbverify, it will be set to 1 if the symb has been set to be 
17359: encrypted; otherwise it will be null.  
17360: 
17361: =item *
17362: 
17363: symbclean($symb) : removes versions numbers from a symb, returns the
17364: cleaned symb
17365: 
17366: =item *
17367: 
17368: is_on_map($uri) : checks if the $uri is somewhere on the current
17369: course map, user must be in a course for it to work.
17370: 
17371: =item *
17372: 
17373: numval($salt) : return random seed value (addend for rndseed)
17374: 
17375: =item *
17376: 
17377: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
17378: a random seed, all arguments are optional, if they aren't sent it uses the
17379: environment to derive them. Note: if symb isn't sent and it can't get one
17380: from &symbread it will use the current time as its return value
17381: 
17382: =item *
17383: 
17384: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
17385: unfakeable, receipt
17386: 
17387: =item *
17388: 
17389: receipt() : API to ireceipt working off of env values; given out to users
17390: 
17391: =item *
17392: 
17393: countacc($url) : count the number of accesses to a given URL
17394: 
17395: =item *
17396: 
17397: 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
17398: 
17399: =item *
17400: 
17401: 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)
17402: 
17403: =item *
17404: 
17405: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
17406: 
17407: =item *
17408: 
17409: devalidate($symb) : devalidate temporary spreadsheet calculations,
17410: forcing spreadsheet to reevaluate the resource scores next time.
17411: 
17412: =item * 
17413: 
17414: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
17415: when viewing in course context.
17416: 
17417:  input: six args -- filename (decluttered), course number, course domain,
17418:                     url, symb (if registered) and group (if this is a 
17419:                     group item -- e.g., bulletin board, group page etc.).
17420: 
17421:  output: array of five scalars --
17422:          $cfile -- url for file editing if editable on current server
17423:          $home -- homeserver of resource (i.e., for author if published,
17424:                                           or course if uploaded.).
17425:          $switchserver --  1 if server switch will be needed.
17426:          $forceedit -- 1 if icon/link should be to go to edit mode 
17427:          $forceview -- 1 if icon/link should be to go to view mode
17428: 
17429: =item *
17430: 
17431: is_course_upload($file,$cnum,$cdom)
17432: 
17433: Used in course context to determine if current file was uploaded to 
17434: the course (i.e., would be found in /userfiles/docs on the course's 
17435: homeserver.
17436: 
17437:   input: 3 args -- filename (decluttered), course number and course domain.
17438:   output: boolean -- 1 if file was uploaded.
17439: 
17440: =back
17441: 
17442: =head2 Storing/Retreiving Data
17443: 
17444: =over 4
17445: 
17446: =item *
17447: 
17448: store($storehash,$symb,$namespace,$udom,$uname,$laststore) : stores hash
17449: permanently for this url; hashref needs to be given and should be a \%hashname;
17450: the remaining args aren't required and if they aren't passed or are '' they will
17451: be derived from the env (with the exception of $laststore, which is an 
17452: optional arg used when a user's submission is stored in grading).
17453: $laststore is $version=$timestamp, where $version is the most recent version
17454: number retrieved for the corresponding $symb in the $namespace db file, and
17455: $timestamp is the timestamp for that transaction (UNIX time).
17456: $laststore is currently only passed when cstore() is called by 
17457: structuretags::finalize_storage().
17458: 
17459: =item *
17460: 
17461: cstore($storehash,$symb,$namespace,$udom,$uname,$laststore) : same as store
17462: but uses critical subroutine
17463: 
17464: =item *
17465: 
17466: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
17467: all args are optional
17468: 
17469: =item *
17470: 
17471: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
17472: dumps the complete (or key matching regexp) namespace into a hash
17473: ($udom, $uname, $regexp, $range are optional) for a namespace that is
17474: normally &store()ed into
17475: 
17476: $range should be either an integer '100' (give me the first 100
17477:                                            matching records)
17478:               or be  two integers sperated by a - with no spaces
17479:                  '30-50' (give me the 30th through the 50th matching
17480:                           records)
17481: 
17482: 
17483: =item *
17484: 
17485: putstore($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog) :
17486: replaces a &store() version of data with a replacement set of data
17487: for a particular resource in a namespace passed in the $storehash hash 
17488: reference. If $tolog is true, the transaction is logged in the courselog
17489: with an action=PUTSTORE.
17490: 
17491: =item *
17492: 
17493: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
17494: works very similar to store/cstore, but all data is stored in a
17495: temporary location and can be reset using tmpreset, $storehash should
17496: be a hash reference, returns nothing on success
17497: 
17498: =item *
17499: 
17500: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
17501: similar to restore, but all data is stored in a temporary location and
17502: can be reset using tmpreset. Returns a hash of values on success,
17503: error string otherwise.
17504: 
17505: =item *
17506: 
17507: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
17508: deltes all keys for $symb form the temporary storage hash.
17509: 
17510: =item *
17511: 
17512: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
17513: reference filled in from namesp ($udom and $uname are optional)
17514: 
17515: =item *
17516: 
17517: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
17518: namesp ($udom and $uname are optional)
17519: 
17520: =item *
17521: 
17522: dump($namespace,$udom,$uname,$regexp,$range) : 
17523: dumps the complete (or key matching regexp) namespace into a hash
17524: ($udom, $uname, $regexp, $range are optional)
17525: 
17526: $range should be either an integer '100' (give me the first 100
17527:                                            matching records)
17528:               or be  two integers sperated by a - with no spaces
17529:                  '30-50' (give me the 30th through the 50th matching
17530:                           records)
17531: =item *
17532: 
17533: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
17534: $store can be a scalar, an array reference, or if the amount to be 
17535: incremented is > 1, a hash reference.
17536: 
17537: ($udom and $uname are optional)
17538: 
17539: =item *
17540: 
17541: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
17542: ($udom and $uname are optional)
17543: 
17544: =item *
17545: 
17546: cput($namespace,$storehash,$udom,$uname) : critical put
17547: ($udom and $uname are optional)
17548: 
17549: =item *
17550: 
17551: newput($namespace,$storehash,$udom,$uname) :
17552: 
17553: Attempts to store the items in the $storehash, but only if they don't
17554: currently exist, if this succeeds you can be certain that you have 
17555: successfully created a new key value pair in the $namespace db.
17556: 
17557: 
17558: Args:
17559:  $namespace: name of database to store values to
17560:  $storehash: hashref to store to the db
17561:  $udom: (optional) domain of user containing the db
17562:  $uname: (optional) name of user caontaining the db
17563: 
17564: Returns:
17565:  'ok' -> succeeded in storing all keys of $storehash
17566:  'key_exists: <key>' -> failed to anything out of $storehash, as at
17567:                         least <key> already existed in the db (other
17568:                         requested keys may also already exist)
17569:  'error: <msg>' -> unable to tie the DB or other error occurred
17570:  'con_lost' -> unable to contact request server
17571:  'refused' -> action was not allowed by remote machine
17572: 
17573: 
17574: =item *
17575: 
17576: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
17577: reference filled in from namesp (encrypts the return communication)
17578: ($udom and $uname are optional)
17579: 
17580: =item *
17581: 
17582: log($udom,$name,$home,$message) : write to permanent log for user; use
17583: critical subroutine
17584: 
17585: =item *
17586: 
17587: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
17588: array reference filled in from namespace found in domain level on either
17589: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
17590: 
17591: =item *
17592: 
17593: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
17594: domain level either on specified domain server ($uhome) or primary domain 
17595: server ($udom and $uhome are optional)
17596: 
17597: =item * 
17598: 
17599: get_domain_defaults($target_domain,$ignore_cache) : returns hash with defaults 
17600: for: authentication, language, quotas, timezone, date locale, and portal URL in
17601: the target domain.
17602: 
17603: May also include additional key => value pairs for the following groups:
17604: 
17605: =over
17606: 
17607: =item
17608: disk quotas (MB allocated by default to portfolios and authoring spaces).
17609: 
17610: =over
17611: 
17612: =item defaultquota, authorquota
17613: 
17614: =back
17615: 
17616: =item
17617: tools (availability of aboutme page, blog, webDAV access for authoring spaces,
17618: portfolio for users).
17619: 
17620: =over
17621: 
17622: =item
17623: aboutme, blog, webdav, portfolio
17624: 
17625: =back
17626: 
17627: =item
17628: requestcourses: ability to request courses, and how requests are processed.
17629: 
17630: =over
17631: 
17632: =item
17633: official, unofficial, community, textbook, placement
17634: 
17635: =back
17636: 
17637: =item
17638: inststatus: types of institutional affiliation, and order in which they are displayed.
17639: 
17640: =over
17641: 
17642: =item
17643: inststatustypes, inststatusorder, inststatusguest
17644: 
17645: =back
17646: 
17647: =item
17648: coursedefaults: can PDF forms can be created, default credits for courses, default quotas (MB)
17649: for course's uploaded content.
17650: 
17651: =over
17652: 
17653: =item
17654: canuse_pdfforms, officialcredits, unofficialcredits, textbookcredits, officialquota, unofficialquota, 
17655: communityquota, textbookquota, placementquota
17656: 
17657: =back
17658: 
17659: =item
17660: usersessions: set options for hosting of your users in other domains, and hosting of users from other domains
17661: on your servers.
17662: 
17663: =over
17664: 
17665: =item 
17666: remotesessions, hostedsessions
17667: 
17668: =back
17669: 
17670: =back
17671: 
17672: In cases where a domain coordinator has never used the "Set Domain Configuration"
17673: utility to create a configuration.db file on a domain's primary library server 
17674: only the following domain defaults: auth_def, auth_arg_def, lang_def
17675: -- corresponding values are authentication type (internal, krb4, krb5,
17676: or localauth), initial password or a kerberos realm, language (e.g., en-us) -- 
17677: will be available. Values are retrieved from cache (if current), unless the
17678: optional $ignore_cache arg is true, or from domain's configuration.db (if available),
17679: or lastly from values in lonTabs/dns_domain,tab, or lonTabs/domain.tab.
17680: 
17681: Typical usage:
17682: 
17683: %domdefaults = &get_domain_defaults($target_domain);
17684: 
17685: =back
17686: 
17687: =head2 Network Status Functions
17688: 
17689: =over 4
17690: 
17691: =item *
17692: 
17693: dirlist() : return directory list based on URI (first arg).
17694: 
17695: Inputs: 1 required, 5 optional.
17696: 
17697: =over
17698: 
17699: =item 
17700: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
17701: 
17702: =item
17703: $userdomain - domain of user/course to be listed. Extracted from $uri if absent. 
17704: 
17705: =item
17706: $username -  username of user/course to be listed. Extracted from $uri if absent. 
17707: 
17708: =item
17709: $getpropath - boolean: 1 if prepend path using &propath(). 
17710: 
17711: =item
17712: $getuserdir - boolean: 1 if prepend path for "userfiles".
17713: 
17714: =item 
17715: $alternateRoot - path to prepend in place of path from $uri.
17716: 
17717: =back
17718: 
17719: Returns: Array of up to two items.
17720: 
17721: =over
17722: 
17723: a reference to an array of files/subdirectories
17724: 
17725: =over
17726: 
17727: Each element in the array of files/subdirectories is a & separated list of
17728: item name and the result of running stat on the item.  If dirlist was requested
17729: for a file instead of a directory, the item name will be ''. For a directory 
17730: listing, if the item is a metadata file, the element will end &N&M 
17731: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
17732: default copyright set (1).  
17733: 
17734: =back
17735: 
17736: a scalar containing error condition (if encountered).
17737: 
17738: =over
17739: 
17740: =item 
17741: no_host (no homeserver identified for $username:$domain).
17742: 
17743: =item 
17744: no_such_host (server contacted for listing not identified as valid host).
17745: 
17746: =item 
17747: con_lost (connection to remote server failed).
17748: 
17749: =item 
17750: refused (invalid $username:$domain received on lond side).
17751: 
17752: =item 
17753: no_such_dir (directory at specified path on lond side does not exist). 
17754: 
17755: =item 
17756: empty (directory at specified path on lond side is empty).
17757: 
17758: =over
17759: 
17760: This is currently not encountered because the &ls3, &ls2, 
17761: &ls (_handler) routines on the lond side do not filter out
17762: . and .. from a directory listing. 
17763: 
17764: =back
17765: 
17766: =back
17767: 
17768: =back
17769: 
17770: =item *
17771: 
17772: spareserver() : find server with least workload from spare.tab
17773: 
17774: 
17775: =item *
17776: 
17777: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
17778: if there is no corresponding loncapa host.
17779: 
17780: =back
17781: 
17782: 
17783: =head2 Apache Request
17784: 
17785: =over 4
17786: 
17787: =item *
17788: 
17789: ssi($url,%hash) : server side include, does a complete request cycle on url to
17790: localhost, posts hash
17791: 
17792: =back
17793: 
17794: =head2 Data to String to Data
17795: 
17796: =over 4
17797: 
17798: =item *
17799: 
17800: hash2str(%hash) : convert a hash into a string complete with escaping and '='
17801: and '&' separators, supports elements that are arrayrefs and hashrefs
17802: 
17803: =item *
17804: 
17805: hashref2str($hashref) : convert a hashref into a string complete with
17806: escaping and '=' and '&' separators, supports elements that are
17807: arrayrefs and hashrefs
17808: 
17809: =item *
17810: 
17811: arrayref2str($arrayref) : convert an arrayref into a string complete
17812: with escaping and '&' separators, supports elements that are arrayrefs
17813: and hashrefs
17814: 
17815: =item *
17816: 
17817: str2hash($string) : convert string to hash using unescaping and
17818: splitting on '=' and '&', supports elements that are arrayrefs and
17819: hashrefs
17820: 
17821: =item *
17822: 
17823: str2array($string) : convert string to hash using unescaping and
17824: splitting on '&', supports elements that are arrayrefs and hashrefs
17825: 
17826: =back
17827: 
17828: =head2 Logging Routines
17829: 
17830: 
17831: These routines allow one to make log messages in the lonnet.log and
17832: lonnet.perm logfiles.
17833: 
17834: =over 4
17835: 
17836: =item *
17837: 
17838: logtouch() : make sure the logfile, lonnet.log, exists
17839: 
17840: =item *
17841: 
17842: logthis() : append message to the normal lonnet.log file, it gets
17843: preiodically rolled over and deleted.
17844: 
17845: =item *
17846: 
17847: logperm() : append a permanent message to lonnet.perm.log, this log
17848: file never gets deleted by any automated portion of the system, only
17849: messages of critical importance should go in here.
17850: 
17851: 
17852: =back
17853: 
17854: =head2 General File Helper Routines
17855: 
17856: =over 4
17857: 
17858: =item *
17859: 
17860: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
17861: (a) files in /uploaded
17862:   (i) If a local copy of the file exists - 
17863:       compares modification date of local copy with last-modified date for 
17864:       definitive version stored on home server for course. If local copy is 
17865:       stale, requests a new version from the home server and stores it. 
17866:       If the original has been removed from the home server, then local copy 
17867:       is unlinked.
17868:   (ii) If local copy does not exist -
17869:       requests the file from the home server and stores it. 
17870:   
17871:   If $caller is 'uploadrep':  
17872:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
17873:     for request for files originally uploaded via DOCS. 
17874:      - returns 'ok' if fresh local copy now available, -1 otherwise.
17875:   
17876:   Otherwise:
17877:      This indicates a call from the content generation phase of the request.
17878:      -  returns the entire contents of the file or -1.
17879:      
17880: (b) files in /res
17881:    - returns the entire contents of a file or -1; 
17882:    it properly subscribes to and replicates the file if neccessary.
17883: 
17884: 
17885: =item *
17886: 
17887: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
17888:                   reference
17889: 
17890: returns either a stat() list of data about the file or an empty list
17891: if the file doesn't exist or couldn't find out about it (connection
17892: problems or user unknown)
17893: 
17894: =item *
17895: 
17896: filelocation($dir,$file) : returns file system location of a file
17897: based on URI; meant to be "fairly clean" absolute reference, $dir is a
17898: directory that relative $file lookups are to looked in ($dir of /a/dir
17899: and a file of ../bob will become /a/bob)
17900: 
17901: =item *
17902: 
17903: hreflocation($dir,$file) : returns file system location or a URL; same as
17904: filelocation except for hrefs
17905: 
17906: =item *
17907: 
17908: declutter() : declutters URLs -- remove beginning slashes, 'res' etc.
17909: also removes beginning /home/httpd/html unless /priv/ follows it.
17910: 
17911: =back
17912: 
17913: =head2 Usererfile file routines (/uploaded*)
17914: 
17915: =over 4
17916: 
17917: =item *
17918: 
17919: userfileupload(): main rotine for putting a file in a user or course's
17920:                   filespace, arguments are,
17921: 
17922:  formname - required - this is the name of the element in $env where the
17923:            filename, and the contents of the file to create/modifed exist
17924:            the filename is in $env{'form.'.$formname.'.filename'} and the
17925:            contents of the file is located in $env{'form.'.$formname}
17926:  context - if coursedoc, store the file in the course of the active role
17927:              of the current user; 
17928:            if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
17929:            if 'canceloverwrite': delete file in tmp/overwrites directory
17930:  subdir - required - subdirectory to put the file in under ../userfiles/
17931:          if undefined, it will be placed in "unknown"
17932: 
17933:  (This routine calls clean_filename() to remove any dangerous
17934:  characters from the filename, and then calls finuserfileupload() to
17935:  complete the transaction)
17936: 
17937:  returns either the url of the uploaded file (/uploaded/....) if successful
17938:  and /adm/notfound.html if unsuccessful
17939: 
17940: =item *
17941: 
17942: clean_filename(): routine for cleaing a filename up for storage in
17943:                  userfile space, argument is:
17944: 
17945:  filename - proposed filename
17946: 
17947: returns: the new clean filename
17948: 
17949: =item *
17950: 
17951: finishuserfileupload(): routine that creates and sends the file to
17952: userspace, probably shouldn't be called directly
17953: 
17954:   docuname: username or courseid of destination for the file
17955:   docudom: domain of user/course of destination for the file
17956:   formname: same as for userfileupload()
17957:   fname: filename (including subdirectories) for the file
17958:   parser: if 'parse', will parse (html) file to extract references to objects, links etc.
17959:           if hashref, and context is scantron, will convert csv format to standard format
17960:   allfiles: reference to hash used to store objects found by parser
17961:   codebase: reference to hash used for codebases of java objects found by parser
17962:   thumbwidth: width (pixels) of thumbnail to be created for uploaded image
17963:   thumbheight: height (pixels) of thumbnail to be created for uploaded image
17964:   resizewidth: width to be used to resize image using resizeImage from ImageMagick
17965:   resizeheight: height to be used to resize image using resizeImage from ImageMagick
17966:   context: if 'overwrite', will move the uploaded file from its temporary location to
17967:             userfiles to facilitate overwriting a previously uploaded file with same name.
17968:   mimetype: reference to scalar to accommodate mime type determined
17969:             from File::MMagic if $parser = parse.
17970: 
17971:  returns either the url of the uploaded file (/uploaded/....) if successful
17972:  and /adm/notfound.html if unsuccessful (or an error message if context 
17973:  was 'overwrite').
17974:  
17975: 
17976: =item *
17977: 
17978: renameuserfile(): renames an existing userfile to a new name
17979: 
17980:   Args:
17981:    docuname: username or courseid of destination for the file
17982:    docudom: domain of user/course of destination for the file
17983:    old: current file name (including any subdirs under userfiles)
17984:    new: desired file name (including any subdirs under userfiles)
17985: 
17986: =item *
17987: 
17988: mkdiruserfile(): creates a directory is a userfiles dir
17989: 
17990:   Args:
17991:    docuname: username or courseid of destination for the file
17992:    docudom: domain of user/course of destination for the file
17993:    dir: dir to create (including any subdirs under userfiles)
17994: 
17995: =item *
17996: 
17997: removeuserfile(): removes a file that exists in userfiles
17998: 
17999:   Args:
18000:    docuname: username or courseid of destination for the file
18001:    docudom: domain of user/course of destination for the file
18002:    fname: filname to delete (including any subdirs under userfiles)
18003: 
18004: =item *
18005: 
18006: removeuploadedurl(): convience function for removeuserfile()
18007: 
18008:   Args:
18009:    url:  a full /uploaded/... url to delete
18010: 
18011: =item * 
18012: 
18013: get_portfile_permissions():
18014:   Args:
18015:     domain: domain of user or course contain the portfolio files
18016:     user: name of user or num of course contain the portfolio files
18017:   Returns:
18018:     hashref of a dump of the proper file_permissions.db
18019:    
18020: 
18021: =item * 
18022: 
18023: get_access_controls():
18024: 
18025: Args:
18026:   current_permissions: the hash ref returned from get_portfile_permissions()
18027:   group: (optional) the group you want the files associated with
18028:   file: (optional) the file you want access info on
18029: 
18030: Returns:
18031:     a hash (keys are file names) of hashes containing
18032:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
18033:         values are XML containing access control settings (see below) 
18034: 
18035: Internal notes:
18036: 
18037:  access controls are stored in file_permissions.db as key=value pairs.
18038:     key -> path to file/file_name\0uniqueID:scope_end_start
18039:         where scope -> public,guest,course,group,domains or users.
18040:               end -> UNIX time for end of access (0 -> no end date)
18041:               start -> UNIX time for start of access
18042: 
18043:     value -> XML description of access control
18044:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
18045:             <start></start>
18046:             <end></end>
18047: 
18048:             <password></password>  for scope type = guest
18049: 
18050:             <domain></domain>     for scope type = course or group
18051:             <number></number>
18052:             <roles id="">
18053:              <role></role>
18054:              <access></access>
18055:              <section></section>
18056:              <group></group>
18057:             </roles>
18058: 
18059:             <dom></dom>         for scope type = domains
18060: 
18061:             <users>             for scope type = users
18062:              <user>
18063:               <uname></uname>
18064:               <udom></udom>
18065:              </user>
18066:             </users>
18067:            </scope> 
18068:               
18069:  Access data is also aggregated for each file in an additional key=value pair:
18070:  key -> path to file/file_name\0accesscontrol 
18071:  value -> reference to hash
18072:           hash contains key = value pairs
18073:           where key = uniqueID:scope_end_start
18074:                 value = UNIX time record was last updated
18075: 
18076:           Used to improve speed of look-ups of access controls for each file.  
18077:  
18078:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
18079: 
18080: =item *
18081: 
18082: modify_access_controls():
18083: 
18084: Modifies access controls for a portfolio file
18085: Args
18086: 1. file name
18087: 2. reference to hash of required changes,
18088: 3. domain
18089: 4. username
18090:   where domain,username are the domain of the portfolio owner 
18091:   (either a user or a course) 
18092: 
18093: Returns:
18094: 1. result of additions or updates ('ok' or 'error', with error message). 
18095: 2. result of deletions ('ok' or 'error', with error message).
18096: 3. reference to hash of any new or updated access controls.
18097: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
18098:    key = integer (inbound ID)
18099:    value = uniqueID
18100: 
18101: =item *
18102: 
18103: get_timebased_id():
18104: 
18105: Attempts to get a unique timestamp-based suffix for use with items added to a 
18106: course via the Course Editor (e.g., folders, composite pages, 
18107: group bulletin boards).
18108: 
18109: Args: (first three required; six others optional)
18110: 
18111: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
18112:    docssequence, or name of group
18113: 
18114: 2. keyid (alphanumeric): name of temporary locking key in hash,
18115:    e.g., num, boardids
18116: 
18117: 3. namespace: name of gdbm file used to store suffixes already assigned;  
18118:    file will be named nohist_namespace.db
18119: 
18120: 4. cdom: domain of course; default is current course domain from %env
18121: 
18122: 5. cnum: course number; default is current course number from %env
18123: 
18124: 6. idtype: set to concat if an additional digit is to be appended to the 
18125:    unix timestamp to form the suffix, if the plain timestamp is already
18126:    in use.  Default is to not do this, but simply increment the unix 
18127:    timestamp by 1 until a unique key is obtained.
18128: 
18129: 7. who: holder of locking key; defaults to user:domain for user.
18130: 
18131: 8. locktries: number of attempts to obtain a lock (sleep of 1s before 
18132:    retrying); default is 3.
18133: 
18134: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.  
18135: 
18136: Returns:
18137: 
18138: 1. suffix obtained (numeric)
18139: 
18140: 2. result of deleting locking key (ok if deleted, or lock never obtained)
18141: 
18142: 3. error: contains (localized) error message if an error occurred.
18143: 
18144: 
18145: =back
18146: 
18147: =head2 HTTP Helper Routines
18148: 
18149: =over 4
18150: 
18151: =item *
18152: 
18153: escape() : unpack non-word characters into CGI-compatible hex codes
18154: 
18155: =item *
18156: 
18157: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
18158: 
18159: =back
18160: 
18161: =head1 PRIVATE SUBROUTINES
18162: 
18163: =head2 Underlying communication routines (Shouldn't call)
18164: 
18165: =over 4
18166: 
18167: =item *
18168: 
18169: subreply() : tries to pass a message to lonc, returns con_lost if incapable
18170: 
18171: =item *
18172: 
18173: reply() : uses subreply to send a message to remote machine, logs all failures
18174: 
18175: =item *
18176: 
18177: critical() : passes a critical message to another server; if cannot
18178: get through then place message in connection buffer directory and
18179: returns con_delayed, if incapable of saving message, returns
18180: con_failed
18181: 
18182: =item *
18183: 
18184: reconlonc() : tries to reconnect lonc client processes.
18185: 
18186: =back
18187: 
18188: =head2 Resource Access Logging
18189: 
18190: =over 4
18191: 
18192: =item *
18193: 
18194: flushcourselogs() : flush (save) buffer logs and access logs
18195: 
18196: =item *
18197: 
18198: courselog($what) : save message for course in hash
18199: 
18200: =item *
18201: 
18202: courseacclog($what) : save message for course using &courselog().  Perform
18203: special processing for specific resource types (problems, exams, quizzes, etc).
18204: 
18205: =item *
18206: 
18207: goodbye() : flush course logs and log shutting down; it is called in srm.conf
18208: as a PerlChildExitHandler
18209: 
18210: =back
18211: 
18212: =head2 Other
18213: 
18214: =over 4
18215: 
18216: =item *
18217: 
18218: symblist($mapname,%newhash) : update symbolic storage links
18219: 
18220: =back
18221: 
18222: =cut
18223: 

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