File:  [LON-CAPA] / loncom / lonnet / perl / lonnet.pm
Revision 1.1518: download - view: text, annotated - select for diffs
Fri Nov 17 17:02:22 2023 UTC (8 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Available editors in Authoring Space: value set for specific author can
  override domain default.

    1: # The LearningOnline Network
    2: # TCP networking package
    3: #
    4: # $Id: lonnet.pm,v 1.1518 2023/11/17 17:02:22 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','domexttool',
 2761:                                   'exttool','privacy'],$domain);
 2762:     my @coursetypes = ('official','unofficial','community','textbook','placement');
 2763:     if (ref($domconfig{'defaults'}) eq 'HASH') {
 2764:         $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'}; 
 2765:         $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
 2766:         $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
 2767:         $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
 2768:         $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
 2769:         $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
 2770:         $domdefaults{'portal_def_email'} = $domconfig{'defaults'}{'portal_def_email'};
 2771:         $domdefaults{'portal_def_web'} = $domconfig{'defaults'}{'portal_def_web'};
 2772:         $domdefaults{'intauth_cost'} = $domconfig{'defaults'}{'intauth_cost'};
 2773:         $domdefaults{'intauth_switch'} = $domconfig{'defaults'}{'intauth_switch'};
 2774:         $domdefaults{'intauth_check'} = $domconfig{'defaults'}{'intauth_check'};
 2775:         $domdefaults{'unamemap_rule'} = $domconfig{'defaults'}{'unamemap_rule'};
 2776:     } else {
 2777:         $domdefaults{'lang_def'} = &domain($domain,'lang_def');
 2778:         $domdefaults{'auth_def'} = &domain($domain,'auth_def');
 2779:         $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
 2780:     }
 2781:     if (ref($domconfig{'quotas'}) eq 'HASH') {
 2782:         if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
 2783:             $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
 2784:         } else {
 2785:             $domdefaults{'defaultquota'} = $domconfig{'quotas'};
 2786:         }
 2787:         my @usertools = ('aboutme','blog','webdav','portfolio');
 2788:         foreach my $item (@usertools) {
 2789:             if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
 2790:                 $domdefaults{$item} = $domconfig{'quotas'}{$item};
 2791:             }
 2792:         }
 2793:         if (ref($domconfig{'quotas'}{'authorquota'}) eq 'HASH') {
 2794:             $domdefaults{'authorquota'} = $domconfig{'quotas'}{'authorquota'};
 2795:         }
 2796:     }
 2797:     if (ref($domconfig{'requestcourses'}) eq 'HASH') {
 2798:         foreach my $item ('official','unofficial','community','textbook','placement') {
 2799:             $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
 2800:         }
 2801:     }
 2802:     if (ref($domconfig{'requestauthor'}) eq 'HASH') {
 2803:         $domdefaults{'requestauthor'} = $domconfig{'requestauthor'};
 2804:     }
 2805:     if (ref($domconfig{'authordefaults'}) eq 'HASH') {
 2806:         foreach my $item ('nocodemirror','copyright','sourceavail','domcoordacc','editors') {
 2807:             if ($item eq 'editors') {
 2808:                 if (ref($domconfig{'authordefaults'}{'editors'}) eq 'ARRAY') {
 2809:                     $domdefaults{$item} = join(',',@{$domconfig{'authordefaults'}{'editors'}});
 2810:                 }
 2811:             } else {
 2812:                 $domdefaults{$item} = $domconfig{'authordefaults'}{$item};
 2813:             }
 2814:         }
 2815:     }
 2816:     if (ref($domconfig{'inststatus'}) eq 'HASH') {
 2817:         foreach my $item ('inststatustypes','inststatusorder','inststatusguest') {
 2818:             $domdefaults{$item} = $domconfig{'inststatus'}{$item};
 2819:         }
 2820:     }
 2821:     if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
 2822:         $domdefaults{'canuse_pdfforms'} = $domconfig{'coursedefaults'}{'canuse_pdfforms'};
 2823:         $domdefaults{'usejsme'} = $domconfig{'coursedefaults'}{'usejsme'};
 2824:         $domdefaults{'inline_chem'} = $domconfig{'coursedefaults'}{'inline_chem'};
 2825:         $domdefaults{'uselcmath'} = $domconfig{'coursedefaults'}{'uselcmath'};
 2826:         if (ref($domconfig{'coursedefaults'}{'postsubmit'}) eq 'HASH') {
 2827:             $domdefaults{'postsubmit'} = $domconfig{'coursedefaults'}{'postsubmit'}{'client'};
 2828:         }
 2829:         foreach my $type (@coursetypes) {
 2830:             if (ref($domconfig{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
 2831:                 unless ($type eq 'community') {
 2832:                     $domdefaults{$type.'credits'} = $domconfig{'coursedefaults'}{'coursecredits'}{$type};
 2833:                 }
 2834:             }
 2835:             if (ref($domconfig{'coursedefaults'}{'uploadquota'}) eq 'HASH') {
 2836:                 $domdefaults{$type.'quota'} = $domconfig{'coursedefaults'}{'uploadquota'}{$type};
 2837:             }
 2838:             if (ref($domconfig{'coursedefaults'}{'coursequota'}) eq 'HASH') {
 2839:                 $domdefaults{$type.'coursequota'} = $domconfig{'coursedefaults'}{'coursequota'}{$type};
 2840:             }
 2841:             if ($domdefaults{'postsubmit'} eq 'on') {
 2842:                 if (ref($domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}) eq 'HASH') {
 2843:                     $domdefaults{$type.'postsubtimeout'} = 
 2844:                         $domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}{$type}; 
 2845:                 }
 2846:             }
 2847:             if (ref($domconfig{'coursedefaults'}{'domexttool'}) eq 'HASH') {
 2848:                 $domdefaults{$type.'domexttool'} = $domconfig{'coursedefaults'}{'domexttool'}{$type};
 2849:             } else {
 2850:                 $domdefaults{$type.'domexttool'} = 1;
 2851:             }
 2852:             if (ref($domconfig{'coursedefaults'}{'exttool'}) eq 'HASH') {
 2853:                 $domdefaults{$type.'exttool'} = $domconfig{'coursedefaults'}{'exttool'}{$type};
 2854:             } else {
 2855:                 $domdefaults{$type.'exttool'} = 0;
 2856:             }
 2857:         }
 2858:         if (ref($domconfig{'coursedefaults'}{'canclone'}) eq 'HASH') {
 2859:             if (ref($domconfig{'coursedefaults'}{'canclone'}{'instcode'}) eq 'ARRAY') {
 2860:                 my @clonecodes = @{$domconfig{'coursedefaults'}{'canclone'}{'instcode'}};
 2861:                 if (@clonecodes) {
 2862:                     $domdefaults{'canclone'} = join('+',@clonecodes);
 2863:                 }
 2864:             }
 2865:         } elsif ($domconfig{'coursedefaults'}{'canclone'}) {
 2866:             $domdefaults{'canclone'}=$domconfig{'coursedefaults'}{'canclone'};
 2867:         }
 2868:         if ($domconfig{'coursedefaults'}{'texengine'}) {
 2869:             $domdefaults{'texengine'} = $domconfig{'coursedefaults'}{'texengine'};
 2870:         }
 2871:         if (exists($domconfig{'coursedefaults'}{'ltiauth'})) {
 2872:             $domdefaults{'crsltiauth'} = $domconfig{'coursedefaults'}{'ltiauth'};
 2873:         }
 2874:     }
 2875:     if (ref($domconfig{'usersessions'}) eq 'HASH') {
 2876:         if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
 2877:             $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
 2878:         }
 2879:         if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
 2880:             $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
 2881:         }
 2882:         if (ref($domconfig{'usersessions'}{'offloadnow'}) eq 'HASH') {
 2883:             $domdefaults{'offloadnow'} = $domconfig{'usersessions'}{'offloadnow'};
 2884:         }
 2885:         if (ref($domconfig{'usersessions'}{'offloadoth'}) eq 'HASH') {
 2886:             $domdefaults{'offloadoth'} = $domconfig{'usersessions'}{'offloadoth'};
 2887:         }
 2888:     }
 2889:     if (ref($domconfig{'selfenrollment'}) eq 'HASH') {
 2890:         if (ref($domconfig{'selfenrollment'}{'admin'}) eq 'HASH') {
 2891:             my @settings = ('types','registered','enroll_dates','access_dates','section',
 2892:                             'approval','limit');
 2893:             foreach my $type (@coursetypes) {
 2894:                 if (ref($domconfig{'selfenrollment'}{'admin'}{$type}) eq 'HASH') {
 2895:                     my @mgrdc = ();
 2896:                     foreach my $item (@settings) {
 2897:                         if ($domconfig{'selfenrollment'}{'admin'}{$type}{$item} eq '0') {
 2898:                             push(@mgrdc,$item);
 2899:                         }
 2900:                     }
 2901:                     if (@mgrdc) {
 2902:                         $domdefaults{$type.'selfenrolladmdc'} = join(',',@mgrdc);
 2903:                     }
 2904:                 }
 2905:             }
 2906:         }
 2907:         if (ref($domconfig{'selfenrollment'}{'default'}) eq 'HASH') {
 2908:             foreach my $type (@coursetypes) {
 2909:                 if (ref($domconfig{'selfenrollment'}{'default'}{$type}) eq 'HASH') {
 2910:                     foreach my $item (keys(%{$domconfig{'selfenrollment'}{'default'}{$type}})) {
 2911:                         $domdefaults{$type.'selfenroll'.$item} = $domconfig{'selfenrollment'}{'default'}{$type}{$item};
 2912:                     }
 2913:                 }
 2914:             }
 2915:         }
 2916:     }
 2917:     if (ref($domconfig{'coursecategories'}) eq 'HASH') {
 2918:         $domdefaults{'catauth'} = 'std';
 2919:         $domdefaults{'catunauth'} = 'std';
 2920:         if ($domconfig{'coursecategories'}{'auth'}) {
 2921:             $domdefaults{'catauth'} = $domconfig{'coursecategories'}{'auth'};
 2922:         }
 2923:         if ($domconfig{'coursecategories'}{'unauth'}) {
 2924:             $domdefaults{'catunauth'} = $domconfig{'coursecategories'}{'unauth'};
 2925:         }
 2926:     }
 2927:     if (ref($domconfig{'ssl'}) eq 'HASH') {
 2928:         if (ref($domconfig{'ssl'}{'replication'}) eq 'HASH') {
 2929:             $domdefaults{'replication'} = $domconfig{'ssl'}{'replication'};
 2930:         }
 2931:         if (ref($domconfig{'ssl'}{'connto'}) eq 'HASH') {
 2932:             $domdefaults{'connect'} = $domconfig{'ssl'}{'connto'};
 2933:         }
 2934:         if (ref($domconfig{'ssl'}{'connfrom'}) eq 'HASH') {
 2935:             $domdefaults{'connect'} = $domconfig{'ssl'}{'connfrom'};
 2936:         }
 2937:     }
 2938:     if (ref($domconfig{'trust'}) eq 'HASH') {
 2939:         my @prefixes = qw(content shared enroll othcoau coaurem domroles catalog reqcrs msg);
 2940:         foreach my $prefix (@prefixes) {
 2941:             if (ref($domconfig{'trust'}{$prefix}) eq 'HASH') {
 2942:                 $domdefaults{'trust'.$prefix} = $domconfig{'trust'}{$prefix};
 2943:             }
 2944:         }
 2945:     }
 2946:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
 2947:         $domdefaults{'autofailsafe'} = $domconfig{'autoenroll'}{'autofailsafe'};
 2948:         $domdefaults{'failsafe'} = $domconfig{'autoenroll'}{'failsafe'};
 2949:     }
 2950:     if (ref($domconfig{'helpsettings'}) eq 'HASH') {
 2951:         $domdefaults{'submitbugs'} = $domconfig{'helpsettings'}{'submitbugs'};
 2952:         if (ref($domconfig{'helpsettings'}{'adhoc'}) eq 'HASH') {
 2953:             $domdefaults{'adhocroles'} = $domconfig{'helpsettings'}{'adhoc'};
 2954:         }
 2955:     }
 2956:     if (ref($domconfig{'wafproxy'}) eq 'HASH') {
 2957:         foreach my $item ('ipheader','trusted','vpnint','vpnext','sslopt') {
 2958:             if ($domconfig{'wafproxy'}{$item}) {
 2959:                 $domdefaults{'waf_'.$item} = $domconfig{'wafproxy'}{$item};
 2960:             }
 2961:         }
 2962:     }
 2963:     if (ref($domconfig{'ltisec'}) eq 'HASH') {
 2964:         if (ref($domconfig{'ltisec'}{'encrypt'}) eq 'HASH') {
 2965:             $domdefaults{'linkprotenc_crs'} = $domconfig{'ltisec'}{'encrypt'}{'crs'};
 2966:             $domdefaults{'linkprotenc_dom'} = $domconfig{'ltisec'}{'encrypt'}{'dom'};
 2967:             $domdefaults{'ltienc_consumers'} = $domconfig{'ltisec'}{'encrypt'}{'consumers'};
 2968:         }
 2969:         if (ref($domconfig{'ltisec'}{'private'}) eq 'HASH') {
 2970:             if (ref($domconfig{'ltisec'}{'private'}{'keys'}) eq 'ARRAY') {
 2971:                 $domdefaults{'ltiprivhosts'} = $domconfig{'ltisec'}{'private'}{'keys'};
 2972:             }
 2973:         }
 2974:     }
 2975:     if (ref($domconfig{'toolsec'}) eq 'HASH') {
 2976:         if (ref($domconfig{'toolsec'}{'encrypt'}) eq 'HASH') {
 2977:             $domdefaults{'toolenc_crs'} = $domconfig{'toolsec'}{'encrypt'}{'crs'};
 2978:             $domdefaults{'toolenc_dom'} = $domconfig{'toolsec'}{'encrypt'}{'dom'};
 2979:         }
 2980:         if (ref($domconfig{'toolsec'}{'private'}) eq 'HASH') {
 2981:             if (ref($domconfig{'toolsec'}{'private'}{'keys'}) eq 'ARRAY') {
 2982:                 $domdefaults{'toolprivhosts'} = $domconfig{'toolsec'}{'private'}{'keys'};
 2983:             }
 2984:         }
 2985:     }
 2986:     if (ref($domconfig{'privacy'}) eq 'HASH') {
 2987:         if (ref($domconfig{'privacy'}{'approval'}) eq 'HASH') {
 2988:             foreach my $domtype ('instdom','extdom') {
 2989:                 if (ref($domconfig{'privacy'}{'approval'}{$domtype}) eq 'HASH') {
 2990:                     foreach my $roletype ('domain','author','course','community') {
 2991:                         if ($domconfig{'privacy'}{'approval'}{$domtype}{$roletype} eq 'user') {
 2992:                             $domdefaults{'userapprovals'} = 1;
 2993:                             last;
 2994:                         }
 2995:                     }
 2996:                 }
 2997:                 last if ($domdefaults{'userapprovals'});
 2998:             }
 2999:         }
 3000:     }
 3001:     &do_cache_new('domdefaults',$domain,\%domdefaults,$cachetime);
 3002:     return %domdefaults;
 3003: }
 3004: 
 3005: sub get_dom_cats {
 3006:     my ($dom) = @_;
 3007:     return unless (&domain($dom));
 3008:     my ($cats,$cached)=&is_cached_new('cats',$dom);
 3009:     unless (defined($cached)) {
 3010:         my %domconfig = &get_dom('configuration',['coursecategories'],$dom);
 3011:         if (ref($domconfig{'coursecategories'}) eq 'HASH') {
 3012:             if (ref($domconfig{'coursecategories'}{'cats'}) eq 'HASH') {
 3013:                 %{$cats} = %{$domconfig{'coursecategories'}{'cats'}};
 3014:             } else {
 3015:                 $cats = {};
 3016:             }
 3017:         } else {
 3018:             $cats = {};
 3019:         }
 3020:         &do_cache_new('cats',$dom,$cats,3600);
 3021:     }
 3022:     return $cats;
 3023: }
 3024: 
 3025: sub get_dom_instcats {
 3026:     my ($dom) = @_;
 3027:     return unless (&domain($dom));
 3028:     my ($instcats,$cached)=&is_cached_new('instcats',$dom);
 3029:     unless (defined($cached)) {
 3030:         my (%coursecodes,%codes,@codetitles,%cat_titles,%cat_order);
 3031:         my $totcodes = &retrieve_instcodes(\%coursecodes,$dom);
 3032:         if ($totcodes > 0) {
 3033:             my $caller = 'global';
 3034:             if (&auto_instcode_format($caller,$dom,\%coursecodes,\%codes,
 3035:                                       \@codetitles,\%cat_titles,\%cat_order) eq 'ok') {
 3036:                 $instcats = {
 3037:                                 totcodes => $totcodes,
 3038:                                 codes => \%codes,
 3039:                                 codetitles => \@codetitles,
 3040:                                 cat_titles => \%cat_titles,
 3041:                                 cat_order => \%cat_order,
 3042:                             };
 3043:                 &do_cache_new('instcats',$dom,$instcats,3600);
 3044:             }
 3045:         }
 3046:     }
 3047:     return $instcats;
 3048: }
 3049: 
 3050: sub retrieve_instcodes {
 3051:     my ($coursecodes,$dom) = @_;
 3052:     my $totcodes;
 3053:     my %courses = &courseiddump($dom,'.',1,'.','.','.',undef,undef,'Course');
 3054:     foreach my $course (keys(%courses)) {
 3055:         if (ref($courses{$course}) eq 'HASH') {
 3056:             if ($courses{$course}{'inst_code'} ne '') {
 3057:                 $$coursecodes{$course} = $courses{$course}{'inst_code'};
 3058:                 $totcodes ++;
 3059:             }
 3060:         }
 3061:     }
 3062:     return $totcodes;
 3063: }
 3064: 
 3065: sub course_portal_url {
 3066:     my ($cnum,$cdom,$r) = @_;
 3067:     my $chome = &homeserver($cnum,$cdom);
 3068:     my $hostname = &hostname($chome);
 3069:     my $protocol = $protocol{$chome};
 3070:     $protocol = 'http' if ($protocol ne 'https');
 3071:     my %domdefaults = &get_domain_defaults($cdom);
 3072:     my $firsturl;
 3073:     if ($domdefaults{'portal_def'}) {
 3074:         $firsturl = $domdefaults{'portal_def'};
 3075:     } else {
 3076:         my $alias = &use_proxy_alias($r,$chome);
 3077:         $hostname = $alias if ($alias ne '');
 3078:         $firsturl = $protocol.'://'.$hostname;
 3079:     }
 3080:     return $firsturl;
 3081: }
 3082: 
 3083: sub url_prefix {
 3084:     my ($r,$dom,$home,$context) = @_;
 3085:     my $prefix;
 3086:     my %domdefs = &get_domain_defaults($dom);
 3087:     if ($domdefs{'portal_def'} && $domdefs{'portal_def_'.$context}) {
 3088:         if ($domdefs{'portal_def'} =~ m{^(https?://[^/]+)}) {
 3089:             $prefix = $1;
 3090:         }
 3091:     }
 3092:     if ($prefix eq '') {
 3093:         my $hostname = &hostname($home);
 3094:         my $protocol = $protocol{$home};
 3095:         $protocol = 'http' if ($protocol{$home} ne 'https');
 3096:         my $alias = &use_proxy_alias($r,$home);
 3097:         $hostname = $alias if ($alias ne '');
 3098:         $prefix = $protocol.'://'.$hostname;
 3099:     }
 3100:     return $prefix;
 3101: }
 3102: 
 3103: # --------------------------------------------- Get domain config for passwords
 3104: 
 3105: sub get_passwdconf {
 3106:     my ($dom) = @_;
 3107:     my (%passwdconf,$gotconf,$lookup);
 3108:     my ($result,$cached)=&is_cached_new('passwdconf',$dom);
 3109:     if (defined($cached)) {
 3110:         if (ref($result) eq 'HASH') {
 3111:             %passwdconf = %{$result};
 3112:             $gotconf = 1;
 3113:         }
 3114:     }
 3115:     unless ($gotconf) {
 3116:         my %domconfig = &get_dom('configuration',['passwords'],$dom);
 3117:         if (ref($domconfig{'passwords'}) eq 'HASH') {
 3118:             %passwdconf = %{$domconfig{'passwords'}};
 3119:         }
 3120:         my $cachetime = 24*60*60;
 3121:         &do_cache_new('passwdconf',$dom,\%passwdconf,$cachetime);
 3122:     }
 3123:     return %passwdconf;
 3124: }
 3125: 
 3126: # --------------------------------------------------- Assign a key to a student
 3127: 
 3128: sub assign_access_key {
 3129: #
 3130: # a valid key looks like uname:udom#comments
 3131: # comments are being appended
 3132: #
 3133:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
 3134:     $kdom=
 3135:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
 3136:     $knum=
 3137:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
 3138:     $cdom=
 3139:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 3140:     $cnum=
 3141:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 3142:     $udom=$env{'user.name'} unless (defined($udom));
 3143:     $uname=$env{'user.domain'} unless (defined($uname));
 3144:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
 3145:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
 3146:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
 3147:                                                   # assigned to this person
 3148:                                                   # - this should not happen,
 3149:                                                   # unless something went wrong
 3150:                                                   # the first time around
 3151: # ready to assign
 3152:         $logentry=$1.'; '.$logentry;
 3153:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
 3154:                                                  $kdom,$knum) eq 'ok') {
 3155: # key now belongs to user
 3156: 	    my $envkey='key.'.$cdom.'_'.$cnum;
 3157:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
 3158:                 &appenv({'environment.'.$envkey => $ckey});
 3159:                 return 'ok';
 3160:             } else {
 3161:                 return 
 3162:   'error: Count not permanently assign key, will need to be re-entered later.';
 3163: 	    }
 3164:         } else {
 3165:             return 'error: Could not assign key, try again later.';
 3166:         }
 3167:     } elsif (!$existing{$ckey}) {
 3168: # the key does not exist
 3169: 	return 'error: The key does not exist';
 3170:     } else {
 3171: # the key is somebody else's
 3172: 	return 'error: The key is already in use';
 3173:     }
 3174: }
 3175: 
 3176: # ------------------------------------------ put an additional comment on a key
 3177: 
 3178: sub comment_access_key {
 3179: #
 3180: # a valid key looks like uname:udom#comments
 3181: # comments are being appended
 3182: #
 3183:     my ($ckey,$cdom,$cnum,$logentry)=@_;
 3184:     $cdom=
 3185:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 3186:     $cnum=
 3187:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 3188:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
 3189:     if ($existing{$ckey}) {
 3190:         $existing{$ckey}.='; '.$logentry;
 3191: # ready to assign
 3192:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
 3193:                                                  $cdom,$cnum) eq 'ok') {
 3194: 	    return 'ok';
 3195:         } else {
 3196: 	    return 'error: Count not store comment.';
 3197:         }
 3198:     } else {
 3199: # the key does not exist
 3200: 	return 'error: The key does not exist';
 3201:     }
 3202: }
 3203: 
 3204: # ------------------------------------------------------ Generate a set of keys
 3205: 
 3206: sub generate_access_keys {
 3207:     my ($number,$cdom,$cnum,$logentry)=@_;
 3208:     $cdom=
 3209:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 3210:     $cnum=
 3211:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 3212:     unless (&allowed('mky',$cdom)) { return 0; }
 3213:     unless (($cdom) && ($cnum)) { return 0; }
 3214:     if ($number>10000) { return 0; }
 3215:     sleep(2); # make sure don't get same seed twice
 3216:     srand(time()^($$+($$<<15))); # from "Programming Perl"
 3217:     my $total=0;
 3218:     for (my $i=1;$i<=$number;$i++) {
 3219:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
 3220:                   sprintf("%lx",int(100000*rand)).'-'.
 3221:                   sprintf("%lx",int(100000*rand));
 3222:        $newkey=~s/1/g/g; # folks mix up 1 and l
 3223:        $newkey=~s/0/h/g; # and also 0 and O
 3224:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
 3225:        if ($existing{$newkey}) {
 3226:            $i--;
 3227:        } else {
 3228: 	  if (&put('accesskeys',
 3229:               { $newkey => '# generated '.localtime().
 3230:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
 3231:                            '; '.$logentry },
 3232: 		   $cdom,$cnum) eq 'ok') {
 3233:               $total++;
 3234: 	  }
 3235:        }
 3236:     }
 3237:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
 3238:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
 3239:     return $total;
 3240: }
 3241: 
 3242: # ------------------------------------------------------- Validate an accesskey
 3243: 
 3244: sub validate_access_key {
 3245:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
 3246:     $cdom=
 3247:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 3248:     $cnum=
 3249:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 3250:     $udom=$env{'user.domain'} unless (defined($udom));
 3251:     $uname=$env{'user.name'} unless (defined($uname));
 3252:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
 3253:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
 3254: }
 3255: 
 3256: # ------------------------------------- Find the section of student in a course
 3257: sub devalidate_getsection_cache {
 3258:     my ($udom,$unam,$courseid)=@_;
 3259:     my $hashid="$udom:$unam:$courseid";
 3260:     &devalidate_cache_new('getsection',$hashid);
 3261: }
 3262: 
 3263: sub courseid_to_courseurl {
 3264:     my ($courseid) = @_;
 3265:     #already url style courseid
 3266:     return $courseid if ($courseid =~ m{^/});
 3267: 
 3268:     if (exists($env{'course.'.$courseid.'.num'})) {
 3269: 	my $cnum = $env{'course.'.$courseid.'.num'};
 3270: 	my $cdom = $env{'course.'.$courseid.'.domain'};
 3271: 	return "/$cdom/$cnum";
 3272:     }
 3273: 
 3274:     my %courseinfo=&coursedescription($courseid);
 3275:     if (exists($courseinfo{'num'})) {
 3276: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
 3277:     }
 3278: 
 3279:     return undef;
 3280: }
 3281: 
 3282: sub getsection {
 3283:     my ($udom,$unam,$courseid)=@_;
 3284:     my $cachetime=1800;
 3285: 
 3286:     my $hashid="$udom:$unam:$courseid";
 3287:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
 3288:     if (defined($cached)) { return $result; }
 3289: 
 3290:     my %Pending; 
 3291:     my %Expired;
 3292:     #
 3293:     # Each role can either have not started yet (pending), be active, 
 3294:     #    or have expired.
 3295:     #
 3296:     # If there is an active role, we are done.
 3297:     #
 3298:     # If there is more than one role which has not started yet, 
 3299:     #     choose the one which will start sooner
 3300:     # If there is one role which has not started yet, return it.
 3301:     #
 3302:     # If there is more than one expired role, choose the one which ended last.
 3303:     # If there is a role which has expired, return it.
 3304:     #
 3305:     $courseid = &courseid_to_courseurl($courseid);
 3306:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
 3307:     foreach my $key (keys(%roleshash)) {
 3308:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
 3309:         my $section=$1;
 3310:         if ($key eq $courseid.'_st') { $section=''; }
 3311:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
 3312:         my $now=time;
 3313:         if (defined($end) && $end && ($now > $end)) {
 3314:             $Expired{$end}=$section;
 3315:             next;
 3316:         }
 3317:         if (defined($start) && $start && ($now < $start)) {
 3318:             $Pending{$start}=$section;
 3319:             next;
 3320:         }
 3321:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
 3322:     }
 3323:     #
 3324:     # Presumedly there will be few matching roles from the above
 3325:     # loop and the sorting time will be negligible.
 3326:     if (scalar(keys(%Pending))) {
 3327:         my ($time) = sort {$a <=> $b} keys(%Pending);
 3328:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
 3329:     } 
 3330:     if (scalar(keys(%Expired))) {
 3331:         my @sorted = sort {$a <=> $b} keys(%Expired);
 3332:         my $time = pop(@sorted);
 3333:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
 3334:     }
 3335:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
 3336: }
 3337: 
 3338: sub save_cache {
 3339:     &purge_remembered();
 3340:     #&Apache::loncommon::validate_page();
 3341:     undef(%env);
 3342:     undef($env_loaded);
 3343: }
 3344: 
 3345: my $to_remember=-1;
 3346: my %remembered;
 3347: my %accessed;
 3348: my $kicks=0;
 3349: my $hits=0;
 3350: sub make_key {
 3351:     my ($name,$id) = @_;
 3352:     if (length($id) > 65 
 3353: 	&& length(&escape($id)) > 200) {
 3354: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
 3355:     }
 3356:     return &escape($name.':'.$id);
 3357: }
 3358: 
 3359: sub devalidate_cache_new {
 3360:     my ($name,$id,$debug) = @_;
 3361:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
 3362:     my $remembered_id=$name.':'.$id;
 3363:     $id=&make_key($name,$id);
 3364:     $memcache->delete($id);
 3365:     delete($remembered{$remembered_id});
 3366:     delete($accessed{$remembered_id});
 3367: }
 3368: 
 3369: sub is_cached_new {
 3370:     my ($name,$id,$debug) = @_;
 3371:     my $remembered_id=$name.':'.$id; # this is to avoid make_key (which is slow) whenever possible
 3372:     if (exists($remembered{$remembered_id})) {
 3373: 	if ($debug) { &Apache::lonnet::logthis("Early return $remembered_id of $remembered{$remembered_id} "); }
 3374: 	$accessed{$remembered_id}=[&gettimeofday()];
 3375: 	$hits++;
 3376: 	return ($remembered{$remembered_id},1);
 3377:     }
 3378:     $id=&make_key($name,$id);
 3379:     my $value = $memcache->get($id);
 3380:     if (!(defined($value))) {
 3381: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
 3382: 	return (undef,undef);
 3383:     }
 3384:     if ($value eq '__undef__') {
 3385: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
 3386: 	$value=undef;
 3387:     }
 3388:     &make_room($remembered_id,$value,$debug);
 3389:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
 3390:     return ($value,1);
 3391: }
 3392: 
 3393: sub do_cache_new {
 3394:     my ($name,$id,$value,$time,$debug) = @_;
 3395:     my $remembered_id=$name.':'.$id;
 3396:     $id=&make_key($name,$id);
 3397:     my $setvalue=$value;
 3398:     if (!defined($setvalue)) {
 3399: 	$setvalue='__undef__';
 3400:     }
 3401:     if (!defined($time) ) {
 3402: 	$time=600;
 3403:     }
 3404:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
 3405:     my $result = $memcache->set($id,$setvalue,$time);
 3406:     if (! $result) {
 3407: 	&logthis("caching of id -> $id  failed");
 3408: 	$memcache->disconnect_all();
 3409:     }
 3410:     # need to make a copy of $value
 3411:     &make_room($remembered_id,$value,$debug);
 3412:     return $value;
 3413: }
 3414: 
 3415: sub make_room {
 3416:     my ($remembered_id,$value,$debug)=@_;
 3417: 
 3418:     $remembered{$remembered_id}= (ref($value)) ? &Storable::dclone($value)
 3419:                                     : $value;
 3420:     if ($to_remember<0) { return; }
 3421:     $accessed{$remembered_id}=[&gettimeofday()];
 3422:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
 3423:     my $to_kick;
 3424:     my $max_time=0;
 3425:     foreach my $other (keys(%accessed)) {
 3426: 	if (&tv_interval($accessed{$other}) > $max_time) {
 3427: 	    $to_kick=$other;
 3428: 	    $max_time=&tv_interval($accessed{$other});
 3429: 	}
 3430:     }
 3431:     delete($remembered{$to_kick});
 3432:     delete($accessed{$to_kick});
 3433:     $kicks++;
 3434:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
 3435:     return;
 3436: }
 3437: 
 3438: sub purge_remembered {
 3439:     #&logthis("Tossing ".scalar(keys(%remembered)));
 3440:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
 3441:     undef(%remembered);
 3442:     undef(%accessed);
 3443: }
 3444: # ------------------------------------- Read an entry from a user's environment
 3445: 
 3446: sub userenvironment {
 3447:     my ($udom,$unam,@what)=@_;
 3448:     my $items;
 3449:     foreach my $item (@what) {
 3450:         $items.=&escape($item).'&';
 3451:     }
 3452:     $items=~s/\&$//;
 3453:     my %returnhash=();
 3454:     my $uhome = &homeserver($unam,$udom);
 3455:     unless ($uhome eq 'no_host') {
 3456:         my @answer=split(/\&/, 
 3457:             &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
 3458:         if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
 3459:             return %returnhash;
 3460:         }
 3461:         my $i;
 3462:         for ($i=0;$i<=$#what;$i++) {
 3463: 	    $returnhash{$what[$i]}=&unescape($answer[$i]);
 3464:         }
 3465:     }
 3466:     return %returnhash;
 3467: }
 3468: 
 3469: # ---------------------------------------------------------- Get a studentphoto
 3470: sub studentphoto {
 3471:     my ($udom,$unam,$ext) = @_;
 3472:     my $home=&homeserver($unam,$udom);
 3473:     if (defined($env{'request.course.id'})) {
 3474:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
 3475:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
 3476:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
 3477:             } else {
 3478:                 my ($result,$perm_reqd)=
 3479: 		    &auto_photo_permission($unam,$udom);
 3480:                 if ($result eq 'ok') {
 3481:                     if (!($perm_reqd eq 'yes')) {
 3482:                         return(&retrievestudentphoto($udom,$unam,$ext));
 3483:                     }
 3484:                 }
 3485:             }
 3486:         }
 3487:     } else {
 3488:         my ($result,$perm_reqd) = 
 3489: 	    &auto_photo_permission($unam,$udom);
 3490:         if ($result eq 'ok') {
 3491:             if (!($perm_reqd eq 'yes')) {
 3492:                 return(&retrievestudentphoto($udom,$unam,$ext));
 3493:             }
 3494:         }
 3495:     }
 3496:     return '/adm/lonKaputt/lonlogo_broken.gif';
 3497: }
 3498: 
 3499: sub retrievestudentphoto {
 3500:     my ($udom,$unam,$ext,$type) = @_;
 3501:     my $home=&homeserver($unam,$udom);
 3502:     my $ret=&reply("studentphoto:$udom:$unam:$ext:$type",$home);
 3503:     if ($ret eq 'ok') {
 3504:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
 3505:         if ($type eq 'thumbnail') {
 3506:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
 3507:         }
 3508:         my $tokenurl=&tokenwrapper($url);
 3509:         return $tokenurl;
 3510:     } else {
 3511:         if ($type eq 'thumbnail') {
 3512:             return '/adm/lonKaputt/genericstudent_tn.gif';
 3513:         } else { 
 3514:             return '/adm/lonKaputt/lonlogo_broken.gif';
 3515:         }
 3516:     }
 3517: }
 3518: 
 3519: # -------------------------------------------------------------------- New chat
 3520: 
 3521: sub chatsend {
 3522:     my ($newentry,$anon,$group)=@_;
 3523:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
 3524:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 3525:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
 3526:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
 3527: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
 3528: 		   &escape($newentry)).':'.$group,$chome);
 3529: }
 3530: 
 3531: # ------------------------------------------ Find current version of a resource
 3532: 
 3533: sub getversion {
 3534:     my $fname=&clutter(shift);
 3535:     unless ($fname=~m{^(/adm/wrapper|)/res/}) { return -1; }
 3536:     return &currentversion(&filelocation('',$fname));
 3537: }
 3538: 
 3539: sub currentversion {
 3540:     my $fname=shift;
 3541:     my $author=$fname;
 3542:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 3543:     my ($udom,$uname)=split(/\//,$author);
 3544:     my $home=&homeserver($uname,$udom);
 3545:     if ($home eq 'no_host') { 
 3546:         return -1; 
 3547:     }
 3548:     my $answer=&reply("currentversion:$fname",$home);
 3549:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
 3550: 	return -1;
 3551:     }
 3552:     return $answer;
 3553: }
 3554: 
 3555: #
 3556: # Return special version number of resource if set by override, empty otherwise
 3557: #
 3558: sub usedversion {
 3559:     my $fname=shift;
 3560:     unless ($fname) { $fname=$env{'request.uri'}; }
 3561:     my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
 3562:     if ($urlversion) { return $urlversion; }
 3563:     return '';
 3564: }
 3565: 
 3566: # ----------------------------- Subscribe to a resource, return URL if possible
 3567: 
 3568: sub subscribe {
 3569:     my $fname=shift;
 3570:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
 3571:     $fname=~s/[\n\r]//g;
 3572:     my $author=$fname;
 3573:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 3574:     my ($udom,$uname)=split(/\//,$author);
 3575:     my $home=homeserver($uname,$udom);
 3576:     if ($home eq 'no_host') {
 3577:         return 'not_found';
 3578:     }
 3579:     my $answer=reply("sub:$fname",$home);
 3580:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
 3581: 	$answer.=' by '.$home;
 3582:     }
 3583:     return $answer;
 3584: }
 3585:     
 3586: # -------------------------------------------------------------- Replicate file
 3587: 
 3588: sub repcopy {
 3589:     my $filename=shift;
 3590:     $filename=~s/\/+/\//g;
 3591:     my $londocroot = $perlvar{'lonDocRoot'};
 3592:     if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
 3593:     if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
 3594:     if ($filename=~m{^\Q$londocroot/userfiles/\E} or
 3595: 	$filename=~m{^/*(uploaded|editupload)/}) {
 3596: 	return &repcopy_userfile($filename);
 3597:     }
 3598:     $filename=~s/[\n\r]//g;
 3599:     my $transname="$filename.in.transfer";
 3600: # FIXME: this should flock
 3601:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
 3602:     my $remoteurl=subscribe($filename);
 3603:     if ($remoteurl =~ /^con_lost by/) {
 3604: 	   &logthis("Subscribe returned $remoteurl: $filename");
 3605:            return 'unavailable';
 3606:     } elsif ($remoteurl eq 'not_found') {
 3607: 	   #&logthis("Subscribe returned not_found: $filename");
 3608: 	   return 'not_found';
 3609:     } elsif ($remoteurl =~ /^rejected by/) {
 3610: 	   &logthis("Subscribe returned $remoteurl: $filename");
 3611:            return 'forbidden';
 3612:     } elsif ($remoteurl eq 'directory') {
 3613:            return 'ok';
 3614:     } else {
 3615:         my $author=$filename;
 3616:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 3617:         my ($udom,$uname)=split(/\//,$author);
 3618:         my $home=homeserver($uname,$udom);
 3619:         unless ($home eq $perlvar{'lonHostID'}) {
 3620:            my @parts=split(/\//,$filename);
 3621:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
 3622:            if ($path ne "$londocroot/res") {
 3623:                &logthis("Malconfiguration for replication: $filename");
 3624: 	       return 'bad_request';
 3625:            }
 3626:            my $count;
 3627:            for ($count=5;$count<$#parts;$count++) {
 3628:                $path.="/$parts[$count]";
 3629:                if ((-e $path)!=1) {
 3630: 		   mkdir($path,0777);
 3631:                }
 3632:            }
 3633:            my $request=new HTTP::Request('GET',"$remoteurl");
 3634:            my $response;
 3635:            if ($remoteurl =~ m{/raw/}) {
 3636:                $response=&LONCAPA::LWPReq::makerequest($home,$request,$transname,\%perlvar,'',0,1);
 3637:            } else {
 3638:                $response=&LONCAPA::LWPReq::makerequest($home,$request,$transname,\%perlvar,'',1);
 3639:            }
 3640:            if ($response->is_error()) {
 3641: 	       unlink($transname);
 3642:                my $message=$response->status_line;
 3643:                &logthis("<font color=\"blue\">WARNING:"
 3644:                        ." LWP get: $message: $filename</font>");
 3645:                return 'unavailable';
 3646:            } else {
 3647: 	       if ($remoteurl!~/\.meta$/) {
 3648:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
 3649:                   my $mresponse;
 3650:                   if ($remoteurl =~ m{/raw/}) {
 3651:                       $mresponse = &LONCAPA::LWPReq::makerequest($home,$mrequest,$filename.'.meta',\%perlvar,'',0,1);
 3652:                   } else {
 3653:                       $mresponse = &LONCAPA::LWPReq::makerequest($home,$mrequest,$filename.'.meta',\%perlvar,'',1);
 3654:                   }
 3655:                   if ($mresponse->is_error()) {
 3656: 		      unlink($filename.'.meta');
 3657:                       &logthis(
 3658:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
 3659:                   }
 3660: 	       }
 3661:                rename($transname,$filename);
 3662:                return 'ok';
 3663:            }
 3664:        }
 3665:     }
 3666: }
 3667: 
 3668: # ------------------------------------------------- Unsubscribe from a resource
 3669: 
 3670: sub unsubscribe {
 3671:     my ($fname) = @_;
 3672:     my $answer;
 3673:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return $answer; }
 3674:     $fname=~s/[\n\r]//g;
 3675:     my $author=$fname;
 3676:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 3677:     my ($udom,$uname)=split(/\//,$author);
 3678:     my $home=homeserver($uname,$udom);
 3679:     if ($home eq 'no_host') {
 3680:         $answer = 'no_host';
 3681:     } elsif (grep { $_ eq $home } &current_machine_ids()) {
 3682:         $answer = 'home';
 3683:     } else {
 3684:         my $defdom = $perlvar{'lonDefDomain'};
 3685:         if (&will_trust('content',$defdom,$udom)) {
 3686:             $answer = reply("unsub:$fname",$home);
 3687:         } else {
 3688:             $answer = 'untrusted';
 3689:         }
 3690:     }
 3691:     return $answer;
 3692: }
 3693: 
 3694: # ------------------------------------------------ Get server side include body
 3695: sub ssi_body {
 3696:     my ($filelink,%form)=@_;
 3697:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
 3698:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
 3699:     }
 3700:     my $output='';
 3701:     my $response;
 3702:     if ($filelink=~/^https?\:/) {
 3703:        ($output,$response)=&externalssi($filelink);
 3704:     } else {
 3705:        $filelink .= $filelink=~/\?/ ? '&' : '?';
 3706:        $filelink .= 'inhibitmenu=yes';
 3707:        ($output,$response)=&ssi($filelink,%form);
 3708:     }
 3709:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
 3710:     $output=~s/^.*?\<body[^\>]*\>//si;
 3711:     $output=~s/\<\/body\s*\>.*?$//si;
 3712:     if (wantarray) {
 3713:         return ($output, $response);
 3714:     } else {
 3715:         return $output;
 3716:     }
 3717: }
 3718: 
 3719: # --------------------------------------------------------- Server Side Include
 3720: 
 3721: sub absolute_url {
 3722:     my ($host_name,$unalias,$keep_proto) = @_;
 3723:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
 3724:     if ($host_name eq '') {
 3725: 	$host_name = $ENV{'SERVER_NAME'};
 3726:     }
 3727:     if ($unalias) {
 3728:         my $alias = &get_proxy_alias();
 3729:         if ($alias eq $host_name) {
 3730:             my $lonhost = $perlvar{'lonHostID'};
 3731:             my $hostname = &hostname($lonhost);
 3732:             my $lcproto; 
 3733:             if (($keep_proto) || ($hostname eq '')) {
 3734:                 $lcproto = $protocol;
 3735:             } else {
 3736:                 $lcproto = $protocol{$lonhost};
 3737:                 $lcproto = 'http' if ($lcproto ne 'https');
 3738:                 $lcproto .= '://';
 3739:             }
 3740:             unless ($hostname eq '') {
 3741:                 return $lcproto.$hostname;
 3742:             }
 3743:         }
 3744:     }
 3745:     return $protocol.$host_name;
 3746: }
 3747: 
 3748: #
 3749: #   Server side include.
 3750: # Parameters:
 3751: #  fn     Possibly encrypted resource name/id.
 3752: #  form   Hash that describes how the rendering should be done
 3753: #         and other things.
 3754: # Returns:
 3755: #   Scalar context: The content of the response.
 3756: #   Array context:  2 element list of the content and the full response object.
 3757: #     
 3758: sub ssi {
 3759: 
 3760:     my ($fn,%form)=@_;
 3761:     my ($host,$request,$response);
 3762:     $host = &absolute_url('',1);
 3763: 
 3764:     $form{'no_update_last_known'}=1;
 3765:     &Apache::lonenc::check_encrypt(\$fn);
 3766:     if (%form) {
 3767:       $request=new HTTP::Request('POST',$host.$fn);
 3768:       $request->content(join('&',map { 
 3769:             my $name = escape($_);
 3770:             "$name=" . ( ref($form{$_}) eq 'ARRAY' 
 3771:             ? join("&$name=", map {escape($_) } @{$form{$_}}) 
 3772:             : &escape($form{$_}) );    
 3773:         } keys(%form)));
 3774:     } else {
 3775:       $request=new HTTP::Request('GET',$host.$fn);
 3776:     }
 3777: 
 3778:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
 3779:     my $lonhost = $perlvar{'lonHostID'};
 3780:     my $islocal;
 3781:     if (($env{'request.course.id'}) &&
 3782:         ($form{'grade_courseid'} eq $env{'request.course.id'}) &&
 3783:         ($form{'grade_username'} ne '') && ($form{'grade_domain'} ne '') &&
 3784:         ($form{'grade_symb'} ne '') &&
 3785:         (&allowed('mgr',$env{'request.course.id'}.
 3786:                         ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:'')))) {
 3787:         $islocal = 1;
 3788:     }
 3789:     $response= &LONCAPA::LWPReq::makerequest($lonhost,$request,'',\%perlvar,
 3790:                                              '','','',$islocal);
 3791: 
 3792:     if (wantarray) {
 3793: 	return ($response->content, $response);
 3794:     } else {
 3795: 	return $response->content;
 3796:     }
 3797: }
 3798: 
 3799: sub externalssi {
 3800:     my ($url)=@_;
 3801:     my $request=new HTTP::Request('GET',$url);
 3802:     my $response = &LONCAPA::LWPReq::makerequest('',$request,'',\%perlvar);
 3803:     if (wantarray) {
 3804:         return ($response->content, $response);
 3805:     } else {
 3806:         return $response->content;
 3807:     }
 3808: }
 3809: 
 3810: 
 3811: # If the local copy of a replicated resource is outdated, trigger a  
 3812: # connection from the homeserver to flush the delayed queue. If no update 
 3813: # happens, remove local copies of outdated resource (and corresponding
 3814: # metadata file).
 3815: 
 3816: sub remove_stale_resfile {
 3817:     my ($url) = @_;
 3818:     my $removed;
 3819:     if ($url=~m{^/res/($match_domain)/($match_username)/}) {
 3820:         my $audom = $1;
 3821:         my $auname = $2;
 3822:         unless (($url =~ /\.\d+\.\w+$/) || ($url =~ m{^/res/lib/templates/})) {
 3823:             my $homeserver = &homeserver($auname,$audom);
 3824:             unless (($homeserver eq 'no_host') ||
 3825:                     (grep { $_ eq $homeserver } &current_machine_ids())) {
 3826:                 my $fname = &filelocation('',$url);
 3827:                 if (-e $fname) {
 3828:                     my $hostname = &hostname($homeserver);
 3829:                     if ($hostname) {
 3830:                         my $protocol = $protocol{$homeserver};
 3831:                         $protocol = 'http' if ($protocol ne 'https');
 3832:                         my $uri = &declutter($url);
 3833:                         my $request=new HTTP::Request('HEAD',$protocol.'://'.$hostname.'/raw/'.$uri);
 3834:                         my $response = &LONCAPA::LWPReq::makerequest($homeserver,$request,'',\%perlvar,5,0,1);
 3835:                         if ($response->is_success()) {
 3836:                             my $remmodtime = &HTTP::Date::str2time( $response->header('Last-modified') );
 3837:                             my $locmodtime = (stat($fname))[9];
 3838:                             if ($locmodtime < $remmodtime) {
 3839:                                 my $stale;
 3840:                                 my $answer = &reply('pong',$homeserver);
 3841:                                 if ($answer eq $homeserver.':'.$perlvar{'lonHostID'}) {
 3842:                                     sleep(0.2);
 3843:                                     $locmodtime = (stat($fname))[9];
 3844:                                     if ($locmodtime < $remmodtime) {
 3845:                                         my $posstransfer = $fname.'.in.transfer';
 3846:                                         if ((-e $posstransfer) && ($remmodtime < (stat($posstransfer))[9])) {
 3847:                                             $removed = 1;
 3848:                                         } else {
 3849:                                             $stale = 1;
 3850:                                         }
 3851:                                     } else {
 3852:                                         $removed = 1;
 3853:                                     }
 3854:                                 } else {
 3855:                                     $stale = 1;
 3856:                                 }
 3857:                                 if ($stale) {
 3858:                                     if (unlink($fname)) {
 3859:                                         if ($uri!~/\.meta$/) {
 3860:                                             if (-e $fname.'.meta') {
 3861:                                                 unlink($fname.'.meta');
 3862:                                             }
 3863:                                         }
 3864:                                         my $unsubresult = &unsubscribe($fname);
 3865:                                         unless ($unsubresult eq 'ok') {
 3866:                                             &logthis("no unsub of $fname from $homeserver, reason: $unsubresult");
 3867:                                         }
 3868:                                         $removed = 1;
 3869:                                     }
 3870:                                 }
 3871:                             }
 3872:                         }
 3873:                     }
 3874:                 }
 3875:             }
 3876:         }
 3877:     }
 3878:     return $removed;
 3879: }
 3880: 
 3881: # -------------------------------- Allow a /uploaded/ URI to be vouched for
 3882: 
 3883: sub allowuploaded {
 3884:     my ($srcurl,$url)=@_;
 3885:     $url=&clutter(&declutter($url));
 3886:     my $dir=$url;
 3887:     $dir=~s/\/[^\/]+$//;
 3888:     my %httpref=();
 3889:     my $httpurl=&hreflocation('',$url);
 3890:     $httpref{'httpref.'.$httpurl}=$srcurl;
 3891:     &Apache::lonnet::appenv(\%httpref);
 3892: }
 3893: 
 3894: #
 3895: # Determine if the current user should be able to edit a particular resource,
 3896: # when viewing in course context.
 3897: # (a) When viewing resource used to determine if "Edit" item is included in 
 3898: #     Functions.
 3899: # (b) When displaying folder contents in course editor, used to determine if
 3900: #     "Edit" link will be displayed alongside resource.
 3901: #
 3902: #  input: six args -- filename (decluttered), course number, course domain,
 3903: #                   url, symb (if registered) and group (if this is a group
 3904: #                   item -- e.g., bulletin board, group page etc.).
 3905: #  output: array of five scalars -- 
 3906: #          $cfile -- url for file editing if editable on current server
 3907: #          $home -- homeserver of resource (i.e., for author if published,
 3908: #                                           or course if uploaded.).
 3909: #          $switchserver --  1 if server switch will be needed.
 3910: #          $forceedit -- 1 if icon/link should be to go to edit mode 
 3911: #          $forceview -- 1 if icon/link should be to go to view mode
 3912: #
 3913: 
 3914: sub can_edit_resource {
 3915:     my ($file,$cnum,$cdom,$resurl,$symb,$group) = @_;
 3916:     my ($cfile,$home,$switchserver,$forceedit,$forceview,$uploaded,$incourse);
 3917: #
 3918: # For aboutme pages user can only edit his/her own.
 3919: #
 3920:     if ($resurl =~ m{^/?adm/($match_domain)/($match_username)/aboutme$}) {
 3921:         my ($sdom,$sname) = ($1,$2);
 3922:         if (($sdom eq $env{'user.domain'}) && ($sname eq $env{'user.name'})) {
 3923:             $home = $env{'user.home'};
 3924:             $cfile = $resurl;
 3925:             if ($env{'form.forceedit'}) {
 3926:                 $forceview = 1;
 3927:             } else {
 3928:                 $forceedit = 1;
 3929:             }
 3930:             return ($cfile,$home,$switchserver,$forceedit,$forceview);
 3931:         } else {
 3932:             return;
 3933:         }
 3934:     }
 3935: 
 3936: #
 3937: # For /adm/viewcoauthors can only edit if author or co-author who is manager.
 3938: #
 3939: 
 3940:     if (($resurl eq '/adm/viewcoauthors') && ($cnum ne '') && ($cdom ne '')) {
 3941:         if (((&allowed('cca',"$cdom/$cnum")) ||
 3942:              (&allowed('caa',"$cdom/$cnum"))) ||
 3943:              ((&allowed('vca',"$cdom/$cnum") ||
 3944:                &allowed('vaa',"$cdom/$cnum")) &&
 3945:               ($env{"environment.internal.manager./$cdom/$cnum"}))) {
 3946:             $home = $env{'user.home'};
 3947:             $cfile = $resurl;
 3948:             if ($env{'form.forceedit'}) {
 3949:                 $forceview = 1;
 3950:             } else {
 3951:                 $forceedit = 1;
 3952:             }
 3953:             return ($cfile,$home,$switchserver,$forceedit,$forceview);
 3954:         } else {
 3955:             return;
 3956:         }
 3957:     }
 3958: 
 3959:     if ($env{'request.course.id'}) {
 3960:         my $crsedit = &allowed('mdc',$env{'request.course.id'});
 3961:         if ($group ne '') {
 3962: # if this is a group homepage or group bulletin board, check group privs
 3963:             my $allowed = 0;
 3964:             if ($resurl =~ m{^/?adm/$cdom/$cnum/$group/smppg$}) {
 3965:                 if ((&allowed('mdg',$env{'request.course.id'}.
 3966:                               ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
 3967:                         (&allowed('mgh',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
 3968:                     $allowed = 1;
 3969:                 }
 3970:             } elsif ($resurl =~ m{^/?adm/$cdom/$cnum/\d+/bulletinboard$}) {
 3971:                 if ((&allowed('mdg',$env{'request.course.id'}.($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
 3972:                         (&allowed('cgb',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
 3973:                     $allowed = 1;
 3974:                 }
 3975:             }
 3976:             if ($allowed) {
 3977:                 $home=&homeserver($cnum,$cdom);
 3978:                 if ($env{'form.forceedit'}) {
 3979:                     $forceview = 1;
 3980:                 } else {
 3981:                     $forceedit = 1;
 3982:                 }
 3983:                 $cfile = $resurl;
 3984:             } else {
 3985:                 return;
 3986:             }
 3987:         } else {
 3988:             if ($resurl =~ m{^/?adm/viewclasslist$}) {
 3989:                 unless (&allowed('opa',$env{'request.course.id'})) {
 3990:                     return;
 3991:                 }
 3992:             } elsif (!$crsedit) {
 3993:                 if ($env{'request.role'} =~ m{^st\./$cdom/$cnum}) {
 3994: #
 3995: # No edit allowed where CC has switched to student role.
 3996: #
 3997:                     return;
 3998:                 } elsif (($resurl !~ m{^/res/$match_domain/$match_username/}) ||
 3999:                          ($resurl =~ m{^/res/lib/templates/})) {
 4000:                     return;
 4001:                 }
 4002:             }
 4003:         }
 4004:     }
 4005: 
 4006:     if ($file ne '') {
 4007:         if (($cnum =~ /$match_courseid/) && ($cdom =~ /$match_domain/)) {
 4008:             if (&is_course_upload($file,$cnum,$cdom)) {
 4009:                 $uploaded = 1;
 4010:                 $incourse = 1;
 4011:                 if ($file =~/\.(htm|html|css|js|txt)$/) {
 4012:                     $cfile = &hreflocation('',$file);
 4013:                     if ($env{'form.forceedit'}) {
 4014:                         $forceview = 1;
 4015:                     } else {
 4016:                         $forceedit = 1;
 4017:                     }
 4018:                 }
 4019:             } elsif ($resurl =~ m{^/public/$cdom/$cnum/syllabus}) {
 4020:                 $incourse = 1;
 4021:                 if ($env{'form.forceedit'}) {
 4022:                     $forceview = 1;
 4023:                 } else {
 4024:                     $forceedit = 1;
 4025:                 }
 4026:                 $cfile = $resurl;
 4027:             } elsif (($resurl ne '') && (&is_on_map($resurl))) {
 4028:                 if ($resurl =~ m{^/adm/$match_domain/$match_username/\d+/smppg|bulletinboard$}) {
 4029:                     $incourse = 1;
 4030:                     if ($env{'form.forceedit'}) {
 4031:                         $forceview = 1;
 4032:                     } else {
 4033:                         $forceedit = 1;
 4034:                     }
 4035:                     $cfile = $resurl;
 4036:                 } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem') {
 4037:                     $incourse = 1;
 4038:                     $cfile = $resurl.'/smpedit';
 4039:                 } elsif ($resurl =~ m{^/adm/wrapper/ext/}) {
 4040:                     $incourse = 1;
 4041:                     if ($env{'form.forceedit'}) {
 4042:                         $forceview = 1;
 4043:                     } else {
 4044:                         $forceedit = 1;
 4045:                     }
 4046:                     $cfile = $resurl;
 4047:                 } elsif (($resurl =~ m{^/ext/}) && ($symb ne '')) {
 4048:                     my ($map,$id,$res) = &decode_symb($symb);
 4049:                     if ($map =~ /\.page$/) {
 4050:                         $incourse = 1;
 4051:                         if ($env{'form.forceedit'}) {
 4052:                             $forceview = 1;
 4053:                             $cfile = $map;
 4054:                         } else {
 4055:                             $forceedit = 1;
 4056:                             $cfile =  '/adm/wrapper'.$resurl;
 4057:                         }
 4058:                     }
 4059:                 } elsif ($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/ext\.tool$}) {
 4060:                     $incourse = 1;
 4061:                     if ($env{'form.forceedit'}) {
 4062:                         $forceview = 1;
 4063:                     } else {
 4064:                         $forceedit = 1;
 4065:                     }
 4066:                     $cfile = $resurl;
 4067:                 } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
 4068:                     $incourse = 1;
 4069:                     if ($env{'form.forceedit'}) {
 4070:                         $forceview = 1;
 4071:                     } else {
 4072:                         $forceedit = 1;
 4073:                     }
 4074:                     $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
 4075:                 }
 4076:             } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem/smpedit') {
 4077:                 my $template = '/res/lib/templates/simpleproblem.problem';
 4078:                 if (&is_on_map($template)) { 
 4079:                     $incourse = 1;
 4080:                     $forceview = 1;
 4081:                     $cfile = $template;
 4082:                 }
 4083:             } elsif (($resurl =~ m{^/adm/wrapper/ext/}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
 4084:                 $incourse = 1;
 4085:                 if ($env{'form.forceedit'}) {
 4086:                     $forceview = 1;
 4087:                 } else {
 4088:                     $forceedit = 1;
 4089:                 }
 4090:                 $cfile = $resurl;
 4091:             } elsif (($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/ext\.tool$}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
 4092:                 $incourse = 1;
 4093:                 if ($env{'form.forceedit'}) {
 4094:                     $forceview = 1;
 4095:                 } else {
 4096:                     $forceedit = 1;
 4097:                 }
 4098:                 $cfile = $resurl;
 4099:             } elsif (($resurl eq '/adm/extresedit') && ($symb || $env{'form.folderpath'})) {
 4100:                 $incourse = 1;
 4101:                 $forceview = 1;
 4102:                 if ($symb) {
 4103:                     my ($map,$id,$res)=&decode_symb($symb);
 4104:                     $env{'request.symb'} = $symb;
 4105:                     $cfile = &clutter($res);
 4106:                 } else {
 4107:                     $cfile = $env{'form.suppurl'};
 4108:                     my $escfile = &unescape($cfile);
 4109:                     if ($escfile =~ m{^/adm/$cdom/$cnum/\d+/ext\.tool$}) {
 4110:                         $cfile = '/adm/wrapper'.$escfile;
 4111:                     } else {
 4112:                         $escfile =~ s{^http://}{};
 4113:                         $cfile = &escape("/adm/wrapper/ext/$escfile");
 4114:                     }
 4115:                 }
 4116:             } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
 4117:                 if ($env{'form.forceedit'}) {
 4118:                     $forceview = 1;
 4119:                 } else {
 4120:                     $forceedit = 1;
 4121:                 }
 4122:                 $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
 4123:             }
 4124:         }
 4125:         if ($uploaded || $incourse) {
 4126:             $home=&homeserver($cnum,$cdom);
 4127:         } elsif ($file !~ m{/$}) {
 4128:             $file=~s{^(priv/$match_domain/$match_username)}{/$1};
 4129:             $file=~s{^($match_domain/$match_username)}{/priv/$1};
 4130:             # Check that the user has permission to edit this resource
 4131:             my $setpriv = 1;
 4132:             my ($cfuname,$cfudom)=&constructaccess($file,$setpriv);
 4133:             if (defined($cfudom)) {
 4134:                 $home=&homeserver($cfuname,$cfudom);
 4135:                 $cfile=$file;
 4136:             }
 4137:         }
 4138:         if (($cfile ne '') && (!$incourse || $uploaded) && 
 4139:             (($home ne '') && ($home ne 'no_host'))) {
 4140:             my @ids=&current_machine_ids();
 4141:             unless (grep(/^\Q$home\E$/,@ids)) {
 4142:                 $switchserver=1;
 4143:             }
 4144:         }
 4145:     }
 4146:     return ($cfile,$home,$switchserver,$forceedit,$forceview);
 4147: }
 4148: 
 4149: sub is_course_upload {
 4150:     my ($file,$cnum,$cdom) = @_;
 4151:     my $uploadpath = &LONCAPA::propath($cdom,$cnum);
 4152:     $uploadpath =~ s{^\/}{};
 4153:     if (($file =~ m{^\Q$uploadpath\E/userfiles/(docs|supplemental)/}) ||
 4154:         ($file =~ m{^userfiles/\Q$cdom\E/\Q$cnum\E/(docs|supplemental)/})) {
 4155:         return 1;
 4156:     }
 4157:     return;
 4158: }
 4159: 
 4160: sub in_course {
 4161:     my ($udom,$uname,$cdom,$cnum,$type,$hideprivileged) = @_;
 4162:     if ($hideprivileged) {
 4163:         my $skipuser;
 4164:         my %coursehash = &coursedescription($cdom.'_'.$cnum);
 4165:         my @possdoms = ($cdom);  
 4166:         if ($coursehash{'checkforpriv'}) { 
 4167:             push(@possdoms,split(/,/,$coursehash{'checkforpriv'})); 
 4168:         }
 4169:         if (&privileged($uname,$udom,\@possdoms)) {
 4170:             $skipuser = 1;
 4171:             if ($coursehash{'nothideprivileged'}) {
 4172:                 foreach my $item (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 4173:                     my $user;
 4174:                     if ($item =~ /:/) {
 4175:                         $user = $item;
 4176:                     } else {
 4177:                         $user = join(':',split(/[\@]/,$item));
 4178:                     }
 4179:                     if ($user eq $uname.':'.$udom) {
 4180:                         undef($skipuser);
 4181:                         last;
 4182:                     }
 4183:                 }
 4184:             }
 4185:             if ($skipuser) {
 4186:                 return 0;
 4187:             }
 4188:         }
 4189:     }
 4190:     $type ||= 'any';
 4191:     if (!defined($cdom) || !defined($cnum)) {
 4192:         my $cid  = $env{'request.course.id'};
 4193:         $cdom = $env{'course.'.$cid.'.domain'};
 4194:         $cnum = $env{'course.'.$cid.'.num'};
 4195:     }
 4196:     my $typesref;
 4197:     if (($type eq 'any') || ($type eq 'all')) {
 4198:         $typesref = ['active','previous','future'];
 4199:     } elsif ($type eq 'previous' || $type eq 'future') {
 4200:         $typesref = [$type];
 4201:     }
 4202:     my %roles = &get_my_roles($uname,$udom,'userroles',
 4203:                               $typesref,undef,[$cdom]);
 4204:     my ($tmp) = keys(%roles);
 4205:     return 0 if ($tmp =~ /^(con_lost|error|no_such_host)/i);
 4206:     my @course_roles = grep(/^\Q$cnum\E:\Q$cdom\E:/, keys(%roles));
 4207:     if (@course_roles > 0) {
 4208:         return 1;
 4209:     }
 4210:     return 0;
 4211: }
 4212: 
 4213: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
 4214: # input: action, courseID, current domain, intended
 4215: #        path to file, source of file, instruction to parse file for objects,
 4216: #        ref to hash for embedded objects,
 4217: #        ref to hash for codebase of java objects.
 4218: #        reference to scalar to accommodate mime type determined
 4219: #          from File::MMagic if $parser = parse.
 4220: #
 4221: # output: url to file (if action was uploaddoc), 
 4222: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
 4223: #
 4224: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
 4225: # course.
 4226: #
 4227: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 4228: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
 4229: #          course's home server.
 4230: #
 4231: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
 4232: #          be copied from $source (current location) to 
 4233: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 4234: #         and will then be copied to
 4235: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
 4236: #         course's home server.
 4237: #
 4238: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 4239: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
 4240: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 4241: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
 4242: #         in course's home server.
 4243: #
 4244: 
 4245: sub process_coursefile {
 4246:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
 4247:         $mimetype)=@_;
 4248:     my $fetchresult;
 4249:     my $home=&homeserver($docuname,$docudom);
 4250:     if ($action eq 'propagate') {
 4251:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 4252: 			     $home);
 4253:     } else {
 4254:         my $fpath = '';
 4255:         my $fname = $file;
 4256:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 4257:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 4258:         my $filepath = &build_filepath($fpath);
 4259:         if ($action eq 'copy') {
 4260:             if ($source eq '') {
 4261:                 $fetchresult = 'no source file';
 4262:                 return $fetchresult;
 4263:             } else {
 4264:                 my $destination = $filepath.'/'.$fname;
 4265:                 rename($source,$destination);
 4266:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 4267:                                  $home);
 4268:             }
 4269:         } elsif ($action eq 'uploaddoc') {
 4270:             open(my $fh,'>',$filepath.'/'.$fname);
 4271:             print $fh $env{'form.'.$source};
 4272:             close($fh);
 4273:             if ($parser eq 'parse') {
 4274:                 my $mm = new File::MMagic;
 4275:                 my $type = $mm->checktype_filename($filepath.'/'.$fname);
 4276:                 if ($type eq 'text/html') {
 4277:                     my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
 4278:                     unless ($parse_result eq 'ok') {
 4279:                         &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
 4280:                     }
 4281:                 }
 4282:                 if (ref($mimetype)) {
 4283:                     $$mimetype = $type;
 4284:                 } 
 4285:             }
 4286:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 4287:                                  $home);
 4288:             if ($fetchresult eq 'ok') {
 4289:                 return '/uploaded/'.$fpath.'/'.$fname;
 4290:             } else {
 4291:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 4292:                         ' to host '.$home.': '.$fetchresult);
 4293:                 return '/adm/notfound.html';
 4294:             }
 4295:         }
 4296:     }
 4297:     unless ( $fetchresult eq 'ok') {
 4298:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 4299:              ' to host '.$home.': '.$fetchresult);
 4300:     }
 4301:     return $fetchresult;
 4302: }
 4303: 
 4304: sub build_filepath {
 4305:     my ($fpath) = @_;
 4306:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
 4307:     unless ($fpath eq '') {
 4308:         my @parts=split('/',$fpath);
 4309:         foreach my $part (@parts) {
 4310:             $filepath.= '/'.$part;
 4311:             if ((-e $filepath)!=1) {
 4312:                 mkdir($filepath,0777);
 4313:             }
 4314:         }
 4315:     }
 4316:     return $filepath;
 4317: }
 4318: 
 4319: sub store_edited_file {
 4320:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
 4321:     my $file = $primary_url;
 4322:     $file =~ s#^/uploaded/$docudom/$docuname/##;
 4323:     my $fpath = '';
 4324:     my $fname = $file;
 4325:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 4326:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 4327:     my $filepath = &build_filepath($fpath);
 4328:     open(my $fh,'>',$filepath.'/'.$fname);
 4329:     print $fh $content;
 4330:     close($fh);
 4331:     my $home=&homeserver($docuname,$docudom);
 4332:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 4333: 			  $home);
 4334:     if ($$fetchresult eq 'ok') {
 4335:         return '/uploaded/'.$fpath.'/'.$fname;
 4336:     } else {
 4337:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 4338: 		 ' to host '.$home.': '.$$fetchresult);
 4339:         return '/adm/notfound.html';
 4340:     }
 4341: }
 4342: 
 4343: sub clean_filename {
 4344:     my ($fname,$args)=@_;
 4345: # Replace Windows backslashes by forward slashes
 4346:     $fname=~s/\\/\//g;
 4347:     if (!$args->{'keep_path'}) {
 4348:         # Get rid of everything but the actual filename
 4349: 	$fname=~s/^.*\/([^\/]+)$/$1/;
 4350:     }
 4351: # Replace spaces by underscores
 4352:     $fname=~s/\s+/\_/g;
 4353: # Transliterate non-ascii text to ascii
 4354:     my $lang = &Apache::lonlocal::current_language();
 4355:     $fname = &LONCAPA::transliterate::fname_to_ascii($fname,$lang);
 4356: # Replace all other weird characters by nothing
 4357:     $fname=~s{[^/\w\.\-]}{}g;
 4358: # Replace all .\d. sequences with _\d. so they no longer look like version
 4359: # numbers
 4360:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
 4361: # Replace three or more adjacent underscores with one for consistency 
 4362: # with loncfile::filename_check() so complete url can be extracted by
 4363: # lonnet::decode_symb()
 4364:     $fname=~s/_{3,}/_/g;
 4365:     return $fname;
 4366: }
 4367: 
 4368: # This Function checks if an Image's dimensions exceed either $resizewidth (width) 
 4369: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an 
 4370: # image with the same aspect ratio as the original, but with dimensions which do 
 4371: # not exceed $resizewidth and $resizeheight.
 4372:  
 4373: sub resizeImage {
 4374:     my ($img_path,$resizewidth,$resizeheight) = @_;
 4375:     my $ima = Image::Magick->new;
 4376:     my $resized;
 4377:     if (-e $img_path) {
 4378:         $ima->Read($img_path);
 4379:         if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
 4380:             my $width = $ima->Get('width');
 4381:             my $height = $ima->Get('height');
 4382:             if ($width > $resizewidth) {
 4383: 	        my $factor = $width/$resizewidth;
 4384:                 my $newheight = $height/$factor;
 4385:                 $ima->Scale(width=>$resizewidth,height=>$newheight);
 4386:                 $resized = 1;
 4387:             }
 4388:         }
 4389:         if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
 4390:             my $width = $ima->Get('width');
 4391:             my $height = $ima->Get('height');
 4392:             if ($height > $resizeheight) {
 4393:                 my $factor = $height/$resizeheight;
 4394:                 my $newwidth = $width/$factor;
 4395:                 $ima->Scale(width=>$newwidth,height=>$resizeheight);
 4396:                 $resized = 1;
 4397:             }
 4398:         }
 4399:         if ($resized) {
 4400:             $ima->Write($img_path);
 4401:         }
 4402:     }
 4403:     return;
 4404: }
 4405: 
 4406: # --------------- Take an uploaded file and put it into the userfiles directory
 4407: # input: $formname - the contents of the file are in $env{"form.$formname"}
 4408: #                    the desired filename is in $env{"form.$formname.filename"}
 4409: #        $context - possible values: coursedoc, existingfile, overwrite, 
 4410: #                                    canceloverwrite, scantron, toollogo  or ''.
 4411: #                   if 'coursedoc': upload to the current course
 4412: #                   if 'existingfile': write file to tmp/overwrites directory 
 4413: #                   if 'canceloverwrite': delete file written to tmp/overwrites directory
 4414: #                   $context is passed as argument to &finishuserfileupload
 4415: #        $subdir - directory in userfile to store the file into
 4416: #        $parser - instruction to parse file for objects ($parser = parse) or
 4417: #                  if context is 'scantron', $parser is hashref of csv column mapping
 4418: #                  (e.g.,{ PaperID => 0, LastName => 1, FirstName => 2, ID => 3, 
 4419: #                          Section => 4, CODE => 5, FirstQuestion => 9 }).
 4420: #        $allfiles - reference to hash for embedded objects
 4421: #        $codebase - reference to hash for codebase of java objects
 4422: #        $destuname - username for permanent storage of uploaded file
 4423: #        $destudom - domain for permanaent storage of uploaded file
 4424: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
 4425: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
 4426: #        $resizewidth - width (pixels) to which to resize uploaded image
 4427: #        $resizeheight - height (pixels) to which to resize uploaded image
 4428: #        $mimetype - reference to scalar to accommodate mime type determined
 4429: #                    from File::MMagic.
 4430: # 
 4431: # output: url of file in userspace, or error: <message> 
 4432: #             or /adm/notfound.html if failure to upload occurse
 4433: 
 4434: sub userfileupload {
 4435:     my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
 4436:         $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
 4437:     if (!defined($subdir)) { $subdir='unknown'; }
 4438:     my $fname=$env{'form.'.$formname.'.filename'};
 4439:     $fname=&clean_filename($fname);
 4440:     # See if there is anything left
 4441:     unless ($fname) { return 'error: no uploaded file'; }
 4442:     # If filename now begins with a . prepend unix timestamp _ milliseconds
 4443:     if ($fname =~ /^\./) {
 4444:         my ($s,$usec) = &gettimeofday();
 4445:         while (length($usec) < 6) {
 4446:             $usec = '0'.$usec;
 4447:         }
 4448:         $fname = $s.'_'.substr($usec,0,3).$fname;
 4449:     }
 4450:     # Files uploaded to help request form, or uploaded to "create course" page are handled differently
 4451:     if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
 4452:         (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
 4453:          ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
 4454:         my $now = time;
 4455:         my $filepath;
 4456:         if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
 4457:              $filepath = 'tmp/helprequests/'.$now;
 4458:         } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
 4459:              $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
 4460:                          '_'.$env{'user.domain'}.'/pending';
 4461:         } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
 4462:             my ($docuname,$docudom);
 4463:             if ($destudom =~ /^$match_domain$/) {
 4464:                 $docudom = $destudom;
 4465:             } else {
 4466:                 $docudom = $env{'user.domain'};
 4467:             }
 4468:             if ($destuname =~ /^$match_username$/) {
 4469:                 $docuname = $destuname;
 4470:             } else {
 4471:                 $docuname = $env{'user.name'};
 4472:             }
 4473:             if (exists($env{'form.group'})) {
 4474:                 $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 4475:                 $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 4476:             }
 4477:             $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
 4478:             if ($context eq 'canceloverwrite') {
 4479:                 my $tempfile =  $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
 4480:                 if (-e  $tempfile) {
 4481:                     my @info = stat($tempfile);
 4482:                     if ($info[9] eq $env{'form.timestamp'}) {
 4483:                         unlink($tempfile);
 4484:                     }
 4485:                 }
 4486:                 return;
 4487:             }
 4488:         }
 4489:         # Create the directory if not present
 4490:         my @parts=split(/\//,$filepath);
 4491:         my $fullpath = $perlvar{'lonDaemons'};
 4492:         for (my $i=0;$i<@parts;$i++) {
 4493:             $fullpath .= '/'.$parts[$i];
 4494:             if ((-e $fullpath)!=1) {
 4495:                 mkdir($fullpath,0777);
 4496:             }
 4497:         }
 4498:         open(my $fh,'>',$fullpath.'/'.$fname);
 4499:         print $fh $env{'form.'.$formname};
 4500:         close($fh);
 4501:         if ($context eq 'existingfile') {
 4502:             my @info = stat($fullpath.'/'.$fname);
 4503:             return ($fullpath.'/'.$fname,$info[9]);
 4504:         } else {
 4505:             return $fullpath.'/'.$fname;
 4506:         }
 4507:     }
 4508:     if ($subdir eq 'scantron') {
 4509:         $fname = 'scantron_orig_'.$fname;
 4510:     } else {
 4511:         $fname="$subdir/$fname";
 4512:     }
 4513:     if ($context eq 'coursedoc') {
 4514: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 4515: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 4516:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
 4517:             return &finishuserfileupload($docuname,$docudom,
 4518: 					 $formname,$fname,$parser,$allfiles,
 4519: 					 $codebase,$thumbwidth,$thumbheight,
 4520:                                          $resizewidth,$resizeheight,$context,$mimetype);
 4521:         } else {
 4522:             if ($env{'form.folder'}) {
 4523:                 $fname=$env{'form.folder'}.'/'.$fname;
 4524:             }
 4525:             return &process_coursefile('uploaddoc',$docuname,$docudom,
 4526: 				       $fname,$formname,$parser,
 4527: 				       $allfiles,$codebase,$mimetype);
 4528:         }
 4529:     } elsif (defined($destuname)) {
 4530:         my $docuname=$destuname;
 4531:         my $docudom=$destudom;
 4532: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
 4533: 				     $parser,$allfiles,$codebase,
 4534:                                      $thumbwidth,$thumbheight,
 4535:                                      $resizewidth,$resizeheight,$context,$mimetype);
 4536:     } else {
 4537:         my $docuname=$env{'user.name'};
 4538:         my $docudom=$env{'user.domain'};
 4539:         if ((exists($env{'form.group'})) || ($context eq 'syllabus')) {
 4540:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 4541:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 4542:         }
 4543: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
 4544: 				     $parser,$allfiles,$codebase,
 4545:                                      $thumbwidth,$thumbheight,
 4546:                                      $resizewidth,$resizeheight,$context,$mimetype);
 4547:     }
 4548: }
 4549: 
 4550: sub finishuserfileupload {
 4551:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
 4552:         $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
 4553:     my $path=$docudom.'/'.$docuname.'/';
 4554:     my $filepath=$perlvar{'lonDocRoot'};
 4555:   
 4556:     my ($fnamepath,$file,$fetchthumb);
 4557:     $file=$fname;
 4558:     if ($fname=~m|/|) {
 4559:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
 4560: 	$path.=$fnamepath.'/';
 4561:     }
 4562:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
 4563:     my $count;
 4564:     for ($count=4;$count<=$#parts;$count++) {
 4565:         $filepath.="/$parts[$count]";
 4566:         if ((-e $filepath)!=1) {
 4567: 	    mkdir($filepath,0777);
 4568:         }
 4569:     }
 4570: 
 4571: # Save the file
 4572:     {
 4573: 	if (!open(FH,'>',$filepath.'/'.$file)) {
 4574: 	    &logthis('Failed to create '.$filepath.'/'.$file);
 4575: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
 4576: 	    return '/adm/notfound.html';
 4577: 	}
 4578:         if ($context eq 'overwrite') {
 4579:             my $source =  LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
 4580:             my $target = $filepath.'/'.$file;
 4581:             if (-e $source) {
 4582:                 my @info = stat($source);
 4583:                 if ($info[9] eq $env{'form.timestamp'}) {   
 4584:                     unless (&File::Copy::move($source,$target)) {
 4585:                         &logthis('Failed to overwrite '.$filepath.'/'.$file);
 4586:                         return "Moving from $source failed";
 4587:                     }
 4588:                 } else {
 4589:                     return "Temporary file: $source had unexpected date/time for last modification";
 4590:                 }
 4591:             } else {
 4592:                 return "Temporary file: $source missing";
 4593:             }
 4594:         } elsif (!print FH ($env{'form.'.$formname})) {
 4595: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
 4596: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
 4597: 	    return '/adm/notfound.html';
 4598: 	}
 4599: 	close(FH);
 4600:         if ($resizewidth && $resizeheight) {
 4601:             my $mm = new File::MMagic;
 4602:             my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
 4603:             if ($mime_type =~ m{^image/}) {
 4604: 	        &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
 4605:             }  
 4606: 	}
 4607:     }
 4608:     if (($context eq 'coursedoc') || ($parser eq 'parse')) {
 4609:         if (ref($mimetype)) {
 4610:             if ($$mimetype eq '') {
 4611:                 my $mm = new File::MMagic;
 4612:                 my $type = $mm->checktype_filename($filepath.'/'.$file);
 4613:                 $$mimetype = $type;
 4614:             }
 4615:         }
 4616:     }
 4617:     if (($context ne 'scantron') && ($parser eq 'parse')) {
 4618:         if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
 4619:             my $parse_result = &extract_embedded_items($filepath.'/'.$file,
 4620:                                                        $allfiles,$codebase);
 4621:             unless ($parse_result eq 'ok') {
 4622:                 &logthis('Failed to parse '.$filepath.$file.
 4623: 	   	         ' for embedded media: '.$parse_result); 
 4624:             }
 4625:         }
 4626:     } elsif (($context eq 'scantron') && (ref($parser) eq 'HASH')) {
 4627:         my $format = $env{'form.scantron_format'};
 4628:         &bubblesheet_converter($docudom,$filepath.'/'.$file,$parser,$format);
 4629:     }
 4630:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
 4631:         my $input = $filepath.'/'.$file;
 4632:         my $output = $filepath.'/'.'tn-'.$file;
 4633:         my $makethumb; 
 4634:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
 4635:         if ($context eq 'toollogo') {
 4636:             my ($fullwidth,$fullheight) = &check_dimensions($input);
 4637:             if ($fullwidth ne '' && $fullheight ne '') {
 4638:                 if ($fullwidth > $thumbwidth && $fullheight > $thumbheight) {
 4639:                     $makethumb = 1;
 4640:                 }
 4641:             }
 4642:         } else {
 4643:             $makethumb = 1;
 4644:         }
 4645:         if ($makethumb) {
 4646:             my @args = ('convert','-sample',$thumbsize,$input,$output);
 4647:             system({$args[0]} @args);
 4648:             if (-e $filepath.'/'.'tn-'.$file) {
 4649:                 $fetchthumb  = 1; 
 4650:             }
 4651:         }
 4652:     }
 4653:  
 4654: # Notify homeserver to grep it
 4655: #
 4656:     my $docuhome=&homeserver($docuname,$docudom);	
 4657:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
 4658:     if ($fetchresult eq 'ok') {
 4659:         if ($fetchthumb) {
 4660:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
 4661:             if ($thumbresult ne 'ok') {
 4662:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
 4663:                          $docuhome.': '.$thumbresult);
 4664:             }
 4665:         }
 4666: #
 4667: # Return the URL to it
 4668:         return '/uploaded/'.$path.$file;
 4669:     } else {
 4670:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
 4671: 		 ': '.$fetchresult);
 4672:         return '/adm/notfound.html';
 4673:     }
 4674: }
 4675: 
 4676: sub extract_embedded_items {
 4677:     my ($fullpath,$allfiles,$codebase,$content) = @_;
 4678:     my @state = ();
 4679:     my (%lastids,%related,%shockwave,%flashvars);
 4680:     my %javafiles = (
 4681:                       codebase => '',
 4682:                       code => '',
 4683:                       archive => ''
 4684:                     );
 4685:     my %mediafiles = (
 4686:                       src => '',
 4687:                       movie => '',
 4688:                      );
 4689:     my $p;
 4690:     if ($content) {
 4691:         $p = HTML::LCParser->new($content);
 4692:     } else {
 4693:         $p = HTML::LCParser->new($fullpath);
 4694:     }
 4695:     while (my $t=$p->get_token()) {
 4696: 	if ($t->[0] eq 'S') {
 4697: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
 4698: 	    push(@state, $tagname);
 4699:             if (lc($tagname) eq 'allow') {
 4700:                 &add_filetype($allfiles,$attr->{'src'},'src');
 4701:             }
 4702: 	    if (lc($tagname) eq 'img') {
 4703: 		&add_filetype($allfiles,$attr->{'src'},'src');
 4704: 	    }
 4705: 	    if (lc($tagname) eq 'a') {
 4706:                 unless (($attr->{'href'} =~ /^#/) || ($attr->{'href'} eq '')) {
 4707:                     &add_filetype($allfiles,$attr->{'href'},'href');
 4708:                 }
 4709: 	    }
 4710:             if (lc($tagname) eq 'script') {
 4711:                 my $src;
 4712:                 if ($attr->{'archive'} =~ /\.jar$/i) {
 4713:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
 4714:                 } else {
 4715:                     if ($attr->{'src'} ne '') {
 4716:                         $src = $attr->{'src'};
 4717:                         &add_filetype($allfiles,$src,'src');
 4718:                     }
 4719:                 }
 4720:                 my $text = $p->get_trimmed_text();
 4721:                 if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
 4722:                     my @swfargs = split(/,/,$1);
 4723:                     foreach my $item (@swfargs) {
 4724:                         $item =~ s/["']//g;
 4725:                         $item =~ s/^\s+//;
 4726:                         $item =~ s/\s+$//;
 4727:                     }
 4728:                     if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
 4729:                         if (ref($related{$swfargs[0]}) eq 'ARRAY') {
 4730:                             push(@{$related{$swfargs[0]}},$swfargs[2]);
 4731:                         } else {
 4732:                             $related{$swfargs[0]} = [$swfargs[2]];
 4733:                         }
 4734:                     }
 4735:                 }
 4736:             }
 4737:             if (lc($tagname) eq 'link') {
 4738:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
 4739:                     &add_filetype($allfiles,$attr->{'href'},'href');
 4740:                 }
 4741:             }
 4742: 	    if (lc($tagname) eq 'object' ||
 4743: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
 4744: 		foreach my $item (keys(%javafiles)) {
 4745: 		    $javafiles{$item} = '';
 4746: 		}
 4747:                 if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
 4748:                     $lastids{lc($tagname)} = $attr->{'id'};
 4749:                 }
 4750: 	    }
 4751: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
 4752: 		my $name = lc($attr->{'name'});
 4753: 		foreach my $item (keys(%javafiles)) {
 4754: 		    if ($name eq $item) {
 4755: 			$javafiles{$item} = $attr->{'value'};
 4756: 			last;
 4757: 		    }
 4758: 		}
 4759:                 my $pathfrom;
 4760: 		foreach my $item (keys(%mediafiles)) {
 4761: 		    if ($name eq $item) {
 4762:                         $pathfrom = $attr->{'value'};
 4763:                         $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
 4764: 			&add_filetype($allfiles,$pathfrom,$name);
 4765: 			last;
 4766: 		    }
 4767: 		}
 4768:                 if ($name eq 'flashvars') {
 4769:                     $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
 4770:                 }
 4771:                 if ($pathfrom ne '') {
 4772:                     &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
 4773:                                          $pathfrom);
 4774:                 }
 4775: 	    }
 4776: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
 4777: 		foreach my $item (keys(%javafiles)) {
 4778: 		    if ($attr->{$item}) {
 4779: 			$javafiles{$item} = $attr->{$item};
 4780: 			last;
 4781: 		    }
 4782: 		}
 4783: 		foreach my $item (keys(%mediafiles)) {
 4784: 		    if ($attr->{$item}) {
 4785: 			&add_filetype($allfiles,$attr->{$item},$item);
 4786: 			last;
 4787: 		    }
 4788: 		}
 4789:                 if (lc($tagname) eq 'embed') {
 4790:                     if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
 4791:                         &embedded_dependency($allfiles,\%related,$attr->{'name'},
 4792:                                              $attr->{'src'});
 4793:                     }
 4794:                 }
 4795: 	    }
 4796:             if (lc($tagname) eq 'iframe') {
 4797:                 my $src = $attr->{'src'} ;
 4798:                 if (($src ne '') && ($src !~ m{^(/|https?://)})) {
 4799:                     &add_filetype($allfiles,$src,'src');
 4800:                 } elsif ($src =~ m{^/}) {
 4801:                     if ($env{'request.course.id'}) {
 4802:                         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 4803:                         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 4804:                         my $url = &hreflocation('',$fullpath);
 4805:                         if ($url =~ m{^/uploaded/$cdom/$cnum/docs/(\w+/\d+)/}) {
 4806:                             my $relpath = $1;
 4807:                             if ($src =~ m{^/uploaded/$cdom/$cnum/docs/\Q$relpath\E/(.+)$}) {
 4808:                                 &add_filetype($allfiles,$1,'src');
 4809:                             }
 4810:                         }
 4811:                     }
 4812:                 }
 4813:             }
 4814:             if ($t->[4] =~ m{/>$}) {
 4815:                 pop(@state);
 4816:             }
 4817: 	} elsif ($t->[0] eq 'E') {
 4818: 	    my ($tagname) = ($t->[1]);
 4819: 	    if ($javafiles{'codebase'} ne '') {
 4820: 		$javafiles{'codebase'} .= '/';
 4821: 	    }  
 4822: 	    if (lc($tagname) eq 'applet' ||
 4823: 		lc($tagname) eq 'object' ||
 4824: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
 4825: 		) {
 4826: 		foreach my $item (keys(%javafiles)) {
 4827: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
 4828: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
 4829: 			&add_filetype($allfiles,$file,$item);
 4830: 		    }
 4831: 		}
 4832: 	    } 
 4833: 	    pop @state;
 4834: 	}
 4835:     }
 4836:     foreach my $id (sort(keys(%flashvars))) {
 4837:         if ($shockwave{$id} ne '') {
 4838:             my @pairs = split(/\&/,$flashvars{$id});
 4839:             foreach my $pair (@pairs) {
 4840:                 my ($key,$value) = split(/\=/,$pair);
 4841:                 if ($key eq 'thumb') {
 4842:                     &add_filetype($allfiles,$value,$key);
 4843:                 } elsif ($key eq 'content') {
 4844:                     my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
 4845:                     my ($ext) = ($value =~ /\.([^.]+)$/);
 4846:                     if ($ext ne '') {
 4847:                         &add_filetype($allfiles,$path.$value,$ext);
 4848:                     }
 4849:                 }
 4850:             }
 4851:         }
 4852:     }
 4853:     return 'ok';
 4854: }
 4855: 
 4856: sub add_filetype {
 4857:     my ($allfiles,$file,$type)=@_;
 4858:     if (exists($allfiles->{$file})) {
 4859: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
 4860: 	    push(@{$allfiles->{$file}}, &escape($type));
 4861: 	}
 4862:     } else {
 4863: 	@{$allfiles->{$file}} = (&escape($type));
 4864:     }
 4865: }
 4866: 
 4867: sub embedded_dependency {
 4868:     my ($allfiles,$related,$identifier,$pathfrom) = @_;
 4869:     if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
 4870:         if (($identifier ne '') &&
 4871:             (ref($related->{$identifier}) eq 'ARRAY') &&
 4872:             ($pathfrom ne '')) {
 4873:             my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
 4874:             foreach my $dep (@{$related->{$identifier}}) {
 4875:                 &add_filetype($allfiles,$path.$dep,'object');
 4876:             }
 4877:         }
 4878:     }
 4879:     return;
 4880: }
 4881: 
 4882: sub check_dimensions {
 4883:     my ($inputfile) = @_;
 4884:     my ($fullwidth,$fullheight);
 4885:     if (($inputfile =~ m|^[/\w.\-]+$|) && (-e $inputfile)) {
 4886:         my $mm = new File::MMagic;
 4887:         my $mime_type = $mm->checktype_filename($inputfile);
 4888:         if ($mime_type =~ m{^image/}) {
 4889:             if (open(PIPE,"identify $inputfile 2>&1 |")) {
 4890:                 my $imageinfo = <PIPE>;
 4891:                 if (!close(PIPE)) {
 4892:                     &Apache::lonnet::logthis("Failed to close PIPE opened to retrieve image information for $inputfile");
 4893:                 }
 4894:                 chomp($imageinfo);
 4895:                 my ($fullsize) =
 4896:                     ($imageinfo =~ /^\Q$inputfile\E\s+\w+\s+(\d+x\d+)/);
 4897:                 if ($fullsize) {
 4898:                     ($fullwidth,$fullheight) = split(/x/,$fullsize);
 4899:                 }
 4900:             }
 4901:         }
 4902:     }
 4903:     return ($fullwidth,$fullheight);
 4904: }
 4905: 
 4906: sub bubblesheet_converter {
 4907:     my ($cdom,$fullpath,$config,$format) = @_;
 4908:     if ((&domain($cdom) ne '') &&
 4909:         ($fullpath =~ m{^\Q$perlvar{'lonDocRoot'}/userfiles/$cdom/\E$match_courseid/scantron_orig}) &&
 4910:         (-e $fullpath) && (ref($config) eq 'HASH') && ($format ne '')) {
 4911:         my (%csvcols,%csvoptions);
 4912:         if (ref($config->{'fields'}) eq 'HASH') {  
 4913:             %csvcols = %{$config->{'fields'}};
 4914:         }
 4915:         if (ref($config->{'options'}) eq 'HASH') {
 4916:             %csvoptions = %{$config->{'options'}};
 4917:         }
 4918:         my %csvbynum = reverse(%csvcols);
 4919:         my %scantronconf = &get_scantron_config($format,$cdom);
 4920:         if (keys(%scantronconf)) {
 4921:             my %bynum = (
 4922:                           $scantronconf{CODEstart} => 'CODEstart',
 4923:                           $scantronconf{IDstart}   => 'IDstart',
 4924:                           $scantronconf{PaperID}   => 'PaperID',
 4925:                           $scantronconf{FirstName} => 'FirstName',
 4926:                           $scantronconf{LastName}  => 'LastName',
 4927:                           $scantronconf{Qstart}    => 'Qstart',
 4928:                         );
 4929:             my @ordered;
 4930:             foreach my $item (sort { $a <=> $b } keys(%bynum)) {
 4931:                 push(@ordered,$bynum{$item});
 4932:             }
 4933:             my %mapstart = (
 4934:                               CODEstart => 'CODE',
 4935:                               IDstart   => 'ID',
 4936:                               PaperID   => 'PaperID',
 4937:                               FirstName => 'FirstName',
 4938:                               LastName  => 'LastName',
 4939:                               Qstart    => 'FirstQuestion',
 4940:                            );
 4941:             my %maplength = (
 4942:                               CODEstart => 'CODElength',
 4943:                               IDstart   => 'IDlength',
 4944:                               PaperID   => 'PaperIDlength',
 4945:                               FirstName => 'FirstNamelength',
 4946:                               LastName  => 'LastNamelength',
 4947:             );
 4948:             if (open(my $fh,'<',$fullpath)) {
 4949:                 my $output;
 4950:                 my %lettdig = &letter_to_digits();
 4951:                 my %diglett = reverse(%lettdig);
 4952:                 my $numletts = scalar(keys(%lettdig));
 4953:                 my $num = 0;
 4954:                 while (my $line=<$fh>) {
 4955:                     $num ++;
 4956:                     next if (($num == 1) && ($csvoptions{'hdr'} == 1));
 4957:                     $line =~ s{[\r\n]+$}{};
 4958:                     my %found;
 4959:                     my @values = split(/,/,$line,-1);
 4960:                     my ($qstart,$record);
 4961:                     for (my $i=0; $i<@values; $i++) {
 4962:                         if ((($qstart ne '') && ($i > $qstart)) ||
 4963:                             ($csvbynum{$i} eq 'FirstQuestion')) {
 4964:                             if ($values[$i] eq '') {
 4965:                                 $values[$i] = $scantronconf{'Qoff'};
 4966:                             } elsif ($scantronconf{'Qon'} eq 'number') {
 4967:                                 if ($values[$i] =~ /^[A-Ja-j]$/) {
 4968:                                     $values[$i] = $lettdig{uc($values[$i])};
 4969:                                 }
 4970:                             } elsif ($scantronconf{'Qon'} eq 'letter') {
 4971:                                 if ($values[$i] =~ /^[0-9]$/) {
 4972:                                     $values[$i] = $diglett{$values[$i]};
 4973:                                 }
 4974:                             } else {
 4975:                                 if ($values[$i] =~ /^[0-9A-Ja-j]$/) {
 4976:                                     my $digit;
 4977:                                     if ($values[$i] =~ /^[A-Ja-j]$/) {
 4978:                                         $digit = $lettdig{uc($values[$i])}-1;
 4979:                                         if ($values[$i] eq 'J') {
 4980:                                             $digit += $numletts;
 4981:                                         }
 4982:                                     } elsif ($values[$i] =~ /^[0-9]$/) {
 4983:                                         $digit = $values[$i]-1;
 4984:                                         if ($values[$i] eq '0') {
 4985:                                             $digit += $numletts;
 4986:                                         }
 4987:                                     }
 4988:                                     my $qval='';
 4989:                                     for (my $j=0; $j<$scantronconf{'Qlength'}; $j++) {
 4990:                                         if ($j == $digit) {
 4991:                                             $qval .= $scantronconf{'Qon'};
 4992:                                         } else {
 4993:                                             $qval .= $scantronconf{'Qoff'};
 4994:                                         }
 4995:                                     }
 4996:                                     $values[$i] = $qval;
 4997:                                 }
 4998:                             }
 4999:                             if (length($values[$i]) > $scantronconf{'Qlength'}) {
 5000:                                 $values[$i] = substr($values[$i],0,$scantronconf{'Qlength'});
 5001:                             }
 5002:                             my $numblank = $scantronconf{'Qlength'} - length($values[$i]);
 5003:                             if ($numblank > 0) {
 5004:                                  $values[$i] .= ($scantronconf{'Qoff'} x $numblank);
 5005:                             }
 5006:                             if ($csvbynum{$i} eq 'FirstQuestion') {
 5007:                                 $qstart = $i;
 5008:                                 $found{$csvbynum{$i}} = $values[$i];
 5009:                             } else {
 5010:                                 $found{'FirstQuestion'} .= $values[$i];
 5011:                             }
 5012:                         } elsif (exists($csvbynum{$i})) {
 5013:                             if ($csvoptions{'rem'}) {
 5014:                                 $values[$i] =~ s/^\s+//;
 5015:                             }
 5016:                             if (($csvbynum{$i} eq 'PaperID') && ($csvoptions{'pad'})) {
 5017:                                 while (length($values[$i]) < $scantronconf{$maplength{$csvbynum{$i}}}) {
 5018:                                     $values[$i] = '0'.$values[$i];
 5019:                                 }
 5020:                             }
 5021:                             $found{$csvbynum{$i}} = $values[$i];
 5022:                         }
 5023:                     }
 5024:                     foreach my $item (@ordered) {
 5025:                         my $currlength = 1+length($record);
 5026:                         my $numspaces = $scantronconf{$item} - $currlength;
 5027:                         if ($numspaces > 0) {
 5028:                             $record .= (' ' x $numspaces);
 5029:                         }
 5030:                         if (($mapstart{$item} ne '') && (exists($found{$mapstart{$item}}))) {
 5031:                             unless ($item eq 'Qstart') {
 5032:                                 if (length($found{$mapstart{$item}}) > $scantronconf{$maplength{$item}}) {
 5033:                                     $found{$mapstart{$item}} = substr($found{$mapstart{$item}},0,$scantronconf{$maplength{$item}});
 5034:                                 }
 5035:                             }
 5036:                             $record .= $found{$mapstart{$item}};
 5037:                         }
 5038:                     }
 5039:                     $output .= "$record\n";
 5040:                 }
 5041:                 close($fh);
 5042:                 if ($output) {
 5043:                     if (open(my $fh,'>',$fullpath)) {
 5044:                         print $fh $output;
 5045:                         close($fh);
 5046:                     }
 5047:                 }
 5048:             }
 5049:         }
 5050:         return;
 5051:     }
 5052: }
 5053: 
 5054: sub letter_to_digits {
 5055:     my %lettdig = (
 5056:                     A => 1,
 5057:                     B => 2,
 5058:                     C => 3,
 5059:                     D => 4,
 5060:                     E => 5,
 5061:                     F => 6,
 5062:                     G => 7,
 5063:                     H => 8,
 5064:                     I => 9,
 5065:                     J => 0,
 5066:                   );
 5067:     return %lettdig;
 5068: }
 5069: 
 5070: sub get_scantron_config {
 5071:     my ($which,$cdom) = @_;
 5072:     my @lines = &get_scantronformat_file($cdom);
 5073:     my %config;
 5074:     #FIXME probably should move to XML it has already gotten a bit much now
 5075:     foreach my $line (@lines) {
 5076:         my ($name,$descrip)=split(/:/,$line);
 5077:         if ($name ne $which ) { next; }
 5078:         chomp($line);
 5079:         my @config=split(/:/,$line);
 5080:         $config{'name'}=$config[0];
 5081:         $config{'description'}=$config[1];
 5082:         $config{'CODElocation'}=$config[2];
 5083:         $config{'CODEstart'}=$config[3];
 5084:         $config{'CODElength'}=$config[4];
 5085:         $config{'IDstart'}=$config[5];
 5086:         $config{'IDlength'}=$config[6];
 5087:         $config{'Qstart'}=$config[7];
 5088:         $config{'Qlength'}=$config[8];
 5089:         $config{'Qoff'}=$config[9];
 5090:         $config{'Qon'}=$config[10];
 5091:         $config{'PaperID'}=$config[11];
 5092:         $config{'PaperIDlength'}=$config[12];
 5093:         $config{'FirstName'}=$config[13];
 5094:         $config{'FirstNamelength'}=$config[14];
 5095:         $config{'LastName'}=$config[15];
 5096:         $config{'LastNamelength'}=$config[16];
 5097:         $config{'BubblesPerRow'}=$config[17];
 5098:         last;
 5099:     }
 5100:     return %config;
 5101: }
 5102: 
 5103: sub get_scantronformat_file {
 5104:     my ($cdom) = @_;
 5105:     if ($cdom eq '') {
 5106:         $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
 5107:     }
 5108:     my %domconfig = &get_dom('configuration',['scantron'],$cdom);
 5109:     my $gottab = 0;
 5110:     my @lines;
 5111:     if (ref($domconfig{'scantron'}) eq 'HASH') {
 5112:         if ($domconfig{'scantron'}{'scantronformat'} ne '') {
 5113:             my $formatfile = &getfile($perlvar{'lonDocRoot'}.$domconfig{'scantron'}{'scantronformat'});
 5114:             if ($formatfile ne '-1') {
 5115:                 @lines = split("\n",$formatfile,-1);
 5116:                 $gottab = 1;
 5117:             }
 5118:         }
 5119:     }
 5120:     if (!$gottab) {
 5121:         my $confname = $cdom.'-domainconfig';
 5122:         my $default = $perlvar{'lonDocRoot'}.'/res/'.$cdom.'/'.$confname.'/default.tab';
 5123:         my $formatfile = &getfile($default);
 5124:         if ($formatfile ne '-1') {
 5125:             @lines = split("\n",$formatfile,-1);
 5126:             $gottab = 1;
 5127:         }
 5128:     }
 5129:     if (!$gottab) {
 5130:         my @domains = &current_machine_domains();
 5131:         if (grep(/^\Q$cdom\E$/,@domains)) {
 5132:             if (open(my $fh,'<',$perlvar{'lonTabDir'}.'/scantronformat.tab')) {
 5133:                 @lines = <$fh>;
 5134:                 close($fh);
 5135:             }
 5136:         } else {
 5137:             if (open(my $fh,'<',$perlvar{'lonTabDir'}.'/default_scantronformat.tab')) {
 5138:                 @lines = <$fh>;
 5139:                 close($fh);
 5140:             }
 5141:         }
 5142:         chomp(@lines);
 5143:     }
 5144:     return @lines;
 5145: }
 5146: 
 5147: sub removeuploadedurl {
 5148:     my ($url)=@_;	
 5149:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);    
 5150:     return &removeuserfile($uname,$udom,$fname);
 5151: }
 5152: 
 5153: sub removeuserfile {
 5154:     my ($docuname,$docudom,$fname)=@_;
 5155:     my $home=&homeserver($docuname,$docudom);    
 5156:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
 5157:     if ($result eq 'ok') {	
 5158:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
 5159:             my $metafile = $fname.'.meta';
 5160:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
 5161: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
 5162:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];	   
 5163:             my $sqlresult = 
 5164:                 &update_portfolio_table($docuname,$docudom,$file,
 5165:                                         'portfolio_metadata',$group,
 5166:                                         'delete');
 5167:         }
 5168:     }
 5169:     return $result;
 5170: }
 5171: 
 5172: sub mkdiruserfile {
 5173:     my ($docuname,$docudom,$dir)=@_;
 5174:     my $home=&homeserver($docuname,$docudom);
 5175:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
 5176: }
 5177: 
 5178: sub renameuserfile {
 5179:     my ($docuname,$docudom,$old,$new)=@_;
 5180:     my $home=&homeserver($docuname,$docudom);
 5181:     my $result = &reply("renameuserfile:$docudom:$docuname:".
 5182:                         &escape("$old").':'.&escape("$new"),$home);
 5183:     if ($result eq 'ok') {
 5184:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
 5185:             my $oldmeta = $old.'.meta';
 5186:             my $newmeta = $new.'.meta';
 5187:             my $metaresult = 
 5188:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
 5189: 	    my $url = "/uploaded/$docudom/$docuname/$old";
 5190:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
 5191:             my $sqlresult = 
 5192:                 &update_portfolio_table($docuname,$docudom,$file,
 5193:                                         'portfolio_metadata',$group,
 5194:                                         'delete');
 5195:         }
 5196:     }
 5197:     return $result;
 5198: }
 5199: 
 5200: # ------------------------------------------------------------------------- Log
 5201: 
 5202: sub log {
 5203:     my ($dom,$nam,$hom,$what)=@_;
 5204:     return critical("log:$dom:$nam:$what",$hom);
 5205: }
 5206: 
 5207: # ------------------------------------------------------------------ Course Log
 5208: #
 5209: # This routine flushes several buffers of non-mission-critical nature
 5210: #
 5211: 
 5212: sub flushcourselogs {
 5213:     &logthis('Flushing log buffers');
 5214: #
 5215: # course logs
 5216: # This is a log of all transactions in a course, which can be used
 5217: # for data mining purposes
 5218: #
 5219: # It also collects the courseid database, which lists last transaction
 5220: # times and course titles for all courseids
 5221: #
 5222:     my %courseidbuffer=();
 5223:     foreach my $crsid (keys(%courselogs)) {
 5224:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
 5225: 		          &escape($courselogs{$crsid}),
 5226: 		          $coursehombuf{$crsid}) eq 'ok') {
 5227: 	    delete $courselogs{$crsid};
 5228:         } else {
 5229:             &logthis('Failed to flush log buffer for '.$crsid);
 5230:             if (length($courselogs{$crsid})>40000) {
 5231:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
 5232:                         " exceeded maximum size, deleting.</font>");
 5233:                delete $courselogs{$crsid};
 5234:             }
 5235:         }
 5236:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
 5237:             'description' => $coursedescrbuf{$crsid},
 5238:             'inst_code'    => $courseinstcodebuf{$crsid},
 5239:             'type'        => $coursetypebuf{$crsid},
 5240:             'owner'       => $courseownerbuf{$crsid},
 5241:         };
 5242:     }
 5243: #
 5244: # Write course id database (reverse lookup) to homeserver of courses 
 5245: # Is used in pickcourse
 5246: #
 5247:     foreach my $crs_home (keys(%courseidbuffer)) {
 5248:         my $response = &courseidput(&host_domain($crs_home),
 5249:                                     $courseidbuffer{$crs_home},
 5250:                                     $crs_home,'timeonly');
 5251:     }
 5252: #
 5253: # File accesses
 5254: # Writes to the dynamic metadata of resources to get hit counts, etc.
 5255: #
 5256:     foreach my $entry (keys(%accesshash)) {
 5257:         if ($entry =~ /___count$/) {
 5258:             my ($dom,$name);
 5259:             ($dom,$name,undef)=
 5260: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
 5261:             if (! defined($dom) || $dom eq '' || 
 5262:                 ! defined($name) || $name eq '') {
 5263:                 my $cid = $env{'request.course.id'};
 5264: #
 5265: # FIXME 11/29/2021
 5266: # Typo in rev. 1.458 (2003/12/09)??
 5267: # These should likely by $env{'course.'.$cid.'.domain'} and $env{'course.'.$cid.'.num'}
 5268: #
 5269: # While these remain as $env{'request.'.$cid.'.domain'} and $env{'request.'.$cid.'.num'}
 5270: # $dom and $name will always be null, so the &inc() call will default to storing this data
 5271: # in a nohist_accesscount.db file for the user rather than the course.
 5272: #
 5273: # That said there is a lot of noise in the data being stored.
 5274: # So counts for prtspool/  and adm/ etc. are recorded.
 5275: #
 5276: # A review of which items ending '___count' are written to %accesshash should likely be 
 5277: # made before deciding whether to set these to 'course.' instead of 'request.'
 5278: #
 5279: # Under the current scheme each user receives a nohist_accesscount.db file listing 
 5280: # accesses for things which are not published resources, regardless of course, and
 5281: # there is not a nohist_accesscount.db file in a course, which might log accesses from
 5282: # anyone in the course for things which are not published resources.
 5283: #
 5284: # For an author, nohist_accesscount.db ends up having records for other items
 5285: # mixed up with the legitimate access counts for the author's published resources.
 5286: #
 5287:                 $dom  = $env{'request.'.$cid.'.domain'};
 5288:                 $name = $env{'request.'.$cid.'.num'};
 5289:             }
 5290:             my $value = $accesshash{$entry};
 5291:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
 5292:             my %temphash=($url => $value);
 5293:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
 5294:             if ($result eq 'ok') {
 5295:                 delete $accesshash{$entry};
 5296:             }
 5297:         } else {
 5298:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
 5299:             if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
 5300:             my %temphash=($entry => $accesshash{$entry});
 5301:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
 5302:                 delete $accesshash{$entry};
 5303:             }
 5304:         }
 5305:     }
 5306: #
 5307: # Roles
 5308: # Reverse lookup of user roles for course faculty/staff and co-authorship
 5309: #
 5310:     foreach my $entry (keys(%userrolehash)) {
 5311:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
 5312: 	    split(/\:/,$entry);
 5313:         if (&put('nohist_userroles',
 5314:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
 5315:                 $rudom,$runame) eq 'ok') {
 5316: 	    delete $userrolehash{$entry};
 5317:         }
 5318:     }
 5319: #
 5320: # Reverse lookup of domain roles (dc, ad, li, sc, dh, da, au)
 5321: #
 5322:     my %domrolebuffer = ();
 5323:     foreach my $entry (keys(%domainrolehash)) {
 5324:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
 5325:         if ($domrolebuffer{$rudom}) {
 5326:             $domrolebuffer{$rudom}.='&'.&escape($entry).
 5327:                       '='.&escape($domainrolehash{$entry});
 5328:         } else {
 5329:             $domrolebuffer{$rudom}.=&escape($entry).
 5330:                       '='.&escape($domainrolehash{$entry});
 5331:         }
 5332:         delete $domainrolehash{$entry};
 5333:     }
 5334:     foreach my $dom (keys(%domrolebuffer)) {
 5335: 	my %servers;
 5336: 	if (defined(&domain($dom,'primary'))) {
 5337: 	    my $primary=&domain($dom,'primary');
 5338: 	    my $hostname=&hostname($primary);
 5339: 	    $servers{$primary} = $hostname;
 5340: 	} else { 
 5341: 	    %servers = &get_servers($dom,'library');
 5342: 	}
 5343: 	foreach my $tryserver (keys(%servers)) {
 5344: 	    if (&reply('domroleput:'.$dom.':'.
 5345: 		       $domrolebuffer{$dom},$tryserver) eq 'ok') {
 5346: 		last;
 5347: 	    } else {  
 5348: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
 5349: 	    }
 5350:         }
 5351:     }
 5352:     $dumpcount++;
 5353: }
 5354: 
 5355: sub courselog {
 5356:     my $what=shift;
 5357:     $what=time.':'.$what;
 5358:     unless ($env{'request.course.id'}) { return ''; }
 5359:     $coursedombuf{$env{'request.course.id'}}=
 5360:        $env{'course.'.$env{'request.course.id'}.'.domain'};
 5361:     $coursenumbuf{$env{'request.course.id'}}=
 5362:        $env{'course.'.$env{'request.course.id'}.'.num'};
 5363:     $coursehombuf{$env{'request.course.id'}}=
 5364:        $env{'course.'.$env{'request.course.id'}.'.home'};
 5365:     $coursedescrbuf{$env{'request.course.id'}}=
 5366:        $env{'course.'.$env{'request.course.id'}.'.description'};
 5367:     $courseinstcodebuf{$env{'request.course.id'}}=
 5368:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
 5369:     $courseownerbuf{$env{'request.course.id'}}=
 5370:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
 5371:     $coursetypebuf{$env{'request.course.id'}}=
 5372:        $env{'course.'.$env{'request.course.id'}.'.type'};
 5373:     if (defined $courselogs{$env{'request.course.id'}}) {
 5374: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
 5375:     } else {
 5376: 	$courselogs{$env{'request.course.id'}}.=$what;
 5377:     }
 5378:     if (length($courselogs{$env{'request.course.id'}})>4048) {
 5379: 	&flushcourselogs();
 5380:     }
 5381: }
 5382: 
 5383: sub courseacclog {
 5384:     my $fnsymb=shift;
 5385:     unless ($env{'request.course.id'}) { return ''; }
 5386:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
 5387:     if ($fnsymb=~/$LONCAPA::assess_re/) {
 5388:         $what.=':POST';
 5389:         # FIXME: Probably ought to escape things....
 5390: 	foreach my $key (keys(%env)) {
 5391:             if ($key=~/^form\.(.*)/) {
 5392:                 my $formitem = $1;
 5393:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
 5394:                     $what.=':'.$formitem.'='.$env{$key};
 5395:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
 5396:                     if ($formitem eq 'proctorpassword') {
 5397:                         $what.=':'.$formitem.'=' . '*' x length($env{$key});
 5398:                     } else {
 5399:                         $what.=':'.$formitem.'='.$env{$key};
 5400:                     }
 5401:                 }
 5402:             }
 5403:         }
 5404:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
 5405:         # FIXME: We should not be depending on a form parameter that someone
 5406:         # editing lonsearchcat.pm might change in the future.
 5407:         if ($env{'form.phase'} eq 'course_search') {
 5408:             $what.= ':POST';
 5409:             # FIXME: Probably ought to escape things....
 5410:             foreach my $element ('courseexp','crsfulltext','crsrelated',
 5411:                                  'crsdiscuss') {
 5412:                 $what.=':'.$element.'='.$env{'form.'.$element};
 5413:             }
 5414:         }
 5415:     }
 5416:     &courselog($what);
 5417: }
 5418: 
 5419: sub countacc {
 5420:     my $url=&declutter(shift);
 5421:     return if (! defined($url) || $url eq '');
 5422:     unless ($env{'request.course.id'}) { return ''; }
 5423: #
 5424: # Mark that this url was used in this course
 5425: #
 5426:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
 5427: #
 5428: # Increase the access count for this resource in this child process
 5429: #
 5430:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
 5431:     $accesshash{$key}++;
 5432: }
 5433: 
 5434: sub linklog {
 5435:     my ($from,$to)=@_;
 5436:     $from=&declutter($from);
 5437:     $to=&declutter($to);
 5438:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
 5439:     $accesshash{$to.'___'.$from.'___goto'}=1;
 5440: }
 5441: 
 5442: sub statslog {
 5443:     my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
 5444:     if ($users<2) { return; }
 5445:     my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
 5446:             'course'       => $env{'request.course.id'},
 5447:             'sections'     => '"all"',
 5448:             'num_students' => $users,
 5449:             'part'         => $part,
 5450:             'symb'         => $symb,
 5451:             'mean_tries'   => $av_attempts,
 5452:             'deg_of_diff'  => $degdiff});
 5453:     foreach my $key (keys(%dynstore)) {
 5454:         $accesshash{$key}=$dynstore{$key};
 5455:     }
 5456: }
 5457:   
 5458: sub userrolelog {
 5459:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
 5460:     if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
 5461:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 5462:        $userrolehash
 5463:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 5464:                     =$tend.':'.$tstart;
 5465:     }
 5466:     if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
 5467:        $userrolehash
 5468:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
 5469:                     =$tend.':'.$tstart;
 5470:     }
 5471:     if ($trole =~ /^(dc|ad|li|au|dg|sc|dh|da)/ ) {
 5472:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 5473:        $domainrolehash
 5474:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 5475:                     = $tend.':'.$tstart;
 5476:     }
 5477: }
 5478: 
 5479: sub courserolelog {
 5480:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,
 5481:         $context,$othdomby,$requester)=@_;
 5482:     if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
 5483:         my $cdom = $1;
 5484:         my $cnum = $2;
 5485:         my $sec = $3;
 5486:         my $namespace = 'rolelog';
 5487:         my %storehash = (
 5488:                            role    => $trole,
 5489:                            start   => $tstart,
 5490:                            end     => $tend,
 5491:                            selfenroll => $selfenroll,
 5492:                            context    => $context,
 5493:                         );
 5494:         if ($othdomby) {
 5495:             if ($othdomby eq 'othdombydc') {
 5496:                 $storehash{'approval'} = 'domain';
 5497:             } elsif ($othdomby eq 'othdombyuser') {
 5498:                 $storehash{'approval'} = 'user'; 
 5499:             }
 5500:             if ($requester ne '') {
 5501:                 $storehash{'requester'} = $requester;
 5502:             }
 5503:         }
 5504:         if ($trole eq 'gr') {
 5505:             $namespace = 'groupslog';
 5506:             $storehash{'group'} = $sec;
 5507:         } else {
 5508:             $storehash{'section'} = $sec;
 5509:             my ($curruserdomstr,$newuserdomstr);
 5510:             if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.userdomains'})) {
 5511:                 $curruserdomstr = $env{'course.'.$env{'request.course.id'}.'.internal.userdomains'};
 5512:             } else {
 5513:                 my %courseinfo = &coursedescription($cdom.'/'.$cnum);
 5514:                 $curruserdomstr = $courseinfo{'internal.userdomains'};
 5515:             }
 5516:             if ($curruserdomstr ne '') {
 5517:                 my @udoms = split(/,/,$curruserdomstr);
 5518:                 unless (grep(/^\Q$domain\E/,@udoms)) {
 5519:                     push(@udoms,$domain);
 5520:                     $newuserdomstr = join(',',sort(@udoms));
 5521:                 }
 5522:             } else {
 5523:                 $newuserdomstr = $domain;
 5524:             }
 5525:             if ($newuserdomstr ne '') {
 5526:                 my $putresult = &put('environment',{ 'internal.userdomains' => $newuserdomstr },
 5527:                                      $cdom,$cnum);
 5528:                 if ($putresult eq 'ok') {
 5529:                     unless (($selfenroll) || ($context eq 'selfenroll')) { 
 5530:                         if (($context eq 'createcourse') || ($context eq 'requestcourses') ||
 5531:                             ($context eq 'automated') || ($context eq 'domain')) {
 5532:                             $env{'course.'.$cdom.'_'.$cnum.'.internal.userdomains'} = $newuserdomstr;
 5533:                         } elsif ($env{'request.course.id'} eq $cdom.'_'.$cnum) {
 5534:                             &appenv({'course.'.$cdom.'_'.$cnum.'.internal.userdomains' => $newuserdomstr});
 5535:                         }
 5536:                     }
 5537:                 }
 5538:             }
 5539:         }
 5540:         &write_log('course',$namespace,\%storehash,$delflag,$username,
 5541:                    $domain,$cnum,$cdom);
 5542:         if (($trole ne 'st') || ($sec ne '')) {
 5543:             &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
 5544:         }
 5545:     }
 5546:     return;
 5547: }
 5548: 
 5549: sub domainrolelog {
 5550:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,
 5551:         $context,$othdomby,$requester)=@_;
 5552:     if ($area =~ m{^/($match_domain)/$}) {
 5553:         my $cdom = $1;
 5554:         my $domconfiguser = &get_domainconfiguser($cdom);
 5555:         my $namespace = 'rolelog';
 5556:         my %storehash = (
 5557:                            role    => $trole,
 5558:                            start   => $tstart,
 5559:                            end     => $tend,
 5560:                            context => $context,
 5561:                         );
 5562:         if ($othdomby) {
 5563:             if ($othdomby eq 'othdombydc') {
 5564:                 $storehash{'approval'} = 'domain';
 5565:             } elsif ($othdomby eq 'othdombyuser') {
 5566:                 $storehash{'approval'} = 'user';
 5567:             }
 5568:             if ($requester ne '') {
 5569:                 $storehash{'requester'} = $requester;
 5570:             }
 5571:         }
 5572:         &write_log('domain',$namespace,\%storehash,$delflag,$username,
 5573:                    $domain,$domconfiguser,$cdom);
 5574:     }
 5575:     return;
 5576: 
 5577: }
 5578: 
 5579: sub coauthorrolelog {
 5580:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,
 5581:         $context,$othdomby,$requester)=@_;
 5582:     if ($area =~ m{^/($match_domain)/($match_username)$}) {
 5583:         my $audom = $1;
 5584:         my $auname = $2;
 5585:         my $namespace = 'rolelog';
 5586:         my %storehash = (
 5587:                            role    => $trole,
 5588:                            start   => $tstart,
 5589:                            end     => $tend,
 5590:                            context => $context,
 5591:                         );
 5592:         if ($othdomby) {
 5593:             if ($othdomby eq 'othdombydc') {
 5594:                 $storehash{'approval'} = 'domain';
 5595:             } elsif ($othdomby eq 'othdombyuser') {
 5596:                 $storehash{'approval'} = 'user';
 5597:             }
 5598:             if ($requester ne '') {
 5599:                 $storehash{'requester'} = $requester;
 5600:             }
 5601:         }
 5602:         &write_log('author',$namespace,\%storehash,$delflag,$username,
 5603:                    $domain,$auname,$audom);
 5604:     }
 5605:     return;
 5606: }
 5607: 
 5608: sub get_course_adv_roles {
 5609:     my ($cid,$codes) = @_;
 5610:     $cid=$env{'request.course.id'} unless (defined($cid));
 5611:     my %coursehash=&coursedescription($cid);
 5612:     my $crstype = &Apache::loncommon::course_type($cid);
 5613:     my %nothide=();
 5614:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 5615:         if ($user !~ /:/) {
 5616: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
 5617:         } else {
 5618:             $nothide{$user}=1;
 5619:         }
 5620:     }
 5621:     my @possdoms = ($coursehash{'domain'});
 5622:     if ($coursehash{'checkforpriv'}) {
 5623:         push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
 5624:     }
 5625:     my %returnhash=();
 5626:     my %dumphash=
 5627:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
 5628:     my $now=time;
 5629:     my %privileged;
 5630:     foreach my $entry (keys(%dumphash)) {
 5631: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
 5632:         if (($tstart) && ($tstart<0)) { next; }
 5633:         if (($tend) && ($tend<$now)) { next; }
 5634:         if (($tstart) && ($now<$tstart)) { next; }
 5635:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
 5636: 	if ($username eq '' || $domain eq '') { next; }
 5637:         if ((&privileged($username,$domain,\@possdoms)) &&
 5638:             (!$nothide{$username.':'.$domain})) { next; }
 5639: 	if ($role eq 'cr') { next; }
 5640:         if ($codes) {
 5641:             if ($section) { $role .= ':'.$section; }
 5642:             if ($returnhash{$role}) {
 5643:                 $returnhash{$role}.=','.$username.':'.$domain;
 5644:             } else {
 5645:                 $returnhash{$role}=$username.':'.$domain;
 5646:             }
 5647:         } else {
 5648:             my $key=&plaintext($role,$crstype);
 5649:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
 5650:             if ($returnhash{$key}) {
 5651: 	        $returnhash{$key}.=','.$username.':'.$domain;
 5652:             } else {
 5653:                 $returnhash{$key}=$username.':'.$domain;
 5654:             }
 5655:         }
 5656:     }
 5657:     return %returnhash;
 5658: }
 5659: 
 5660: sub get_my_roles {
 5661:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
 5662:     unless (defined($uname)) { $uname=$env{'user.name'}; }
 5663:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
 5664:     my (%dumphash,%nothide);
 5665:     if ($context eq 'userroles') {
 5666:         %dumphash = &dump('roles',$udom,$uname);
 5667:     } else {
 5668:         %dumphash = &dump('nohist_userroles',$udom,$uname);
 5669:         if ($hidepriv) {
 5670:             my %coursehash=&coursedescription($udom.'_'.$uname);
 5671:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 5672:                 if ($user !~ /:/) {
 5673:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
 5674:                 } else {
 5675:                     $nothide{$user} = 1;
 5676:                 }
 5677:             }
 5678:         }
 5679:     }
 5680:     my %returnhash=();
 5681:     my $now=time;
 5682:     my %privileged;
 5683:     foreach my $entry (keys(%dumphash)) {
 5684:         my ($role,$tend,$tstart);
 5685:         if ($context eq 'userroles') {
 5686:             next if ($entry =~ /^rolesdef/);
 5687: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
 5688:         } else {
 5689:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
 5690:         }
 5691:         if (($tstart) && ($tstart<0)) { next; }
 5692:         my $status = 'active';
 5693:         if (($tend) && ($tend<=$now)) {
 5694:             $status = 'previous';
 5695:         } 
 5696:         if (($tstart) && ($now<$tstart)) {
 5697:             $status = 'future';
 5698:         }
 5699:         if (ref($types) eq 'ARRAY') {
 5700:             if (!grep(/^\Q$status\E$/,@{$types})) {
 5701:                 next;
 5702:             } 
 5703:         } else {
 5704:             if ($status ne 'active') {
 5705:                 next;
 5706:             }
 5707:         }
 5708:         my ($rolecode,$username,$domain,$section,$area);
 5709:         if ($context eq 'userroles') {
 5710:             ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
 5711:             (undef,$domain,$username,$section) = split(/\//,$area);
 5712:         } else {
 5713:             ($role,$username,$domain,$section) = split(/\:/,$entry);
 5714:         }
 5715:         if (ref($roledoms) eq 'ARRAY') {
 5716:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
 5717:                 next;
 5718:             }
 5719:         }
 5720:         if (ref($roles) eq 'ARRAY') {
 5721:             if (!grep(/^\Q$role\E$/,@{$roles})) {
 5722:                 if ($role =~ /^cr\//) {
 5723:                     if (!grep(/^cr$/,@{$roles})) {
 5724:                         next;
 5725:                     }
 5726:                 } elsif ($role =~ /^gr\//) {
 5727:                     if (!grep(/^gr$/,@{$roles})) {
 5728:                         next;
 5729:                     }
 5730:                 } else {
 5731:                     next;
 5732:                 }
 5733:             }
 5734:         }
 5735:         if ($hidepriv) {
 5736:             my @privroles = ('dc','su');
 5737:             if ($context eq 'userroles') {
 5738:                 next if (grep(/^\Q$role\E$/,@privroles));
 5739:             } else {
 5740:                 my $possdoms = [$domain];
 5741:                 if (ref($roledoms) eq 'ARRAY') {
 5742:                    push(@{$possdoms},@{$roledoms}); 
 5743:                 }
 5744:                 if (&privileged($username,$domain,$possdoms,\@privroles)) {
 5745:                     if (!$nothide{$username.':'.$domain}) {
 5746:                         next;
 5747:                     }
 5748:                 }
 5749:             }
 5750:         }
 5751:         if ($withsec) {
 5752:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
 5753:                 $tstart.':'.$tend;
 5754:         } else {
 5755:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
 5756:         }
 5757:     }
 5758:     return %returnhash;
 5759: }
 5760: 
 5761: sub get_all_adhocroles {
 5762:     my ($dom) = @_;
 5763:     my @roles_by_num = ();
 5764:     my %domdefaults = &get_domain_defaults($dom);
 5765:     my (%description,%access_in_dom,%access_info);
 5766:     if (ref($domdefaults{'adhocroles'}) eq 'HASH') {
 5767:         my $count = 0;
 5768:         my %domcurrent = %{$domdefaults{'adhocroles'}};
 5769:         my %ordered;
 5770:         foreach my $role (sort(keys(%domcurrent))) {
 5771:             my ($order,$desc,$access_in_dom);
 5772:             if (ref($domcurrent{$role}) eq 'HASH') {
 5773:                 $order = $domcurrent{$role}{'order'};
 5774:                 $desc = $domcurrent{$role}{'desc'};
 5775:                 $access_in_dom{$role} = $domcurrent{$role}{'access'};
 5776:                 $access_info{$role} = $domcurrent{$role}{$access_in_dom{$role}};
 5777:             }
 5778:             if ($order eq '') {
 5779:                 $order = $count;
 5780:             }
 5781:             $ordered{$order} = $role;
 5782:             if ($desc ne '') {
 5783:                 $description{$role} = $desc;
 5784:             } else {
 5785:                 $description{$role}= $role;
 5786:             }
 5787:             $count++;
 5788:         }
 5789:         foreach my $item (sort {$a <=> $b } (keys(%ordered))) {
 5790:             push(@roles_by_num,$ordered{$item});
 5791:         }
 5792:     }
 5793:     return (\@roles_by_num,\%description,\%access_in_dom,\%access_info);
 5794: }
 5795: 
 5796: sub get_my_adhocroles {
 5797:     my ($cid,$checkreg) = @_;
 5798:     my ($cdom,$cnum,%info,@possroles,$description,$roles_by_num);
 5799:     if ($env{'request.course.id'} eq $cid) {
 5800:         $cdom = $env{'course.'.$cid.'.domain'};
 5801:         $cnum = $env{'course.'.$cid.'.num'};
 5802:         $info{'internal.coursecode'} = $env{'course.'.$cid.'.internal.coursecode'};
 5803:     } elsif ($cid =~ /^($match_domain)_($match_courseid)$/) {
 5804:         $cdom = $1;
 5805:         $cnum = $2;
 5806:         %info = &get('environment',['internal.coursecode'],
 5807:                      $cdom,$cnum);
 5808:     }
 5809:     if (($info{'internal.coursecode'} ne '') && ($checkreg)) {
 5810:         my $user = $env{'user.name'}.':'.$env{'user.domain'};
 5811:         my %rosterhash = &get('classlist',[$user],$cdom,$cnum);
 5812:         if ($rosterhash{$user} ne '') {
 5813:             my $type = (split(/:/,$rosterhash{$user}))[5];
 5814:             return ([],{}) if ($type eq 'auto');
 5815:         }
 5816:     }
 5817:     if (($cdom ne '') && ($cnum ne ''))  {
 5818:         if (($env{"user.role.dh./$cdom/"}) || ($env{"user.role.da./$cdom/"})) {
 5819:             my $then=$env{'user.login.time'};
 5820:             my $update=$env{'user.update.time'};
 5821:             if (!$update) {
 5822:                 $update = $then;
 5823:             }
 5824:             my @liveroles;
 5825:             foreach my $role ('dh','da') {
 5826:                 if ($env{"user.role.$role./$cdom/"}) {
 5827:                     my ($tstart,$tend)=split(/\./,$env{"user.role.$role./$cdom/"});
 5828:                     my $limit = $update;
 5829:                     if ($env{'request.role'} eq "$role./$cdom/") {
 5830:                         $limit = $then;
 5831:                     }
 5832:                     my $activerole = 1;
 5833:                     if ($tstart && $tstart>$limit) { $activerole = 0; }
 5834:                     if ($tend   && $tend  <$limit) { $activerole = 0; }
 5835:                     if ($activerole) {
 5836:                         push(@liveroles,$role);
 5837:                     }
 5838:                 }
 5839:             }
 5840:             if (@liveroles) {
 5841:                 if (&homeserver($cnum,$cdom) ne 'no_host') {
 5842:                     my ($accessref,$accessinfo,%access_in_dom);
 5843:                     ($roles_by_num,$description,$accessref,$accessinfo) = &get_all_adhocroles($cdom);
 5844:                     if (ref($roles_by_num) eq 'ARRAY') {
 5845:                         if (@{$roles_by_num}) {
 5846:                             my %settings;
 5847:                             if ($env{'request.course.id'} eq $cid) {
 5848:                                 foreach my $envkey (keys(%env)) {
 5849:                                     if ($envkey =~ /^\Qcourse.$cid.\E(internal\.adhoc.+)$/) {
 5850:                                         $settings{$1} = $env{$envkey};
 5851:                                     }
 5852:                                 }
 5853:                             } else {
 5854:                                 %settings = &dump('environment',$cdom,$cnum,'internal\.adhoc');
 5855:                             }
 5856:                             my %setincrs;
 5857:                             if ($settings{'internal.adhocaccess'}) {
 5858:                                 map { $setincrs{$_} = 1; } split(/,/,$settings{'internal.adhocaccess'});
 5859:                             }
 5860:                             my @statuses;
 5861:                             if ($env{'environment.inststatus'}) {
 5862:                                 @statuses = split(/,/,$env{'environment.inststatus'});
 5863:                             }
 5864:                             my $user = $env{'user.name'}.':'.$env{'user.domain'};
 5865:                             if (ref($accessref) eq 'HASH') {
 5866:                                 %access_in_dom = %{$accessref};
 5867:                             }
 5868:                             foreach my $role (@{$roles_by_num}) {
 5869:                                 my ($curraccess,@okstatus,@personnel);
 5870:                                 if ($setincrs{$role}) {
 5871:                                     ($curraccess,my $rest) = split(/=/,$settings{'internal.adhoc.'.$role});
 5872:                                     if ($curraccess eq 'status') {
 5873:                                         @okstatus = split(/\&/,$rest);
 5874:                                     } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
 5875:                                         @personnel = split(/\&/,$rest);
 5876:                                     }
 5877:                                 } else {
 5878:                                     $curraccess = $access_in_dom{$role};
 5879:                                     if (ref($accessinfo) eq 'HASH') {
 5880:                                         if ($curraccess eq 'status') {
 5881:                                             if (ref($accessinfo->{$role}) eq 'ARRAY') {
 5882:                                                 @okstatus = @{$accessinfo->{$role}};
 5883:                                             }
 5884:                                         } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
 5885:                                             if (ref($accessinfo->{$role}) eq 'ARRAY') {
 5886:                                                 @personnel = @{$accessinfo->{$role}};
 5887:                                             }
 5888:                                         }
 5889:                                     }
 5890:                                 }
 5891:                                 if ($curraccess eq 'none') {
 5892:                                     next;
 5893:                                 } elsif ($curraccess eq 'all') {
 5894:                                     push(@possroles,$role);
 5895:                                 } elsif ($curraccess eq 'dh') {
 5896:                                     if (grep(/^dh$/,@liveroles)) {
 5897:                                         push(@possroles,$role);
 5898:                                     } else {
 5899:                                         next;
 5900:                                     }
 5901:                                 } elsif ($curraccess eq 'da') {
 5902:                                     if (grep(/^da$/,@liveroles)) {
 5903:                                         push(@possroles,$role);
 5904:                                     } else {
 5905:                                         next;
 5906:                                     }
 5907:                                 } elsif ($curraccess eq 'status') {
 5908:                                     if (@okstatus) {
 5909:                                         if (!@statuses) {
 5910:                                             if (grep(/^default$/,@okstatus)) {
 5911:                                                 push(@possroles,$role);
 5912:                                             }
 5913:                                         } else {
 5914:                                             foreach my $status (@okstatus) {
 5915:                                                 if (grep(/^\Q$status\E$/,@statuses)) {
 5916:                                                     push(@possroles,$role);
 5917:                                                     last;
 5918:                                                 }
 5919:                                             }
 5920:                                         }
 5921:                                     }
 5922:                                 } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
 5923:                                     if (grep(/^\Q$user\E$/,@personnel)) {
 5924:                                         if ($curraccess eq 'exc') {
 5925:                                             push(@possroles,$role);
 5926:                                         }
 5927:                                     } elsif ($curraccess eq 'inc') {
 5928:                                         push(@possroles,$role);
 5929:                                     }
 5930:                                 }
 5931:                             }
 5932:                         }
 5933:                     }
 5934:                 }
 5935:             }
 5936:         }
 5937:     }
 5938:     unless (ref($description) eq 'HASH') {
 5939:         if (ref($roles_by_num) eq 'ARRAY') {
 5940:             my %desc;
 5941:             map { $desc{$_} = $_; } (@{$roles_by_num});
 5942:             $description = \%desc;
 5943:         } else {
 5944:             $description = {};
 5945:         }
 5946:     }
 5947:     return (\@possroles,$description);
 5948: }
 5949: 
 5950: # ----------------------------------------------------- Frontpage Announcements
 5951: #
 5952: #
 5953: 
 5954: sub postannounce {
 5955:     my ($server,$text)=@_;
 5956:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
 5957:     unless ($text=~/\w/) { $text=''; }
 5958:     return &reply('setannounce:'.&escape($text),$server);
 5959: }
 5960: 
 5961: sub getannounce {
 5962: 
 5963:     if (open(my $fh,"<",$perlvar{'lonDocRoot'}.'/announcement.txt')) {
 5964: 	my $announcement='';
 5965: 	while (my $line = <$fh>) { $announcement .= $line; }
 5966: 	close($fh);
 5967: 	if ($announcement=~/\w/) { 
 5968: 	    return 
 5969:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
 5970:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
 5971: 	} else {
 5972: 	    return '';
 5973: 	}
 5974:     } else {
 5975: 	return '';
 5976:     }
 5977: }
 5978: 
 5979: # ---------------------------------------------------------- Course ID routines
 5980: # Deal with domain's nohist_courseid.db files
 5981: #
 5982: 
 5983: sub courseidput {
 5984:     my ($domain,$storehash,$coursehome,$caller) = @_;
 5985:     return unless (ref($storehash) eq 'HASH');
 5986:     my $outcome;
 5987:     if ($caller eq 'timeonly') {
 5988:         my $cids = '';
 5989:         foreach my $item (keys(%$storehash)) {
 5990:             $cids.=&escape($item).'&';
 5991:         }
 5992:         $cids=~s/\&$//;
 5993:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
 5994:                           $coursehome);       
 5995:     } else {
 5996:         my $items = '';
 5997:         foreach my $item (keys(%$storehash)) {
 5998:             $items.= &escape($item).'='.
 5999:                      &freeze_escape($$storehash{$item}).'&';
 6000:         }
 6001:         $items=~s/\&$//;
 6002:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
 6003:                           $coursehome);
 6004:     }
 6005:     if ($outcome eq 'unknown_cmd') {
 6006:         my $what;
 6007:         foreach my $cid (keys(%$storehash)) {
 6008:             $what .= &escape($cid).'=';
 6009:             foreach my $item ('description','inst_code','owner','type') {
 6010:                 $what .= &escape($storehash->{$cid}{$item}).':';
 6011:             }
 6012:             $what =~ s/\:$/&/;
 6013:         }
 6014:         $what =~ s/\&$//;  
 6015:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
 6016:     } else {
 6017:         return $outcome;
 6018:     }
 6019: }
 6020: 
 6021: sub courseiddump {
 6022:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
 6023:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
 6024:         $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
 6025:         $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner,
 6026:         $hasuniquecode,$reqcrsdom,$reqinstcode)=@_;
 6027:     my $as_hash = 1;
 6028:     my %returnhash;
 6029:     if (!$domfilter) { $domfilter=''; }
 6030:     my %libserv = &all_library();
 6031:     foreach my $tryserver (keys(%libserv)) {
 6032:         if ( (  $hostidflag == 1 
 6033: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
 6034: 	     || (!defined($hostidflag)) ) {
 6035: 
 6036: 	    if (($domfilter eq '') ||
 6037: 		(&host_domain($tryserver) eq $domfilter)) {
 6038:                 my $rep;
 6039:                 if (grep { $_ eq $tryserver } current_machine_ids()) {
 6040:                     $rep = LONCAPA::Lond::dump_course_id_handler(
 6041:                         join(":", (&host_domain($tryserver), $sincefilter, 
 6042:                                 &escape($descfilter), &escape($instcodefilter), 
 6043:                                 &escape($ownerfilter), &escape($coursefilter),
 6044:                                 &escape($typefilter), &escape($regexp_ok), 
 6045:                                 $as_hash, &escape($selfenrollonly), 
 6046:                                 &escape($catfilter), $showhidden, $caller, 
 6047:                                 &escape($cloner), &escape($cc_clone), $cloneonly, 
 6048:                                 &escape($createdbefore), &escape($createdafter), 
 6049:                                 &escape($creationcontext),$domcloner,$hasuniquecode,
 6050:                                 $reqcrsdom,&escape($reqinstcode))));
 6051:                 } else {
 6052:                     $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
 6053:                              $sincefilter.':'.&escape($descfilter).':'.
 6054:                              &escape($instcodefilter).':'.&escape($ownerfilter).
 6055:                              ':'.&escape($coursefilter).':'.&escape($typefilter).
 6056:                              ':'.&escape($regexp_ok).':'.$as_hash.':'.
 6057:                              &escape($selfenrollonly).':'.&escape($catfilter).':'.
 6058:                              $showhidden.':'.$caller.':'.&escape($cloner).':'.
 6059:                              &escape($cc_clone).':'.$cloneonly.':'.
 6060:                              &escape($createdbefore).':'.&escape($createdafter).':'.
 6061:                              &escape($creationcontext).':'.$domcloner.':'.$hasuniquecode.
 6062:                              ':'.$reqcrsdom.':'.&escape($reqinstcode),$tryserver);
 6063:                 }
 6064:                      
 6065:                 my @pairs=split(/\&/,$rep);
 6066:                 foreach my $item (@pairs) {
 6067:                     my ($key,$value)=split(/\=/,$item,2);
 6068:                     $key = &unescape($key);
 6069:                     next if ($key =~ /^error: 2 /);
 6070:                     my $result = &thaw_unescape($value);
 6071:                     if (ref($result) eq 'HASH') {
 6072:                         $returnhash{$key}=$result;
 6073:                     } else {
 6074:                         my @responses = split(/:/,$value);
 6075:                         my @items = ('description','inst_code','owner','type');
 6076:                         for (my $i=0; $i<@responses; $i++) {
 6077:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
 6078:                         }
 6079:                     }
 6080:                 }
 6081:             }
 6082:         }
 6083:     }
 6084:     return %returnhash;
 6085: }
 6086: 
 6087: sub courselastaccess {
 6088:     my ($cdom,$cnum,$hostidref) = @_;
 6089:     my %returnhash;
 6090:     if ($cdom && $cnum) {
 6091:         my $chome = &homeserver($cnum,$cdom);
 6092:         if ($chome ne 'no_host') {
 6093:             my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
 6094:             &extract_lastaccess(\%returnhash,$rep);
 6095:         }
 6096:     } else {
 6097:         if (!$cdom) { $cdom=''; }
 6098:         my %libserv = &all_library();
 6099:         foreach my $tryserver (keys(%libserv)) {
 6100:             if (ref($hostidref) eq 'ARRAY') {
 6101:                 next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
 6102:             } 
 6103:             if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
 6104:                 my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
 6105:                 &extract_lastaccess(\%returnhash,$rep);
 6106:             }
 6107:         }
 6108:     }
 6109:     return %returnhash;
 6110: }
 6111: 
 6112: sub extract_lastaccess {
 6113:     my ($returnhash,$rep) = @_;
 6114:     if (ref($returnhash) eq 'HASH') {
 6115:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' || 
 6116:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
 6117:                  $rep eq '') {
 6118:             my @pairs=split(/\&/,$rep);
 6119:             foreach my $item (@pairs) {
 6120:                 my ($key,$value)=split(/\=/,$item,2);
 6121:                 $key = &unescape($key);
 6122:                 next if ($key =~ /^error: 2 /);
 6123:                 $returnhash->{$key} = &thaw_unescape($value);
 6124:             }
 6125:         }
 6126:     }
 6127:     return;
 6128: }
 6129: 
 6130: # ---------------------------------------------------------- DC e-mail
 6131: 
 6132: sub dcmailput {
 6133:     my ($domain,$msgid,$message,$server)=@_;
 6134:     my $status = &critical(
 6135:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
 6136:        &escape($message),$server);
 6137:     return $status;
 6138: }
 6139: 
 6140: sub dcmaildump {
 6141:     my ($dom,$startdate,$enddate,$senders) = @_;
 6142:     my %returnhash=();
 6143: 
 6144:     if (defined(&domain($dom,'primary'))) {
 6145:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
 6146:                                                          &escape($enddate).':';
 6147: 	my @esc_senders=map { &escape($_)} @$senders;
 6148: 	$cmd.=&escape(join('&',@esc_senders));
 6149: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
 6150:             my ($key,$value) = split(/\=/,$line,2);
 6151:             if (($key) && ($value)) {
 6152:                 $returnhash{&unescape($key)} = &unescape($value);
 6153:             }
 6154:         }
 6155:     }
 6156:     return %returnhash;
 6157: }
 6158: # ---------------------------------------------------------- Domain roles
 6159: 
 6160: sub get_domain_roles {
 6161:     my ($dom,$roles,$startdate,$enddate)=@_;
 6162:     if ((!defined($startdate)) || ($startdate eq '')) {
 6163:         $startdate = '.';
 6164:     }
 6165:     if ((!defined($enddate)) || ($enddate eq '')) {
 6166:         $enddate = '.';
 6167:     }
 6168:     my $rolelist;
 6169:     if (ref($roles) eq 'ARRAY') {
 6170:         $rolelist = join('&',@{$roles});
 6171:     }
 6172:     my %personnel = ();
 6173: 
 6174:     my %servers = &get_servers($dom,'library');
 6175:     foreach my $tryserver (keys(%servers)) {
 6176: 	%{$personnel{$tryserver}}=();
 6177: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
 6178: 					    &escape($startdate).':'.
 6179: 					    &escape($enddate).':'.
 6180: 					    &escape($rolelist), $tryserver))) {
 6181: 	    my ($key,$value) = split(/\=/,$line,2);
 6182: 	    if (($key) && ($value)) {
 6183: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
 6184: 	    }
 6185: 	}
 6186:     }
 6187:     return %personnel;
 6188: }
 6189: 
 6190: sub get_active_domroles {
 6191:     my ($dom,$roles) = @_;
 6192:     return () unless (ref($roles) eq 'ARRAY');
 6193:     my $now = time;
 6194:     my %dompersonnel = &get_domain_roles($dom,$roles,$now,$now);
 6195:     my %domroles;
 6196:     foreach my $server (keys(%dompersonnel)) {
 6197:         foreach my $user (sort(keys(%{$dompersonnel{$server}}))) {
 6198:             my ($trole,$uname,$udom,$runame,$rudom,$rsec) = split(/:/,$user);
 6199:             $domroles{$uname.':'.$udom} = $dompersonnel{$server}{$user};
 6200:         }
 6201:     }
 6202:     return %domroles;
 6203: }
 6204: 
 6205: # ----------------------------------------------------------- Interval timing 
 6206: 
 6207: {
 6208: # Caches needed for speedup of navmaps
 6209: # We don't want to cache this for very long at all (5 seconds at most)
 6210: # 
 6211: # The user for whom we cache
 6212: my $cachedkey='';
 6213: # The cached times for this user
 6214: my %cachedtimes=();
 6215: # When this was last done
 6216: my $cachedtime='';
 6217: 
 6218: sub load_all_first_access {
 6219:     my ($uname,$udom,$ignorecache)=@_;
 6220:     if (($cachedkey eq $uname.':'.$udom) &&
 6221:         (abs($cachedtime-time)<5) && (!$env{'form.markaccess'}) &&
 6222:         (!$ignorecache)) {
 6223:         return;
 6224:     }
 6225:     $cachedtime=time;
 6226:     $cachedkey=$uname.':'.$udom;
 6227:     %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
 6228: }
 6229: 
 6230: sub get_first_access {
 6231:     my ($type,$argsymb,$argmap,$ignorecache)=@_;
 6232:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 6233:     if ($argsymb) { $symb=$argsymb; }
 6234:     my ($map,$id,$res)=&decode_symb($symb);
 6235:     if ($argmap) { $map = $argmap; }
 6236:     if ($type eq 'course') {
 6237: 	$res='course';
 6238:     } elsif ($type eq 'map') {
 6239: 	$res=&symbread($map);
 6240:     } else {
 6241: 	$res=$symb;
 6242:     }
 6243:     &load_all_first_access($uname,$udom,$ignorecache);
 6244:     return $cachedtimes{"$courseid\0$res"};
 6245: }
 6246: 
 6247: sub set_first_access {
 6248:     my ($type,$interval)=@_;
 6249:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 6250:     my ($map,$id,$res)=&decode_symb($symb);
 6251:     if ($type eq 'course') {
 6252: 	$res='course';
 6253:     } elsif ($type eq 'map') {
 6254: 	$res=&symbread($map);
 6255:     } else {
 6256: 	$res=$symb;
 6257:     }
 6258:     $cachedkey='';
 6259:     my $firstaccess=&get_first_access($type,$symb,$map);
 6260:     if ($firstaccess) {
 6261:         &logthis("First access time already set ($firstaccess) when attempting ".
 6262:                  "to set new value (type: $type, extent: $res) for $uname:$udom ".
 6263:                  "in $courseid");
 6264:         return 'already_set';
 6265:     } else {
 6266:         my $start = time;
 6267: 	my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
 6268:                           $udom,$uname);
 6269:         if ($putres eq 'ok') {
 6270:             &put('timerinterval',{"$courseid\0$res"=>$interval},
 6271:                  $udom,$uname); 
 6272:             &appenv(
 6273:                      {
 6274:                         'course.'.$courseid.'.firstaccess.'.$res   => $start,
 6275:                         'course.'.$courseid.'.timerinterval.'.$res => $interval,
 6276:                      }
 6277:                   );
 6278:             if (($cachedtime) && (abs($start-$cachedtime) < 5)) {
 6279:                 $cachedtimes{"$courseid\0$res"} = $start;
 6280:             }
 6281:         } elsif ($putres ne 'refused') {
 6282:             &logthis("Result: $putres when attempting to set first access time ".
 6283:                      "(type: $type, extent: $res) for $uname:$udom in $courseid");
 6284:         }
 6285:         return $putres;
 6286:     }
 6287:     return 'already_set';
 6288: }
 6289: }
 6290: 
 6291: # --------------------------------------------- Set Expire Date for Spreadsheet
 6292: 
 6293: sub expirespread {
 6294:     my ($uname,$udom,$stype,$usymb)=@_;
 6295:     my $cid=$env{'request.course.id'}; 
 6296:     if ($cid) {
 6297:        my $now=time;
 6298:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
 6299:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
 6300:                             $env{'course.'.$cid.'.num'}.
 6301: 	        	    ':nohist_expirationdates:'.
 6302:                             &escape($key).'='.$now,
 6303:                             $env{'course.'.$cid.'.home'})
 6304:     }
 6305:     return 'ok';
 6306: }
 6307: 
 6308: # ----------------------------------------------------- Devalidate Spreadsheets
 6309: 
 6310: sub devalidate {
 6311:     my ($symb,$uname,$udom)=@_;
 6312:     my $cid=$env{'request.course.id'}; 
 6313:     if ($cid) {
 6314:         # delete the stored spreadsheets for
 6315:         # - the student level sheet of this user in course's homespace
 6316:         # - the assessment level sheet for this resource 
 6317:         #   for this user in user's homespace
 6318: 	# - current conditional state info
 6319: 	my $key=$uname.':'.$udom.':';
 6320:         my $status=
 6321: 	    &del('nohist_calculatedsheets',
 6322: 		 [$key.'studentcalc:'],
 6323: 		 $env{'course.'.$cid.'.domain'},
 6324: 		 $env{'course.'.$cid.'.num'})
 6325: 		.' '.
 6326: 	    &del('nohist_calculatedsheets_'.$cid,
 6327: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
 6328:         unless ($status eq 'ok ok') {
 6329:            &logthis('Could not devalidate spreadsheet '.
 6330:                     $uname.' at '.$udom.' for '.
 6331: 		    $symb.': '.$status);
 6332:         }
 6333: 	&delenv('user.state.'.$cid);
 6334:     }
 6335: }
 6336: 
 6337: sub get_scalar {
 6338:     my ($string,$end) = @_;
 6339:     my $value;
 6340:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
 6341: 	$value = $1;
 6342:     } elsif ($$string =~ s/^([^&]*?)&//) {
 6343: 	$value = $1;
 6344:     }
 6345:     return &unescape($value);
 6346: }
 6347: 
 6348: sub array2str {
 6349:   my (@array) = @_;
 6350:   my $result=&arrayref2str(\@array);
 6351:   $result=~s/^__ARRAY_REF__//;
 6352:   $result=~s/__END_ARRAY_REF__$//;
 6353:   return $result;
 6354: }
 6355: 
 6356: sub arrayref2str {
 6357:   my ($arrayref) = @_;
 6358:   my $result='__ARRAY_REF__';
 6359:   foreach my $elem (@$arrayref) {
 6360:     if(ref($elem) eq 'ARRAY') {
 6361:       $result.=&arrayref2str($elem).'&';
 6362:     } elsif(ref($elem) eq 'HASH') {
 6363:       $result.=&hashref2str($elem).'&';
 6364:     } elsif(ref($elem)) {
 6365:       #print("Got a ref of ".(ref($elem))." skipping.");
 6366:     } else {
 6367:       $result.=&escape($elem).'&';
 6368:     }
 6369:   }
 6370:   $result=~s/\&$//;
 6371:   $result .= '__END_ARRAY_REF__';
 6372:   return $result;
 6373: }
 6374: 
 6375: sub hash2str {
 6376:   my (%hash) = @_;
 6377:   my $result=&hashref2str(\%hash);
 6378:   $result=~s/^__HASH_REF__//;
 6379:   $result=~s/__END_HASH_REF__$//;
 6380:   return $result;
 6381: }
 6382: 
 6383: sub hashref2str {
 6384:   my ($hashref)=@_;
 6385:   my $result='__HASH_REF__';
 6386:   foreach my $key (sort(keys(%$hashref))) {
 6387:     if (ref($key) eq 'ARRAY') {
 6388:       $result.=&arrayref2str($key).'=';
 6389:     } elsif (ref($key) eq 'HASH') {
 6390:       $result.=&hashref2str($key).'=';
 6391:     } elsif (ref($key)) {
 6392:       $result.='=';
 6393:       #print("Got a ref of ".(ref($key))." skipping.");
 6394:     } else {
 6395: 	if (defined($key)) {$result.=&escape($key).'=';} else { last; }
 6396:     }
 6397: 
 6398:     if(ref($hashref->{$key}) eq 'ARRAY') {
 6399:       $result.=&arrayref2str($hashref->{$key}).'&';
 6400:     } elsif(ref($hashref->{$key}) eq 'HASH') {
 6401:       $result.=&hashref2str($hashref->{$key}).'&';
 6402:     } elsif(ref($hashref->{$key})) {
 6403:        $result.='&';
 6404:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
 6405:     } else {
 6406:       $result.=&escape($hashref->{$key}).'&';
 6407:     }
 6408:   }
 6409:   $result=~s/\&$//;
 6410:   $result .= '__END_HASH_REF__';
 6411:   return $result;
 6412: }
 6413: 
 6414: sub str2hash {
 6415:     my ($string)=@_;
 6416:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
 6417:     return %$hash;
 6418: }
 6419: 
 6420: sub str2hashref {
 6421:   my ($string) = @_;
 6422: 
 6423:   my %hash;
 6424: 
 6425:   if($string !~ /^__HASH_REF__/) {
 6426:       if (! ($string eq '' || !defined($string))) {
 6427: 	  $hash{'error'}='Not hash reference';
 6428:       }
 6429:       return (\%hash, $string);
 6430:   }
 6431: 
 6432:   $string =~ s/^__HASH_REF__//;
 6433: 
 6434:   while($string !~ /^__END_HASH_REF__/) {
 6435:       #key
 6436:       my $key='';
 6437:       if($string =~ /^__HASH_REF__/) {
 6438:           ($key, $string)=&str2hashref($string);
 6439:           if(defined($key->{'error'})) {
 6440:               $hash{'error'}='Bad data';
 6441:               return (\%hash, $string);
 6442:           }
 6443:       } elsif($string =~ /^__ARRAY_REF__/) {
 6444:           ($key, $string)=&str2arrayref($string);
 6445:           if($key->[0] eq 'Array reference error') {
 6446:               $hash{'error'}='Bad data';
 6447:               return (\%hash, $string);
 6448:           }
 6449:       } else {
 6450:           $string =~ s/^(.*?)=//;
 6451: 	  $key=&unescape($1);
 6452:       }
 6453:       $string =~ s/^=//;
 6454: 
 6455:       #value
 6456:       my $value='';
 6457:       if($string =~ /^__HASH_REF__/) {
 6458:           ($value, $string)=&str2hashref($string);
 6459:           if(defined($value->{'error'})) {
 6460:               $hash{'error'}='Bad data';
 6461:               return (\%hash, $string);
 6462:           }
 6463:       } elsif($string =~ /^__ARRAY_REF__/) {
 6464:           ($value, $string)=&str2arrayref($string);
 6465:           if($value->[0] eq 'Array reference error') {
 6466:               $hash{'error'}='Bad data';
 6467:               return (\%hash, $string);
 6468:           }
 6469:       } else {
 6470: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
 6471:       }
 6472:       $string =~ s/^&//;
 6473: 
 6474:       $hash{$key}=$value;
 6475:   }
 6476: 
 6477:   $string =~ s/^__END_HASH_REF__//;
 6478: 
 6479:   return (\%hash, $string);
 6480: }
 6481: 
 6482: sub str2array {
 6483:     my ($string)=@_;
 6484:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
 6485:     return @$array;
 6486: }
 6487: 
 6488: sub str2arrayref {
 6489:   my ($string) = @_;
 6490:   my @array;
 6491: 
 6492:   if($string !~ /^__ARRAY_REF__/) {
 6493:       if (! ($string eq '' || !defined($string))) {
 6494: 	  $array[0]='Array reference error';
 6495:       }
 6496:       return (\@array, $string);
 6497:   }
 6498: 
 6499:   $string =~ s/^__ARRAY_REF__//;
 6500: 
 6501:   while($string !~ /^__END_ARRAY_REF__/) {
 6502:       my $value='';
 6503:       if($string =~ /^__HASH_REF__/) {
 6504:           ($value, $string)=&str2hashref($string);
 6505:           if(defined($value->{'error'})) {
 6506:               $array[0] ='Array reference error';
 6507:               return (\@array, $string);
 6508:           }
 6509:       } elsif($string =~ /^__ARRAY_REF__/) {
 6510:           ($value, $string)=&str2arrayref($string);
 6511:           if($value->[0] eq 'Array reference error') {
 6512:               $array[0] ='Array reference error';
 6513:               return (\@array, $string);
 6514:           }
 6515:       } else {
 6516: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
 6517:       }
 6518:       $string =~ s/^&//;
 6519: 
 6520:       push(@array, $value);
 6521:   }
 6522: 
 6523:   $string =~ s/^__END_ARRAY_REF__//;
 6524: 
 6525:   return (\@array, $string);
 6526: }
 6527: 
 6528: # -------------------------------------------------------------------Temp Store
 6529: 
 6530: sub tmpreset {
 6531:   my ($symb,$namespace,$domain,$stuname) = @_;
 6532:   if (!$symb) {
 6533:     $symb=&symbread();
 6534:     if (!$symb) { $symb= $env{'request.url'}; }
 6535:   }
 6536:   $symb=escape($symb);
 6537: 
 6538:   if (!$namespace) { $namespace=$env{'request.state'}; }
 6539:   $namespace=~s/\//\_/g;
 6540:   $namespace=~s/\W//g;
 6541: 
 6542:   if (!$domain) { $domain=$env{'user.domain'}; }
 6543:   if (!$stuname) { $stuname=$env{'user.name'}; }
 6544:   if ($domain eq 'public' && $stuname eq 'public') {
 6545:       $stuname=&get_requestor_ip();
 6546:   }
 6547:   my $path=LONCAPA::tempdir();
 6548:   my %hash;
 6549:   if (tie(%hash,'GDBM_File',
 6550: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 6551: 	  &GDBM_WRCREAT(),0640)) {
 6552:     foreach my $key (keys(%hash)) {
 6553:       if ($key=~ /:$symb/) {
 6554: 	delete($hash{$key});
 6555:       }
 6556:     }
 6557:   }
 6558: }
 6559: 
 6560: sub tmpstore {
 6561:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 6562: 
 6563:   if (!$symb) {
 6564:     $symb=&symbread();
 6565:     if (!$symb) { $symb= $env{'request.url'}; }
 6566:   }
 6567:   $symb=escape($symb);
 6568: 
 6569:   if (!$namespace) {
 6570:     # I don't think we would ever want to store this for a course.
 6571:     # it seems this will only be used if we don't have a course.
 6572:     #$namespace=$env{'request.course.id'};
 6573:     #if (!$namespace) {
 6574:       $namespace=$env{'request.state'};
 6575:     #}
 6576:   }
 6577:   $namespace=~s/\//\_/g;
 6578:   $namespace=~s/\W//g;
 6579:   if (!$domain) { $domain=$env{'user.domain'}; }
 6580:   if (!$stuname) { $stuname=$env{'user.name'}; }
 6581:   if ($domain eq 'public' && $stuname eq 'public') {
 6582:       $stuname=&get_requestor_ip();
 6583:   }
 6584:   my $now=time;
 6585:   my %hash;
 6586:   my $path=LONCAPA::tempdir();
 6587:   if (tie(%hash,'GDBM_File',
 6588: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 6589: 	  &GDBM_WRCREAT(),0640)) {
 6590:     $hash{"version:$symb"}++;
 6591:     my $version=$hash{"version:$symb"};
 6592:     my $allkeys=''; 
 6593:     foreach my $key (keys(%$storehash)) {
 6594:       $allkeys.=$key.':';
 6595:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
 6596:     }
 6597:     $hash{"$version:$symb:timestamp"}=$now;
 6598:     $allkeys.='timestamp';
 6599:     $hash{"$version:keys:$symb"}=$allkeys;
 6600:     if (untie(%hash)) {
 6601:       return 'ok';
 6602:     } else {
 6603:       return "error:$!";
 6604:     }
 6605:   } else {
 6606:     return "error:$!";
 6607:   }
 6608: }
 6609: 
 6610: # -----------------------------------------------------------------Temp Restore
 6611: 
 6612: sub tmprestore {
 6613:   my ($symb,$namespace,$domain,$stuname) = @_;
 6614: 
 6615:   if (!$symb) {
 6616:     $symb=&symbread();
 6617:     if (!$symb) { $symb= $env{'request.url'}; }
 6618:   }
 6619:   $symb=escape($symb);
 6620: 
 6621:   if (!$namespace) { $namespace=$env{'request.state'}; }
 6622: 
 6623:   if (!$domain) { $domain=$env{'user.domain'}; }
 6624:   if (!$stuname) { $stuname=$env{'user.name'}; }
 6625:   if ($domain eq 'public' && $stuname eq 'public') {
 6626:       $stuname=&get_requestor_ip();
 6627:   }
 6628:   my %returnhash;
 6629:   $namespace=~s/\//\_/g;
 6630:   $namespace=~s/\W//g;
 6631:   my %hash;
 6632:   my $path=LONCAPA::tempdir();
 6633:   if (tie(%hash,'GDBM_File',
 6634: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 6635: 	  &GDBM_READER(),0640)) {
 6636:     my $version=$hash{"version:$symb"};
 6637:     $returnhash{'version'}=$version;
 6638:     my $scope;
 6639:     for ($scope=1;$scope<=$version;$scope++) {
 6640:       my $vkeys=$hash{"$scope:keys:$symb"};
 6641:       my @keys=split(/:/,$vkeys);
 6642:       my $key;
 6643:       $returnhash{"$scope:keys"}=$vkeys;
 6644:       foreach $key (@keys) {
 6645: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 6646: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 6647:       }
 6648:     }
 6649:     if (!(untie(%hash))) {
 6650:       return "error:$!";
 6651:     }
 6652:   } else {
 6653:     return "error:$!";
 6654:   }
 6655:   return %returnhash;
 6656: }
 6657: 
 6658: # ----------------------------------------------------------------------- Store
 6659: 
 6660: sub store {
 6661:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
 6662:     my $home='';
 6663: 
 6664:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 6665: 
 6666:     $symb=&symbclean($symb);
 6667:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 6668: 
 6669:     if (!$domain) { $domain=$env{'user.domain'}; }
 6670:     if (!$stuname) { $stuname=$env{'user.name'}; }
 6671: 
 6672:     &devalidate($symb,$stuname,$domain);
 6673: 
 6674:     $symb=escape($symb);
 6675:     if (!$namespace) { 
 6676:        unless ($namespace=$env{'request.course.id'}) { 
 6677:           return ''; 
 6678:        } 
 6679:     }
 6680:     if (!$home) { $home=$env{'user.home'}; }
 6681: 
 6682:     $$storehash{'ip'}=&get_requestor_ip();
 6683:     $$storehash{'host'}=$perlvar{'lonHostID'};
 6684: 
 6685:     my $namevalue='';
 6686:     foreach my $key (keys(%$storehash)) {
 6687:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 6688:     }
 6689:     $namevalue=~s/\&$//;
 6690:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
 6691:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
 6692: }
 6693: 
 6694: # -------------------------------------------------------------- Critical Store
 6695: 
 6696: sub cstore {
 6697:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
 6698:     my $home='';
 6699: 
 6700:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 6701: 
 6702:     $symb=&symbclean($symb);
 6703:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 6704: 
 6705:     if (!$domain) { $domain=$env{'user.domain'}; }
 6706:     if (!$stuname) { $stuname=$env{'user.name'}; }
 6707: 
 6708:     &devalidate($symb,$stuname,$domain);
 6709: 
 6710:     $symb=escape($symb);
 6711:     if (!$namespace) { 
 6712:        unless ($namespace=$env{'request.course.id'}) { 
 6713:           return ''; 
 6714:        } 
 6715:     }
 6716:     if (!$home) { $home=$env{'user.home'}; }
 6717: 
 6718:     $$storehash{'ip'}=&get_requestor_ip();
 6719:     $$storehash{'host'}=$perlvar{'lonHostID'};
 6720: 
 6721:     my $namevalue='';
 6722:     foreach my $key (keys(%$storehash)) {
 6723:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 6724:     }
 6725:     $namevalue=~s/\&$//;
 6726:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
 6727:     return critical
 6728:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
 6729: }
 6730: 
 6731: # --------------------------------------------------------------------- Restore
 6732: 
 6733: sub restore {
 6734:     my ($symb,$namespace,$domain,$stuname) = @_;
 6735:     my $home='';
 6736: 
 6737:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 6738: 
 6739:     if (!$symb) {
 6740:         return if ($namespace eq 'courserequests');
 6741:         unless ($symb=escape(&symbread())) { return ''; }
 6742:     } else {
 6743:         unless ($namespace eq 'courserequests') {
 6744:             $symb=&escape(&symbclean($symb));
 6745:         }
 6746:     }
 6747:     if (!$namespace) { 
 6748:        unless ($namespace=$env{'request.course.id'}) { 
 6749:           return ''; 
 6750:        } 
 6751:     }
 6752:     if (!$domain) { $domain=$env{'user.domain'}; }
 6753:     if (!$stuname) { $stuname=$env{'user.name'}; }
 6754:     if (!$home) { $home=$env{'user.home'}; }
 6755:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
 6756: 
 6757:     my %returnhash=();
 6758:     foreach my $line (split(/\&/,$answer)) {
 6759: 	my ($name,$value)=split(/\=/,$line);
 6760:         $returnhash{&unescape($name)}=&thaw_unescape($value);
 6761:     }
 6762:     my $version;
 6763:     for ($version=1;$version<=$returnhash{'version'};$version++) {
 6764:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
 6765:           $returnhash{$item}=$returnhash{$version.':'.$item};
 6766:        }
 6767:     }
 6768:     return %returnhash;
 6769: }
 6770: 
 6771: # ---------------------------------------------------------- Course Description
 6772: #
 6773: #  
 6774: 
 6775: sub coursedescription {
 6776:     my ($courseid,$args)=@_;
 6777:     $courseid=~s/^\///;
 6778:     $courseid=~s/\_/\//g;
 6779:     my ($cdomain,$cnum)=split(/\//,$courseid);
 6780:     my $chome=&homeserver($cnum,$cdomain);
 6781:     my $normalid=$cdomain.'_'.$cnum;
 6782:     # need to always cache even if we get errors otherwise we keep 
 6783:     # trying and trying and trying to get the course description.
 6784:     my %envhash=();
 6785:     my %returnhash=();
 6786:     
 6787:     my $expiretime=600;
 6788:     if ($env{'request.course.id'} eq $normalid) {
 6789: 	$expiretime=120;
 6790:     }
 6791: 
 6792:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
 6793:     if (!$args->{'freshen_cache'}
 6794: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
 6795: 	foreach my $key (keys(%env)) {
 6796: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
 6797: 	    my ($setting) = $1;
 6798: 	    $returnhash{$setting} = $env{$key};
 6799: 	}
 6800: 	return %returnhash;
 6801:     }
 6802: 
 6803:     # get the data again
 6804: 
 6805:     if (!$args->{'one_time'}) {
 6806: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
 6807:     }
 6808: 
 6809:     if ($chome ne 'no_host') {
 6810:        %returnhash=&dump('environment',$cdomain,$cnum);
 6811:        if (!exists($returnhash{'con_lost'})) {
 6812: 	   my $username = $env{'user.name'}; # Defult username
 6813: 	   if(defined $args->{'user'}) {
 6814: 	       $username = $args->{'user'};
 6815: 	   }
 6816:            $returnhash{'home'}= $chome;
 6817: 	   $returnhash{'domain'} = $cdomain;
 6818: 	   $returnhash{'num'} = $cnum;
 6819:            if (!defined($returnhash{'type'})) {
 6820:                $returnhash{'type'} = 'Course';
 6821:            }
 6822:            while (my ($name,$value) = each %returnhash) {
 6823:                $envhash{'course.'.$normalid.'.'.$name}=$value;
 6824:            }
 6825:            $returnhash{'url'}=&clutter($returnhash{'url'});
 6826:            $returnhash{'fn'}=LONCAPA::tempdir() .
 6827: 	       $username.'_'.$cdomain.'_'.$cnum;
 6828:            $envhash{'course.'.$normalid.'.home'}=$chome;
 6829:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
 6830:            $envhash{'course.'.$normalid.'.num'}=$cnum;
 6831:        }
 6832:     }
 6833:     if (!$args->{'one_time'}) {
 6834: 	&appenv(\%envhash);
 6835:     }
 6836:     return %returnhash;
 6837: }
 6838: 
 6839: sub update_released_required {
 6840:     my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
 6841:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
 6842:         $cid = $env{'request.course.id'};
 6843:         $cdom = $env{'course.'.$cid.'.domain'};
 6844:         $cnum = $env{'course.'.$cid.'.num'};
 6845:         $chome = $env{'course.'.$cid.'.home'};
 6846:     }
 6847:     if ($needsrelease) {
 6848:         my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
 6849:         my $needsupdate;
 6850:         if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
 6851:             $needsupdate = 1;
 6852:         } else {
 6853:             my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
 6854:             my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
 6855:             if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
 6856:                 $needsupdate = 1;
 6857:             }
 6858:         }
 6859:         if ($needsupdate) {
 6860:             my %needshash = (
 6861:                              'internal.releaserequired' => $needsrelease,
 6862:                             );
 6863:             my $putresult = &put('environment',\%needshash,$cdom,$cnum);
 6864:             if ($putresult eq 'ok') {
 6865:                 &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
 6866:                 my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
 6867:                 if (ref($crsinfo{$cid}) eq 'HASH') {
 6868:                     $crsinfo{$cid}{'releaserequired'} = $needsrelease;
 6869:                     &courseidput($cdom,\%crsinfo,$chome,'notime');
 6870:                 }
 6871:             }
 6872:         }
 6873:     }
 6874:     return;
 6875: }
 6876: 
 6877: # -------------------------------------------------See if a user is privileged
 6878: 
 6879: sub privileged {
 6880:     my ($username,$domain,$possdomains,$possroles)=@_;
 6881:     my $now = time;
 6882:     my $roles;
 6883:     if (ref($possroles) eq 'ARRAY') {
 6884:         $roles = $possroles; 
 6885:     } else {
 6886:         $roles = ['dc','su'];
 6887:     }
 6888:     if (ref($possdomains) eq 'ARRAY') {
 6889:         my %privileged = &privileged_by_domain($possdomains,$roles);
 6890:         foreach my $dom (@{$possdomains}) {
 6891:             if (($username =~ /^$match_username$/) && ($domain =~ /^$match_domain$/) &&
 6892:                 (ref($privileged{$dom}) eq 'HASH')) {
 6893:                 foreach my $role (@{$roles}) {
 6894:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
 6895:                         if (exists($privileged{$dom}{$role}{$username.':'.$domain})) {
 6896:                             my ($end,$start) = split(/:/,$privileged{$dom}{$role}{$username.':'.$domain});
 6897:                             return 1 unless (($end && $end < $now) ||
 6898:                                              ($start && $start > $now));
 6899:                         }
 6900:                     }
 6901:                 }
 6902:             }
 6903:         }
 6904:     } else {
 6905:         my %rolesdump = &dump("roles", $domain, $username) or return 0;
 6906:         my $now = time;
 6907: 
 6908:         for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys(%rolesdump)}) {
 6909:             my ($trole, $tend, $tstart) = split(/_/, $role);
 6910:             if (grep(/^\Q$trole\E$/,@{$roles})) {
 6911:                 return 1 unless ($tend && $tend < $now) 
 6912:                         or ($tstart && $tstart > $now);
 6913:             }
 6914:         }
 6915:     }
 6916:     return 0;
 6917: }
 6918: 
 6919: sub privileged_by_domain {
 6920:     my ($domains,$roles) = @_;
 6921:     my %privileged = ();
 6922:     my $cachetime = 60*60*24;
 6923:     my $now = time;
 6924:     unless ((ref($domains) eq 'ARRAY') && (ref($roles) eq 'ARRAY')) {
 6925:         return %privileged;
 6926:     }
 6927:     foreach my $dom (@{$domains}) {
 6928:         next if (ref($privileged{$dom}) eq 'HASH');
 6929:         my $needroles;
 6930:         foreach my $role (@{$roles}) {
 6931:             my ($result,$cached)=&is_cached_new('priv_'.$role,$dom);
 6932:             if (defined($cached)) {
 6933:                 if (ref($result) eq 'HASH') {
 6934:                     $privileged{$dom}{$role} = $result;
 6935:                 }
 6936:             } else {
 6937:                 $needroles = 1;
 6938:             }
 6939:         }
 6940:         if ($needroles) {
 6941:             my %dompersonnel = &get_domain_roles($dom,$roles);
 6942:             $privileged{$dom} = {};
 6943:             foreach my $server (keys(%dompersonnel)) {
 6944:                 if (ref($dompersonnel{$server}) eq 'HASH') {
 6945:                     foreach my $item (keys(%{$dompersonnel{$server}})) {
 6946:                         my ($trole,$uname,$udom,$rest) = split(/:/,$item,4);
 6947:                         my ($end,$start) = split(/:/,$dompersonnel{$server}{$item});
 6948:                         next if ($end && $end < $now);
 6949:                         $privileged{$dom}{$trole}{$uname.':'.$udom} = 
 6950:                             $dompersonnel{$server}{$item};
 6951:                     }
 6952:                 }
 6953:             }
 6954:             if (ref($privileged{$dom}) eq 'HASH') {
 6955:                 foreach my $role (@{$roles}) {
 6956:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
 6957:                         &do_cache_new('priv_'.$role,$dom,$privileged{$dom}{$role},$cachetime);
 6958:                     } else {
 6959:                         my %hash = ();
 6960:                         &do_cache_new('priv_'.$role,$dom,\%hash,$cachetime);
 6961:                     }
 6962:                 }
 6963:             }
 6964:         }
 6965:     }
 6966:     return %privileged;
 6967: }
 6968: 
 6969: # -------------------------------------------------------- Get user privileges
 6970: 
 6971: sub rolesinit {
 6972:     my ($domain, $username) = @_;
 6973:     my %userroles = ('user.login.time' => time);
 6974:     my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
 6975: 
 6976:     # firstaccess and timerinterval are related to timed maps/resources. 
 6977:     # also, blocking can be triggered by an activating timer
 6978:     # it's saved in the user's %env.
 6979:     my %firstaccess = &dump('firstaccesstimes', $domain, $username);
 6980:     my %timerinterval = &dump('timerinterval', $domain, $username);
 6981:     my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
 6982:         %timerintchk, %timerintenv, %coauthorenv);
 6983: 
 6984:     foreach my $key (keys(%firstaccess)) {
 6985:         my ($cid, $rest) = split(/\0/, $key);
 6986:         $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
 6987:     }
 6988: 
 6989:     foreach my $key (keys(%timerinterval)) {
 6990:         my ($cid,$rest) = split(/\0/,$key);
 6991:         $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
 6992:     }
 6993: 
 6994:     my %allroles=();
 6995:     my %allgroups=();
 6996:     my %gotcoauconfig=();
 6997: 
 6998:     for my $area (grep { ! /^rolesdef_/ } keys(%rolesdump)) {
 6999:         my $role = $rolesdump{$area};
 7000:         $area =~ s/\_\w\w$//;
 7001: 
 7002:         my ($trole, $tend, $tstart, $group_privs);
 7003: 
 7004:         if ($role =~ /^cr/) {
 7005:         # Custom role, defined by a user 
 7006:         # e.g., user.role.cr/msu/smith/mynewrole
 7007:             if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
 7008:                 $trole = $1;
 7009:                 ($tend, $tstart) = split('_', $2);
 7010:             } else {
 7011:                 $trole = $role;
 7012:             }
 7013:         } elsif ($role =~ m|^gr/|) {
 7014:         # Role of member in a group, defined within a course/community
 7015:         # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
 7016:             ($trole, $tend, $tstart) = split(/_/, $role);
 7017:             next if $tstart eq '-1';
 7018:             ($trole, $group_privs) = split(/\//, $trole);
 7019:             $group_privs = &unescape($group_privs);
 7020:         } else {
 7021:         # Just a normal role, defined in roles.tab
 7022:             ($trole, $tend, $tstart) = split(/_/,$role);
 7023:         }
 7024: 
 7025:         my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
 7026:                  $username);
 7027:         @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
 7028: 
 7029:         # role expired or not available yet?
 7030:         $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or 
 7031:             ($tstart != 0 && $tstart > $userroles{'user.login.time'});
 7032: 
 7033:         next if $area eq '' or $trole eq '';
 7034: 
 7035:         my $spec = "$trole.$area";
 7036:         my ($tdummy, $tdomain, $trest) = split(/\//, $area);
 7037: 
 7038:         if ($trole =~ /^cr\//) {
 7039:         # Custom role, defined by a user
 7040:             &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
 7041:         } elsif ($trole eq 'gr') {
 7042:         # Role of a member in a group, defined within a course/community
 7043:             &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
 7044:             next;
 7045:         } else {
 7046:         # Normal role, defined in roles.tab
 7047:             &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
 7048:             if (($trole eq 'ca') || ($trole eq 'aa')) {
 7049:                 (undef,my ($audom,$auname)) = split(/\//,$area);
 7050:                 unless ($gotcoauconfig{$area}) {
 7051:                     my @ca_settings = ('authoreditors','coauthorlist','coauthoroptin');
 7052:                     my %info = &userenvironment($audom,$auname,@ca_settings);
 7053:                     $gotcoauconfig{$area} = 1;
 7054:                     foreach my $item (@ca_settings) {
 7055:                         if (exists($info{$item})) {
 7056:                             $coauthorenv{"environment.internal.$item.$area"} = $info{$item};
 7057:                         }
 7058:                     }
 7059:                 }
 7060:             }
 7061:         }
 7062: 
 7063:         my $cid = $tdomain.'_'.$trest;
 7064:         unless ($firstaccchk{$cid}) {
 7065:             if (ref($coursetimerstarts{$cid}) eq 'HASH') {
 7066:                 foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
 7067:                     $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} = 
 7068:                         $coursetimerstarts{$cid}{$item}; 
 7069:                 }
 7070:             }
 7071:             $firstaccchk{$cid} = 1;
 7072:         }
 7073:         unless ($timerintchk{$cid}) {
 7074:             if (ref($coursetimerintervals{$cid}) eq 'HASH') {
 7075:                 foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
 7076:                     $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
 7077:                        $coursetimerintervals{$cid}{$item};
 7078:                 }
 7079:             }
 7080:             $timerintchk{$cid} = 1;
 7081:         }
 7082:     }
 7083: 
 7084:     @userroles{'user.author','user.adv','user.rar'} = &set_userprivs(\%userroles,
 7085:                                                           \%allroles, \%allgroups);
 7086:     $env{'user.adv'} = $userroles{'user.adv'};
 7087:     $env{'user.rar'} = $userroles{'user.rar'};
 7088: 
 7089:     return (\%userroles,\%firstaccenv,\%timerintenv,\%coauthorenv);
 7090: }
 7091: 
 7092: sub set_arearole {
 7093:     my ($trole,$area,$tstart,$tend,$domain,$username,$nolog) = @_;
 7094:     unless ($nolog) {
 7095: # log the associated role with the area
 7096:         &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
 7097:     }
 7098:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
 7099: }
 7100: 
 7101: sub custom_roleprivs {
 7102:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
 7103:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
 7104:     my $homsvr = &homeserver($rauthor,$rdomain);
 7105:     if (&hostname($homsvr) ne '') {
 7106:         my ($rdummy,$roledef)=
 7107:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
 7108:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
 7109:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
 7110:             if (defined($syspriv)) {
 7111:                 if ($trest =~ /^$match_community$/) {
 7112:                     $syspriv =~ s/bre\&S//; 
 7113:                 }
 7114:                 $$allroles{'cm./'}.=':'.$syspriv;
 7115:                 $$allroles{$spec.'./'}.=':'.$syspriv;
 7116:             }
 7117:             if ($tdomain ne '') {
 7118:                 if (defined($dompriv)) {
 7119:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
 7120:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
 7121:                 }
 7122:                 if (($trest ne '') && (defined($coursepriv))) {
 7123:                     if ($trole =~ m{^cr/$tdomain/$tdomain\Q-domainconfig\E/([^/]+)$}) {
 7124:                         my $rolename = $1;
 7125:                         $coursepriv = &course_adhocrole_privs($rolename,$tdomain,$trest,$coursepriv);
 7126:                     }
 7127:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
 7128:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
 7129:                 }
 7130:             }
 7131:         }
 7132:     }
 7133: }
 7134: 
 7135: sub course_adhocrole_privs {
 7136:     my ($rolename,$cdom,$cnum,$coursepriv) = @_;
 7137:     my %overrides = &get('environment',["internal.adhocpriv.$rolename"],$cdom,$cnum);
 7138:     if ($overrides{"internal.adhocpriv.$rolename"}) {
 7139:         my (%currprivs,%storeprivs);
 7140:         foreach my $item (split(/:/,$coursepriv)) {
 7141:             my ($priv,$restrict) = split(/\&/,$item);
 7142:             $currprivs{$priv} = $restrict;
 7143:         }
 7144:         my (%possadd,%possremove,%full);
 7145:         foreach my $item (split(/\:/,$Apache::lonnet::pr{'cr:c'})) {
 7146:             my ($priv,$restrict)=split(/\&/,$item);
 7147:             $full{$priv} = $restrict;
 7148:         }
 7149:         foreach my $item (split(/,/,$overrides{"internal.adhocpriv.$rolename"})) {
 7150:             next if ($item eq '');
 7151:             my ($rule,$rest) = split(/=/,$item);
 7152:             next unless (($rule eq 'off') || ($rule eq 'on'));
 7153:             foreach my $priv (split(/:/,$rest)) {
 7154:                 if ($priv ne '') {
 7155:                     if ($rule eq 'off') {
 7156:                         $possremove{$priv} = 1;
 7157:                     } else {
 7158:                         $possadd{$priv} = 1;
 7159:                     }
 7160:                 }
 7161:             }
 7162:         }
 7163:         foreach my $priv (sort(keys(%full))) {
 7164:             if (exists($currprivs{$priv})) {
 7165:                 unless (exists($possremove{$priv})) {
 7166:                     $storeprivs{$priv} = $currprivs{$priv};
 7167:                 }
 7168:             } elsif (exists($possadd{$priv})) {
 7169:                 $storeprivs{$priv} = $full{$priv};
 7170:             }
 7171:         }
 7172:         $coursepriv = ':'.join(':',map { $_.'&'.$storeprivs{$_}; } sort(keys(%storeprivs)));
 7173:     }
 7174:     return $coursepriv;
 7175: }
 7176: 
 7177: sub group_roleprivs {
 7178:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
 7179:     my $access = 1;
 7180:     my $now = time;
 7181:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
 7182:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
 7183:     if ($access) {
 7184:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
 7185:         $$allgroups{$course}{$group} .=':'.$group_privs;
 7186:     }
 7187: }
 7188: 
 7189: sub standard_roleprivs {
 7190:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
 7191:     if (defined($pr{$trole.':s'})) {
 7192:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
 7193:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
 7194:     }
 7195:     if ($tdomain ne '') {
 7196:         if (defined($pr{$trole.':d'})) {
 7197:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 7198:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 7199:         }
 7200:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
 7201:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
 7202:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
 7203:         }
 7204:     }
 7205: }
 7206: 
 7207: sub set_userprivs {
 7208:     my ($userroles,$allroles,$allgroups,$groups_roles) = @_; 
 7209:     my $author=0;
 7210:     my $adv=0;
 7211:     my $rar=0;
 7212:     my %grouproles = ();
 7213:     if (keys(%{$allgroups}) > 0) {
 7214:         my @groupkeys; 
 7215:         foreach my $role (keys(%{$allroles})) {
 7216:             push(@groupkeys,$role);
 7217:         }
 7218:         if (ref($groups_roles) eq 'HASH') {
 7219:             foreach my $key (keys(%{$groups_roles})) {
 7220:                 unless (grep(/^\Q$key\E$/,@groupkeys)) {
 7221:                     push(@groupkeys,$key);
 7222:                 }
 7223:             }
 7224:         }
 7225:         if (@groupkeys > 0) {
 7226:             foreach my $role (@groupkeys) {
 7227:                 my ($trole,$area,$sec,$extendedarea);
 7228:                 if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
 7229:                     $trole = $1;
 7230:                     $area = $2;
 7231:                     $sec = $3;
 7232:                     $extendedarea = $area.$sec;
 7233:                     if (exists($$allgroups{$area})) {
 7234:                         foreach my $group (keys(%{$$allgroups{$area}})) {
 7235:                             my $spec = $trole.'.'.$extendedarea;
 7236:                             $grouproles{$spec.'.'.$area.'/'.$group} = 
 7237:                                                 $$allgroups{$area}{$group};
 7238:                         }
 7239:                     }
 7240:                 }
 7241:             }
 7242:         }
 7243:     }
 7244:     foreach my $group (keys(%grouproles)) {
 7245:         $$allroles{$group} = $grouproles{$group};
 7246:     }
 7247:     foreach my $role (keys(%{$allroles})) {
 7248:         my %thesepriv;
 7249:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
 7250:         foreach my $item (split(/:/,$$allroles{$role})) {
 7251:             if ($item ne '') {
 7252:                 my ($privilege,$restrictions)=split(/&/,$item);
 7253:                 if ($restrictions eq '') {
 7254:                     $thesepriv{$privilege}='F';
 7255:                 } elsif ($thesepriv{$privilege} ne 'F') {
 7256:                     $thesepriv{$privilege}.=$restrictions;
 7257:                 }
 7258:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
 7259:                 if ($thesepriv{'rar'} eq 'F') { $rar=1; }
 7260:             }
 7261:         }
 7262:         my $thesestr='';
 7263:         foreach my $priv (sort(keys(%thesepriv))) {
 7264: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
 7265: 	}
 7266:         $userroles->{'user.priv.'.$role} = $thesestr;
 7267:     }
 7268:     return ($author,$adv,$rar);
 7269: }
 7270: 
 7271: sub role_status {
 7272:     my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
 7273:     if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
 7274:         my ($one,$two) = split(m{\./},$rolekey,2);
 7275:         (undef,undef,$$role) = split(/\./,$one,3);
 7276:         unless (!defined($$role) || $$role eq '') {
 7277:             $$where = '/'.$two;
 7278:             $$trolecode=$$role.'.'.$$where;
 7279:             ($$tstart,$$tend)=split(/\./,$env{$rolekey});
 7280:             $$tstatus='is';
 7281:             if ($$tstart && $$tstart>$update) {
 7282:                 $$tstatus='future';
 7283:                 if ($$tstart<$now) {
 7284:                     if ($$tstart && $$tstart>$refresh) {
 7285:                         if (($$where ne '') && ($$role ne '')) {
 7286:                             my (%allroles,%allgroups,$group_privs,
 7287:                                 %groups_roles,@rolecodes);
 7288:                             my %userroles = (
 7289:                                 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
 7290:                             );
 7291:                             @rolecodes = ('cm'); 
 7292:                             my $spec=$$role.'.'.$$where;
 7293:                             my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
 7294:                             if ($$role =~ /^cr\//) {
 7295:                                 &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
 7296:                                 push(@rolecodes,'cr');
 7297:                             } elsif ($$role eq 'gr') {
 7298:                                 push(@rolecodes,$$role);
 7299:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
 7300:                                                     $env{'user.name'});
 7301:                                 my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
 7302:                                 (undef,my $group_privs) = split(/\//,$trole);
 7303:                                 $group_privs = &unescape($group_privs);
 7304:                                 &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
 7305:                                 my %course_roles = &get_my_roles($env{'user.name'},$env{'user.domain'},'userroles',['active'],['cc','co','in','ta','ep','ad','st','cr'],[$tdomain],1);
 7306:                                 &get_groups_roles($tdomain,$trest,
 7307:                                                   \%course_roles,\@rolecodes,
 7308:                                                   \%groups_roles);
 7309:                             } else {
 7310:                                 push(@rolecodes,$$role);
 7311:                                 &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
 7312:                             }
 7313:                             my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%allroles,\%allgroups,
 7314:                                                                    \%groups_roles);
 7315:                             &appenv(\%userroles,\@rolecodes);
 7316:                             &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
 7317:                         }
 7318:                     }
 7319:                     $$tstatus = 'is';
 7320:                 }
 7321:             }
 7322:             if ($$tend) {
 7323:                 if ($$tend<$update) {
 7324:                     $$tstatus='expired';
 7325:                 } elsif ($$tend<$now) {
 7326:                     $$tstatus='will_not';
 7327:                 }
 7328:             }
 7329:         }
 7330:     }
 7331: }
 7332: 
 7333: sub get_groups_roles {
 7334:     my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
 7335:     return unless((ref($cdom_courseroles) eq 'HASH') && 
 7336:                   (ref($rolecodes) eq 'ARRAY') && 
 7337:                   (ref($groups_roles) eq 'HASH')); 
 7338:     if (keys(%{$cdom_courseroles}) > 0) {
 7339:         my ($cnum) = ($rest =~ /^($match_courseid)/);
 7340:         if ($cdom ne '' && $cnum ne '') {
 7341:             foreach my $key (keys(%{$cdom_courseroles})) {
 7342:                 if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
 7343:                     my $crsrole = $1;
 7344:                     my $crssec = $2;
 7345:                     if ($crsrole =~ /^cr/) {
 7346:                         unless (grep(/^cr$/,@{$rolecodes})) {
 7347:                             push(@{$rolecodes},'cr');
 7348:                         }
 7349:                     } else {
 7350:                         unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
 7351:                             push(@{$rolecodes},$crsrole);
 7352:                         }
 7353:                     }
 7354:                     my $rolekey = "$crsrole./$cdom/$cnum";
 7355:                     if ($crssec ne '') {
 7356:                         $rolekey .= "/$crssec";
 7357:                     }
 7358:                     $rolekey .= './';
 7359:                     $groups_roles->{$rolekey} = $rolecodes;
 7360:                 }
 7361:             }
 7362:         }
 7363:     }
 7364:     return;
 7365: }
 7366: 
 7367: sub delete_env_groupprivs {
 7368:     my ($where,$courseroles,$possroles) = @_;
 7369:     return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
 7370:     my ($dummy,$udom,$uname,$group) = split(/\//,$where);
 7371:     unless (ref($courseroles->{$udom}) eq 'HASH') {
 7372:         %{$courseroles->{$udom}} =
 7373:             &get_my_roles('','','userroles',['active'],
 7374:                           $possroles,[$udom],1);
 7375:     }
 7376:     if (ref($courseroles->{$udom}) eq 'HASH') {
 7377:         foreach my $item (keys(%{$courseroles->{$udom}})) {
 7378:             my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
 7379:             my $area = '/'.$cdom.'/'.$cnum;
 7380:             my $privkey = "user.priv.$crsrole.$area";
 7381:             if ($crssec ne '') {
 7382:                 $privkey .= '/'.$crssec;
 7383:             }
 7384:             $privkey .= ".$area/$group";
 7385:             &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
 7386:         }
 7387:     }
 7388:     return;
 7389: }
 7390: 
 7391: sub check_adhoc_privs {
 7392:     my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller,$sec) = @_;
 7393:     my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
 7394:     if ($sec) {
 7395:         $cckey .= '/'.$sec;
 7396:     } 
 7397:     my $setprivs;
 7398:     if ($env{$cckey}) {
 7399:         my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
 7400:         &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
 7401:         unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
 7402:             &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
 7403:             $setprivs = 1;
 7404:         }
 7405:     } else {
 7406:         &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
 7407:         $setprivs = 1;
 7408:     }
 7409:     return $setprivs;
 7410: }
 7411: 
 7412: sub set_adhoc_privileges {
 7413: # role can be cc, ca, or cr/<dom>/<dom>-domainconfig/role
 7414:     my ($dcdom,$pickedcourse,$role,$caller,$sec) = @_;
 7415:     my $area = '/'.$dcdom.'/'.$pickedcourse;
 7416:     if ($sec ne '') {
 7417:         $area .= '/'.$sec;
 7418:     }
 7419:     my $spec = $role.'.'.$area;
 7420:     my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
 7421:                                   $env{'user.name'},1);
 7422:     my %rolehash = ();
 7423:     if ($role =~ m{^\Qcr/$dcdom/$dcdom\E\-domainconfig/(\w+)$}) {
 7424:         my $rolename = $1;
 7425:         &custom_roleprivs(\%rolehash,$role,$dcdom,$pickedcourse,$spec,$area);
 7426:         my %domdef = &get_domain_defaults($dcdom);
 7427:         if (ref($domdef{'adhocroles'}) eq 'HASH') {
 7428:             if (ref($domdef{'adhocroles'}{$rolename}) eq 'HASH') {
 7429:                 &appenv({'request.role.desc' => $domdef{'adhocroles'}{$rolename}{'desc'},});
 7430:             }
 7431:         }
 7432:     } else {
 7433:         &standard_roleprivs(\%rolehash,$role,$dcdom,$spec,$pickedcourse,$area);
 7434:     }
 7435:     my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%rolehash);
 7436:     &appenv(\%userroles,[$role,'cm']);
 7437:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
 7438:     unless (($caller eq 'constructaccess' && $env{'request.course.id'}) ||
 7439:             ($caller eq 'tiny')) {
 7440:         &appenv( {'request.role'        => $spec,
 7441:                   'request.role.domain' => $dcdom,
 7442:                   'request.course.sec'  => $sec,
 7443:                  }
 7444:                );
 7445:         my $tadv=0;
 7446:         if (&allowed('adv') eq 'F') { $tadv=1; }
 7447:         &appenv({'request.role.adv'    => $tadv});
 7448:     }
 7449: }
 7450: 
 7451: # --------------------------------------------------------------- get interface
 7452: 
 7453: sub get {
 7454:    my ($namespace,$storearr,$udomain,$uname)=@_;
 7455:    my $items='';
 7456:    foreach my $item (@$storearr) {
 7457:        $items.=&escape($item).'&';
 7458:    }
 7459:    $items=~s/\&$//;
 7460:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 7461:    if (!$uname) { $uname=$env{'user.name'}; }
 7462:    my $uhome=&homeserver($uname,$udomain);
 7463: 
 7464:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
 7465:    my @pairs=split(/\&/,$rep);
 7466:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
 7467:      return @pairs;
 7468:    }
 7469:    my %returnhash=();
 7470:    my $i=0;
 7471:    foreach my $item (@$storearr) {
 7472:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 7473:       $i++;
 7474:    }
 7475:    return %returnhash;
 7476: }
 7477: 
 7478: # --------------------------------------------------------------- del interface
 7479: 
 7480: sub del {
 7481:    my ($namespace,$storearr,$udomain,$uname)=@_;
 7482:    my $items='';
 7483:    foreach my $item (@$storearr) {
 7484:        $items.=&escape($item).'&';
 7485:    }
 7486: 
 7487:    $items=~s/\&$//;
 7488:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 7489:    if (!$uname) { $uname=$env{'user.name'}; }
 7490:    my $uhome=&homeserver($uname,$udomain);
 7491:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
 7492: }
 7493: 
 7494: # -------------------------------------------------------------- dump interface
 7495: 
 7496: sub unserialize {
 7497:     my ($rep, $escapedkeys) = @_;
 7498: 
 7499:     return {} if $rep =~ /^error/;
 7500: 
 7501:     my %returnhash=();
 7502: 	foreach my $item (split(/\&/,$rep)) {
 7503: 	    my ($key, $value) = split(/=/, $item, 2);
 7504: 	    $key = unescape($key) unless $escapedkeys;
 7505: 	    next if $key =~ /^error: 2 /;
 7506: 	    $returnhash{$key} = &thaw_unescape($value);
 7507: 	}
 7508:     #return %returnhash;
 7509:     return \%returnhash;
 7510: }        
 7511: 
 7512: # see Lond::dump_with_regexp
 7513: # if $escapedkeys hash keys won't get unescaped.
 7514: sub dump {
 7515:     my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys,$encrypt)=@_;
 7516:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 7517:     if (!$uname) { $uname=$env{'user.name'}; }
 7518:     my $uhome=&homeserver($uname,$udomain);
 7519: 
 7520:     if ($regexp) {
 7521:         $regexp=&escape($regexp);
 7522:     } else {
 7523:         $regexp='.';
 7524:     }
 7525:     if (grep { $_ eq $uhome } current_machine_ids()) {
 7526:         # user is hosted on this machine
 7527:         my $reply = LONCAPA::Lond::dump_with_regexp(join(":", ($udomain,
 7528:                     $uname, $namespace, $regexp, $range)), $perlvar{'lonVersion'});
 7529:         return %{unserialize($reply, $escapedkeys)};
 7530:     }
 7531:     my $rep;
 7532:     if ($encrypt) {
 7533:         $rep=&reply("encrypt:edump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
 7534:     } else {
 7535:         $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
 7536:     }
 7537:     my @pairs=split(/\&/,$rep);
 7538:     my %returnhash=();
 7539:     if (!($rep =~ /^error/ )) {
 7540: 	foreach my $item (@pairs) {
 7541: 	    my ($key,$value)=split(/=/,$item,2);
 7542:         $key = unescape($key) unless $escapedkeys;
 7543:         #$key = &unescape($key);
 7544: 	    next if ($key =~ /^error: 2 /);
 7545: 	    $returnhash{$key}=&thaw_unescape($value);
 7546: 	}
 7547:     }
 7548:     return %returnhash;
 7549: }
 7550: 
 7551: 
 7552: # --------------------------------------------------------- dumpstore interface
 7553: 
 7554: sub dumpstore {
 7555:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
 7556:    # same as dump but keys must be escaped. They may contain colon separated
 7557:    # lists of values that may themself contain colons (e.g. symbs).
 7558:    return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
 7559: }
 7560: 
 7561: # -------------------------------------------------------------- keys interface
 7562: 
 7563: sub getkeys {
 7564:    my ($namespace,$udomain,$uname)=@_;
 7565:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 7566:    if (!$uname) { $uname=$env{'user.name'}; }
 7567:    my $uhome=&homeserver($uname,$udomain);
 7568:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
 7569:    my @keyarray=();
 7570:    foreach my $key (split(/\&/,$rep)) {
 7571:       next if ($key =~ /^error: 2 /);
 7572:       push(@keyarray,&unescape($key));
 7573:    }
 7574:    return @keyarray;
 7575: }
 7576: 
 7577: # --------------------------------------------------------------- currentdump
 7578: sub currentdump {
 7579:    my ($courseid,$sdom,$sname)=@_;
 7580:    $courseid = $env{'request.course.id'} if (! defined($courseid));
 7581:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
 7582:    $sname    = $env{'user.name'}         if (! defined($sname));
 7583:    my $uhome = &homeserver($sname,$sdom);
 7584:    my $rep;
 7585: 
 7586:    if (grep { $_ eq $uhome } current_machine_ids()) {
 7587:        $rep = LONCAPA::Lond::dump_profile_database(join(":", ($sdom, $sname, 
 7588:                    $courseid)));
 7589:    } else {
 7590:        $rep = reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
 7591:    }
 7592: 
 7593:    return if ($rep =~ /^(error:|no_such_host)/);
 7594:    #
 7595:    my %returnhash=();
 7596:    #
 7597:    if ($rep eq 'unknown_cmd') {
 7598:        # an old lond will not know currentdump
 7599:        # Do a dump and make it look like a currentdump
 7600:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
 7601:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
 7602:        my %hash = @tmp;
 7603:        @tmp=();
 7604:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
 7605:    } else {
 7606:        my @pairs=split(/\&/,$rep);
 7607:        foreach my $pair (@pairs) {
 7608:            my ($key,$value)=split(/=/,$pair,2);
 7609:            my ($symb,$param) = split(/:/,$key);
 7610:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
 7611:                                                         &thaw_unescape($value);
 7612:        }
 7613:    }
 7614:    return %returnhash;
 7615: }
 7616: 
 7617: sub convert_dump_to_currentdump{
 7618:     my %hash = %{shift()};
 7619:     my %returnhash;
 7620:     # Code ripped from lond, essentially.  The only difference
 7621:     # here is the unescaping done by lonnet::dump().  Conceivably
 7622:     # we might run in to problems with parameter names =~ /^v\./
 7623:     while (my ($key,$value) = each(%hash)) {
 7624:         my ($v,$symb,$param) = split(/:/,$key);
 7625: 	$symb  = &unescape($symb);
 7626: 	$param = &unescape($param);
 7627:         next if ($v eq 'version' || $symb eq 'keys');
 7628:         next if (exists($returnhash{$symb}) &&
 7629:                  exists($returnhash{$symb}->{$param}) &&
 7630:                  $returnhash{$symb}->{'v.'.$param} > $v);
 7631:         $returnhash{$symb}->{$param}=$value;
 7632:         $returnhash{$symb}->{'v.'.$param}=$v;
 7633:     }
 7634:     #
 7635:     # Remove all of the keys in the hashes which keep track of
 7636:     # the version of the parameter.
 7637:     while (my ($symb,$param_hash) = each(%returnhash)) {
 7638:         # use a foreach because we are going to delete from the hash.
 7639:         foreach my $key (keys(%$param_hash)) {
 7640:             delete($param_hash->{$key}) if ($key =~ /^v\./);
 7641:         }
 7642:     }
 7643:     return \%returnhash;
 7644: }
 7645: 
 7646: # ------------------------------------------------------ critical inc interface
 7647: 
 7648: sub cinc {
 7649:     return &inc(@_,'critical');
 7650: }
 7651: 
 7652: # --------------------------------------------------------------- inc interface
 7653: 
 7654: sub inc {
 7655:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
 7656:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 7657:     if (!$uname) { $uname=$env{'user.name'}; }
 7658:     my $uhome=&homeserver($uname,$udomain);
 7659:     my $items='';
 7660:     if (! ref($store)) {
 7661:         # got a single value, so use that instead
 7662:         $items = &escape($store).'=&';
 7663:     } elsif (ref($store) eq 'SCALAR') {
 7664:         $items = &escape($$store).'=&';        
 7665:     } elsif (ref($store) eq 'ARRAY') {
 7666:         $items = join('=&',map {&escape($_);} @{$store});
 7667:     } elsif (ref($store) eq 'HASH') {
 7668:         while (my($key,$value) = each(%{$store})) {
 7669:             $items.= &escape($key).'='.&escape($value).'&';
 7670:         }
 7671:     }
 7672:     $items=~s/\&$//;
 7673:     if ($critical) {
 7674: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
 7675:     } else {
 7676: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
 7677:     }
 7678: }
 7679: 
 7680: # --------------------------------------------------------------- put interface
 7681: 
 7682: sub put {
 7683:    my ($namespace,$storehash,$udomain,$uname,$encrypt)=@_;
 7684:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 7685:    if (!$uname) { $uname=$env{'user.name'}; }
 7686:    my $uhome=&homeserver($uname,$udomain);
 7687:    my $items='';
 7688:    foreach my $item (keys(%$storehash)) {
 7689:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 7690:    }
 7691:    $items=~s/\&$//;
 7692:    if ($encrypt) {
 7693:        return &reply("encrypt:put:$udomain:$uname:$namespace:$items",$uhome);
 7694:    } else {
 7695:        return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 7696:    }
 7697: }
 7698: 
 7699: # ------------------------------------------------------------ newput interface
 7700: 
 7701: sub newput {
 7702:    my ($namespace,$storehash,$udomain,$uname)=@_;
 7703:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 7704:    if (!$uname) { $uname=$env{'user.name'}; }
 7705:    my $uhome=&homeserver($uname,$udomain);
 7706:    my $items='';
 7707:    foreach my $key (keys(%$storehash)) {
 7708:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 7709:    }
 7710:    $items=~s/\&$//;
 7711:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
 7712: }
 7713: 
 7714: # ---------------------------------------------------------  putstore interface
 7715: 
 7716: sub putstore {
 7717:    my ($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog)=@_;
 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 $key (keys(%$storehash)) {
 7723:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
 7724:    }
 7725:    $items=~s/\&$//;
 7726:    my $esc_symb=&escape($symb);
 7727:    my $esc_v=&escape($version);
 7728:    my $reply =
 7729:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
 7730: 	      $uhome);
 7731:    if (($tolog) && ($reply eq 'ok')) {
 7732:        my $namevalue='';
 7733:        foreach my $key (keys(%{$storehash})) {
 7734:            $namevalue.=&escape($key).'='.&freeze_escape($storehash->{$key}).'&';
 7735:        }
 7736:        my $ip = &get_requestor_ip();
 7737:        $namevalue .= 'ip='.&escape($ip).
 7738:                      '&host='.&escape($perlvar{'lonHostID'}).
 7739:                      '&version='.$esc_v.
 7740:                      '&by='.&escape($env{'user.name'}.':'.$env{'user.domain'});
 7741:        &courselog($symb.':'.$uname.':'.$udomain.':PUTSTORE:'.$namevalue);
 7742:    }
 7743:    if ($reply eq 'unknown_cmd') {
 7744:        # gfall back to way things use to be done
 7745:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
 7746: 			    $uname);
 7747:    }
 7748:    return $reply;
 7749: }
 7750: 
 7751: sub old_putstore {
 7752:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
 7753:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 7754:     if (!$uname) { $uname=$env{'user.name'}; }
 7755:     my $uhome=&homeserver($uname,$udomain);
 7756:     my %newstorehash;
 7757:     foreach my $item (keys(%$storehash)) {
 7758: 	my $key = $version.':'.&escape($symb).':'.$item;
 7759: 	$newstorehash{$key} = $storehash->{$item};
 7760:     }
 7761:     my $items='';
 7762:     my %allitems = ();
 7763:     foreach my $item (keys(%newstorehash)) {
 7764: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
 7765: 	    my $key = $1.':keys:'.$2;
 7766: 	    $allitems{$key} .= $3.':';
 7767: 	}
 7768: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
 7769:     }
 7770:     foreach my $item (keys(%allitems)) {
 7771: 	$allitems{$item} =~ s/\:$//;
 7772: 	$items.= $item.'='.$allitems{$item}.'&';
 7773:     }
 7774:     $items=~s/\&$//;
 7775:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 7776: }
 7777: 
 7778: # ------------------------------------------------------ critical put interface
 7779: 
 7780: sub cput {
 7781:    my ($namespace,$storehash,$udomain,$uname)=@_;
 7782:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 7783:    if (!$uname) { $uname=$env{'user.name'}; }
 7784:    my $uhome=&homeserver($uname,$udomain);
 7785:    my $items='';
 7786:    foreach my $item (keys(%$storehash)) {
 7787:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 7788:    }
 7789:    $items=~s/\&$//;
 7790:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
 7791: }
 7792: 
 7793: # -------------------------------------------------------------- eget interface
 7794: 
 7795: sub eget {
 7796:    my ($namespace,$storearr,$udomain,$uname)=@_;
 7797:    my $items='';
 7798:    foreach my $item (@$storearr) {
 7799:        $items.=&escape($item).'&';
 7800:    }
 7801:    $items=~s/\&$//;
 7802:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 7803:    if (!$uname) { $uname=$env{'user.name'}; }
 7804:    my $uhome=&homeserver($uname,$udomain);
 7805:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
 7806:    my @pairs=split(/\&/,$rep);
 7807:    my %returnhash=();
 7808:    my $i=0;
 7809:    foreach my $item (@$storearr) {
 7810:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 7811:       $i++;
 7812:    }
 7813:    return %returnhash;
 7814: }
 7815: 
 7816: # ------------------------------------------------------------ tmpput interface
 7817: sub tmpput {
 7818:     my ($storehash,$server,$context)=@_;
 7819:     my $items='';
 7820:     foreach my $item (keys(%$storehash)) {
 7821: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 7822:     }
 7823:     $items=~s/\&$//;
 7824:     if (defined($context)) {
 7825:         $items .= ':'.&escape($context);
 7826:     }
 7827:     return &reply("tmpput:$items",$server);
 7828: }
 7829: 
 7830: # ------------------------------------------------------------ tmpget interface
 7831: sub tmpget {
 7832:     my ($token,$server)=@_;
 7833:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 7834:     my $rep=&reply("tmpget:$token",$server);
 7835:     my %returnhash;
 7836:     if ($rep =~ /^(con_lost|error|no_such_host)/i) {
 7837:         return %returnhash;
 7838:     }
 7839:     foreach my $item (split(/\&/,$rep)) {
 7840: 	my ($key,$value)=split(/=/,$item);
 7841: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
 7842:     }
 7843:     return %returnhash;
 7844: }
 7845: 
 7846: # ------------------------------------------------------------ tmpdel interface
 7847: sub tmpdel {
 7848:     my ($token,$server)=@_;
 7849:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 7850:     return &reply("tmpdel:$token",$server);
 7851: }
 7852: 
 7853: # ------------------------------------------------------------ get_timebased_id 
 7854: 
 7855: sub get_timebased_id {
 7856:     my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
 7857:         $maxtries) = @_;
 7858:     my ($newid,$error,$dellock);
 7859:     unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {  
 7860:         return ('','ok','invalid call to get suffix');
 7861:     }
 7862: 
 7863: # set defaults for any optional args for which values were not supplied
 7864:     if ($who eq '') {
 7865:         $who = $env{'user.name'}.':'.$env{'user.domain'};
 7866:     }
 7867:     if (!$locktries) {
 7868:         $locktries = 3;
 7869:     }
 7870:     if (!$maxtries) {
 7871:         $maxtries = 10;
 7872:     }
 7873:     
 7874:     if (($cdom eq '') || ($cnum eq '')) {
 7875:         if ($env{'request.course.id'}) {
 7876:             $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 7877:             $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 7878:         }
 7879:         if (($cdom eq '') || ($cnum eq '')) {
 7880:             return ('','ok','call to get suffix not in course context');
 7881:         }
 7882:     }
 7883: 
 7884: # construct locking item
 7885:     my $lockhash = {
 7886:                       $prefix."\0".'locked_'.$keyid => $who,
 7887:                    };
 7888:     my $tries = 0;
 7889: 
 7890: # attempt to get lock on nohist_$namespace file
 7891:     my $gotlock = &newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
 7892:     while (($gotlock ne 'ok') && $tries <$locktries) {
 7893:         $tries ++;
 7894:         sleep 1;
 7895:         $gotlock = &newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
 7896:     }
 7897: 
 7898: # attempt to get unique identifier, based on current timestamp
 7899:     if ($gotlock eq 'ok') {
 7900:         my %inuse = &dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
 7901:         my $id = time;
 7902:         $newid = $id;
 7903:         if ($idtype eq 'addcode') {
 7904:             $newid .= &sixnum_code();
 7905:         }
 7906:         my $idtries = 0;
 7907:         while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
 7908:             if ($idtype eq 'concat') {
 7909:                 $newid = $id.$idtries;
 7910:             } elsif ($idtype eq 'addcode') {
 7911:                 $newid = $newid.&sixnum_code();
 7912:             } else {
 7913:                 $newid ++;
 7914:             }
 7915:             $idtries ++;
 7916:         }
 7917:         if (!exists($inuse{$prefix."\0".$newid})) {
 7918:             my %new_item =  (
 7919:                               $prefix."\0".$newid => $who,
 7920:                             );
 7921:             my $putresult = &put('nohist_'.$namespace,\%new_item,
 7922:                                                  $cdom,$cnum);
 7923:             if ($putresult ne 'ok') {
 7924:                 undef($newid);
 7925:                 $error = 'error saving new item: '.$putresult;
 7926:             }
 7927:         } else {
 7928:              undef($newid);
 7929:              $error = ('error: no unique suffix available for the new item ');
 7930:         }
 7931: #  remove lock
 7932:         my @del_lock = ($prefix."\0".'locked_'.$keyid);
 7933:         $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
 7934:     } else {
 7935:         $error = "error: could not obtain lockfile\n";
 7936:         $dellock = 'ok';
 7937:         if (($prefix eq 'paste') && ($namespace eq 'courseeditor') && ($keyid eq 'num')) {
 7938:             $dellock = 'nolock';
 7939:         }
 7940:     }
 7941:     return ($newid,$dellock,$error);
 7942: }
 7943: 
 7944: sub sixnum_code {
 7945:     my $code;
 7946:     for (0..6) {
 7947:         $code .= int( rand(9) );
 7948:     }
 7949:     return $code;
 7950: }
 7951: 
 7952: # -------------------------------------------------- portfolio access checking
 7953: 
 7954: sub portfolio_access {
 7955:     my ($requrl,$clientip) = @_;
 7956:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
 7957:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group,$clientip);
 7958:     if ($result) {
 7959:         my %setters;
 7960:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 7961:             my ($startblock,$endblock,$triggerblock,$by_ip,$blockdom) =
 7962:                 &Apache::loncommon::blockcheck(\%setters,'port',$clientip,$unum,$udom);
 7963:             if (($startblock && $endblock) || ($by_ip)) {
 7964:                 return 'B';
 7965:             }
 7966:         } else {
 7967:             my ($startblock,$endblock,$triggerblock,$by_ip,$blockdom) =
 7968:                 &Apache::loncommon::blockcheck(\%setters,'port',$clientip);
 7969:             if (($startblock && $endblock) || ($by_ip)) {
 7970:                 return 'B';
 7971:             }
 7972:         }
 7973:     }
 7974:     if ($result eq 'ok') {
 7975:        return 'F';
 7976:     } elsif ($result =~ /^[^:]+:guest_/) {
 7977:        return 'A';
 7978:     }
 7979:     return '';
 7980: }
 7981: 
 7982: sub get_portfolio_access {
 7983:     my ($udom,$unum,$file_name,$group,$clientip,$access_hash) = @_;
 7984: 
 7985:     if (!ref($access_hash)) {
 7986: 	my $current_perms = &get_portfile_permissions($udom,$unum);
 7987: 	my %access_controls = &get_access_controls($current_perms,$group,
 7988: 						   $file_name);
 7989: 	$access_hash = $access_controls{$file_name};
 7990:     }
 7991: 
 7992:     my ($public,$guest,@domains,@users,@courses,@groups,@ips);
 7993:     my $now = time;
 7994:     if (ref($access_hash) eq 'HASH') {
 7995:         foreach my $key (keys(%{$access_hash})) {
 7996:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
 7997:             if ($start > $now) {
 7998:                 next;
 7999:             }
 8000:             if ($end && $end<$now) {
 8001:                 next;
 8002:             }
 8003:             if ($scope eq 'public') {
 8004:                 $public = $key;
 8005:                 last;
 8006:             } elsif ($scope eq 'guest') {
 8007:                 $guest = $key;
 8008:             } elsif ($scope eq 'domains') {
 8009:                 push(@domains,$key);
 8010:             } elsif ($scope eq 'users') {
 8011:                 push(@users,$key);
 8012:             } elsif ($scope eq 'course') {
 8013:                 push(@courses,$key);
 8014:             } elsif ($scope eq 'group') {
 8015:                 push(@groups,$key);
 8016:             } elsif ($scope eq 'ip') {
 8017:                 push(@ips,$key);
 8018:             }
 8019:         }
 8020:         if ($public) {
 8021:             return 'ok';
 8022:         } elsif (@ips > 0) {
 8023:             my $allowed;
 8024:             foreach my $ipkey (@ips) {
 8025:                 if (ref($access_hash->{$ipkey}{'ip'}) eq 'ARRAY') {
 8026:                     if (&Apache::loncommon::check_ip_acc(join(',',@{$access_hash->{$ipkey}{'ip'}}),$clientip)) {
 8027:                         $allowed = 1;
 8028:                         last; 
 8029:                     }
 8030:                 }
 8031:             }
 8032:             if ($allowed) {
 8033:                 return 'ok';
 8034:             }
 8035:         }
 8036:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 8037:             if ($guest) {
 8038:                 return $guest;
 8039:             }
 8040:         } else {
 8041:             if (@domains > 0) {
 8042:                 foreach my $domkey (@domains) {
 8043:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
 8044:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
 8045:                             return 'ok';
 8046:                         }
 8047:                     }
 8048:                 }
 8049:             }
 8050:             if (@users > 0) {
 8051:                 foreach my $userkey (@users) {
 8052:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
 8053:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
 8054:                             if (ref($item) eq 'HASH') {
 8055:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
 8056:                                     ($item->{'udom'} eq $env{'user.domain'})) {
 8057:                                     return 'ok';
 8058:                                 }
 8059:                             }
 8060:                         }
 8061:                     } 
 8062:                 }
 8063:             }
 8064:             my %roleshash;
 8065:             my @courses_and_groups = @courses;
 8066:             push(@courses_and_groups,@groups); 
 8067:             if (@courses_and_groups > 0) {
 8068:                 my (%allgroups,%allroles); 
 8069:                 my ($start,$end,$role,$sec,$group);
 8070:                 foreach my $envkey (%env) {
 8071:                     if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
 8072:                         my $cid = $2.'_'.$3; 
 8073:                         if ($1 eq 'gr') {
 8074:                             $group = $4;
 8075:                             $allgroups{$cid}{$group} = $env{$envkey};
 8076:                         } else {
 8077:                             if ($4 eq '') {
 8078:                                 $sec = 'none';
 8079:                             } else {
 8080:                                 $sec = $4;
 8081:                             }
 8082:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
 8083:                         }
 8084:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
 8085:                         my $cid = $2.'_'.$3;
 8086:                         if ($4 eq '') {
 8087:                             $sec = 'none';
 8088:                         } else {
 8089:                             $sec = $4;
 8090:                         }
 8091:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
 8092:                     }
 8093:                 }
 8094:                 if (keys(%allroles) == 0) {
 8095:                     return;
 8096:                 }
 8097:                 foreach my $key (@courses_and_groups) {
 8098:                     my %content = %{$$access_hash{$key}};
 8099:                     my $cnum = $content{'number'};
 8100:                     my $cdom = $content{'domain'};
 8101:                     my $cid = $cdom.'_'.$cnum;
 8102:                     if (!exists($allroles{$cid})) {
 8103:                         next;
 8104:                     }    
 8105:                     foreach my $role_id (keys(%{$content{'roles'}})) {
 8106:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
 8107:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
 8108:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
 8109:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
 8110:                         foreach my $role (keys(%{$allroles{$cid}})) {
 8111:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
 8112:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
 8113:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
 8114:                                         if (grep/^all$/,@sections) {
 8115:                                             return 'ok';
 8116:                                         } else {
 8117:                                             if (grep/^$sec$/,@sections) {
 8118:                                                 return 'ok';
 8119:                                             }
 8120:                                         }
 8121:                                     }
 8122:                                 }
 8123:                                 if (keys(%{$allgroups{$cid}}) == 0) {
 8124:                                     if (grep/^none$/,@groups) {
 8125:                                         return 'ok';
 8126:                                     }
 8127:                                 } else {
 8128:                                     if (grep/^all$/,@groups) {
 8129:                                         return 'ok';
 8130:                                     } 
 8131:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
 8132:                                         if (grep/^$group$/,@groups) {
 8133:                                             return 'ok';
 8134:                                         }
 8135:                                     }
 8136:                                 } 
 8137:                             }
 8138:                         }
 8139:                     }
 8140:                 }
 8141:             }
 8142:             if ($guest) {
 8143:                 return $guest;
 8144:             }
 8145:         }
 8146:     }
 8147:     return;
 8148: }
 8149: 
 8150: sub course_group_datechecker {
 8151:     my ($dates,$now,$status) = @_;
 8152:     my ($start,$end) = split(/\./,$dates);
 8153:     if (!$start && !$end) {
 8154:         return 'ok';
 8155:     }
 8156:     if (grep/^active$/,@{$status}) {
 8157:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
 8158:             return 'ok';
 8159:         }
 8160:     }
 8161:     if (grep/^previous$/,@{$status}) {
 8162:         if ($end > $now ) {
 8163:             return 'ok';
 8164:         }
 8165:     }
 8166:     if (grep/^future$/,@{$status}) {
 8167:         if ($start > $now) {
 8168:             return 'ok';
 8169:         }
 8170:     }
 8171:     return; 
 8172: }
 8173: 
 8174: sub parse_portfolio_url {
 8175:     my ($url) = @_;
 8176: 
 8177:     my ($type,$udom,$unum,$group,$file_name);
 8178:     
 8179:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
 8180: 	$type = 1;
 8181:         $udom = $1;
 8182:         $unum = $2;
 8183:         $file_name = $3;
 8184:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
 8185: 	$type = 2;
 8186:         $udom = $1;
 8187:         $unum = $2;
 8188:         $group = $3;
 8189:         $file_name = $3.'/'.$4;
 8190:     }
 8191:     if (wantarray) {
 8192: 	return ($type,$udom,$unum,$file_name,$group);
 8193:     }
 8194:     return $type;
 8195: }
 8196: 
 8197: sub is_portfolio_url {
 8198:     my ($url) = @_;
 8199:     return scalar(&parse_portfolio_url($url));
 8200: }
 8201: 
 8202: sub is_portfolio_file {
 8203:     my ($file) = @_;
 8204:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
 8205:         return 1;
 8206:     }
 8207:     return;
 8208: }
 8209: 
 8210: sub is_coursetool_logo {
 8211:     my ($uri) = @_;
 8212:     if ($env{'request.course.id'}) {
 8213:         my $courseurl = &courseid_to_courseurl($env{'request.course.id'});
 8214:         if ($uri =~ m{^/*uploaded\Q$courseurl\E/toollogo/\d+/[^/]+$}) {
 8215:             return 1;
 8216:         }
 8217:     }
 8218:     return;
 8219: }
 8220: 
 8221: sub usertools_access {
 8222:     my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
 8223:     my ($access,%tools);
 8224:     if ($context eq '') {
 8225:         $context = 'tools';
 8226:     }
 8227:     if ($context eq 'requestcourses') {
 8228:         %tools = (
 8229:                       official   => 1,
 8230:                       unofficial => 1,
 8231:                       community  => 1,
 8232:                       textbook   => 1,
 8233:                       placement  => 1,
 8234:                       lti        => 1,
 8235:                  );
 8236:     } elsif ($context eq 'requestauthor') {
 8237:         %tools = (
 8238:                       requestauthor => 1,
 8239:                  );
 8240:     } elsif ($context eq 'authordefaults') {
 8241:         %tools = (
 8242:                       webdav    => 1,
 8243:                  );
 8244:     } else {
 8245:         %tools = (
 8246:                       aboutme   => 1,
 8247:                       blog      => 1,
 8248:                       portfolio => 1,
 8249:                       portaccess => 1,
 8250:                       timezone  => 1,
 8251:                  );
 8252:     }
 8253:     return if (!defined($tools{$tool}));
 8254: 
 8255:     if (($udom eq '') || ($uname eq '')) {
 8256:         $udom = $env{'user.domain'};
 8257:         $uname = $env{'user.name'};
 8258:     }
 8259: 
 8260:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 8261:         if ($action ne 'reload') {
 8262:             if ($context eq 'requestcourses') {
 8263:                 return $env{'environment.canrequest.'.$tool};
 8264:             } elsif ($context eq 'requestauthor') {
 8265:                 return $env{'environment.canrequest.author'};
 8266:             } elsif ($context eq 'authordefaults') {
 8267:                 if ($tool eq 'webdav') {
 8268:                     return $env{'environment.availabletools.'.$tool};
 8269:                 }
 8270:             } else {
 8271:                 return $env{'environment.availabletools.'.$tool};
 8272:             }
 8273:         }
 8274:     }
 8275: 
 8276:     my ($toolstatus,$inststatus,$envkey);
 8277:     if ($context eq 'requestauthor') {
 8278:         $envkey = $context;
 8279:     } elsif ($context eq 'authordefaults') {
 8280:         if ($tool eq 'webdav') {
 8281:             $envkey = 'tools.'.$tool;
 8282:         }
 8283:     } else {
 8284:         $envkey = $context.'.'.$tool;
 8285:     }
 8286: 
 8287:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
 8288:          ($action ne 'reload')) {
 8289:         $toolstatus = $env{'environment.'.$envkey};
 8290:         $inststatus = $env{'environment.inststatus'};
 8291:     } else {
 8292:         if (ref($userenvref) eq 'HASH') {
 8293:             $toolstatus = $userenvref->{$envkey};
 8294:             $inststatus = $userenvref->{'inststatus'};
 8295:         } else {
 8296:             my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
 8297:             $toolstatus = $userenv{$envkey};
 8298:             $inststatus = $userenv{'inststatus'};
 8299:         }
 8300:     }
 8301: 
 8302:     if ($toolstatus ne '') {
 8303:         if ($toolstatus) {
 8304:             $access = 1;
 8305:         } else {
 8306:             $access = 0;
 8307:         }
 8308:         return $access;
 8309:     }
 8310: 
 8311:     my ($is_adv,%domdef);
 8312:     if (ref($is_advref) eq 'HASH') {
 8313:         $is_adv = $is_advref->{'is_adv'};
 8314:     } else {
 8315:         $is_adv = &is_advanced_user($udom,$uname);
 8316:     }
 8317:     if (ref($domdefref) eq 'HASH') {
 8318:         %domdef = %{$domdefref};
 8319:     } else {
 8320:         %domdef = &get_domain_defaults($udom);
 8321:     }
 8322:     if (ref($domdef{$tool}) eq 'HASH') {
 8323:         if ($is_adv) {
 8324:             if ($domdef{$tool}{'_LC_adv'} ne '') {
 8325:                 if ($domdef{$tool}{'_LC_adv'}) { 
 8326:                     $access = 1;
 8327:                 } else {
 8328:                     $access = 0;
 8329:                 }
 8330:                 return $access;
 8331:             }
 8332:         }
 8333:         if ($inststatus ne '') {
 8334:             my ($hasaccess,$hasnoaccess);
 8335:             foreach my $affiliation (split(/:/,$inststatus)) {
 8336:                 if ($domdef{$tool}{$affiliation} ne '') { 
 8337:                     if ($domdef{$tool}{$affiliation}) {
 8338:                         $hasaccess = 1;
 8339:                     } else {
 8340:                         $hasnoaccess = 1;
 8341:                     }
 8342:                 }
 8343:             }
 8344:             if ($hasaccess || $hasnoaccess) {
 8345:                 if ($hasaccess) {
 8346:                     $access = 1;
 8347:                 } elsif ($hasnoaccess) {
 8348:                     $access = 0; 
 8349:                 }
 8350:                 return $access;
 8351:             }
 8352:         } else {
 8353:             if ($domdef{$tool}{'default'} ne '') {
 8354:                 if ($domdef{$tool}{'default'}) {
 8355:                     $access = 1;
 8356:                 } elsif ($domdef{$tool}{'default'} == 0) {
 8357:                     $access = 0;
 8358:                 }
 8359:                 return $access;
 8360:             }
 8361:         }
 8362:     } else {
 8363:         if (($context eq 'tools') && ($tool ne 'webdav')) {
 8364:             $access = 1;
 8365:         } else {
 8366:             $access = 0;
 8367:         }
 8368:         return $access;
 8369:     }
 8370: }
 8371: 
 8372: sub is_course_owner {
 8373:     my ($cdom,$cnum,$udom,$uname) = @_;
 8374:     if (($udom eq '') || ($uname eq '')) {
 8375:         $udom = $env{'user.domain'};
 8376:         $uname = $env{'user.name'};
 8377:     }
 8378:     unless (($udom eq '') || ($uname eq '')) {
 8379:         if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
 8380:             if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
 8381:                 return 1;
 8382:             } else {
 8383:                 my %courseinfo = &coursedescription($cdom.'/'.$cnum);
 8384:                 if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
 8385:                     return 1;
 8386:                 }
 8387:             }
 8388:         }
 8389:     }
 8390:     return;
 8391: }
 8392: 
 8393: sub is_advanced_user {
 8394:     my ($udom,$uname,$nocache) = @_;
 8395:     my ($is_adv,$is_author,$use_cache,$hashid);
 8396:     if ($udom ne '' && $uname ne '') {
 8397:         if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 8398:             if (wantarray) {
 8399:                 return ($env{'user.adv'},$env{'user.author'});
 8400:             } else {
 8401:                 return $env{'user.adv'};
 8402:             }
 8403:         } elsif (!$nocache) {
 8404:             $use_cache = 1;
 8405:             $hashid = "$udom:$uname";  
 8406:             my ($info,$cached)=&is_cached_new('isadvau',$hashid);
 8407:             if ($cached) {
 8408:                 ($is_adv,$is_author) = split(/:/,$info);
 8409:                 if (wantarray) {
 8410:                     return ($is_adv,$is_author);
 8411:                 }
 8412:                 return $is_adv; 
 8413:             }
 8414:         }
 8415:     }
 8416:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
 8417:     my %allroles;
 8418:     foreach my $role (keys(%roleshash)) {
 8419:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
 8420:         my $area = '/'.$tdomain.'/'.$trest;
 8421:         if ($sec ne '') {
 8422:             $area .= '/'.$sec;
 8423:         }
 8424:         if (($area ne '') && ($trole ne '')) {
 8425:             my $spec=$trole.'.'.$area;
 8426:             if ($trole =~ /^cr\//) {
 8427:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
 8428:             } elsif ($trole ne 'gr') {
 8429:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
 8430:             }
 8431:             if ($trole eq 'au') {
 8432:                 $is_author = 1;
 8433:             }
 8434:         }
 8435:     }
 8436:     foreach my $role (keys(%allroles)) {
 8437:         last if ($is_adv);
 8438:         foreach my $item (split(/:/,$allroles{$role})) {
 8439:             if ($item ne '') {
 8440:                 my ($privilege,$restrictions)=split(/&/,$item);
 8441:                 if ($privilege eq 'adv') {
 8442:                     $is_adv = 1;
 8443:                     last;
 8444:                 }
 8445:             }
 8446:         }
 8447:     }
 8448:     if ($use_cache) {
 8449:         my $cachetime = 600;
 8450:         &do_cache_new('isadvau',$hashid,$is_adv.':'.$is_author,$cachetime);
 8451:     }
 8452:     if (wantarray) {
 8453:         return ($is_adv,$is_author);
 8454:     }
 8455:     return $is_adv;
 8456: }
 8457: 
 8458: sub check_can_request {
 8459:     my ($dom,$can_request,$request_domains,$uname,$udom) = @_;
 8460:     my $canreq = 0;
 8461:     if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
 8462:         $uname = $env{'user.name'};
 8463:         $udom = $env{'user.domain'};
 8464:     }
 8465:     my ($types,$typename) = &Apache::loncommon::course_types();
 8466:     my @options = ('approval','validate','autolimit');
 8467:     my $optregex = join('|',@options);
 8468:     if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
 8469:         my %willtrust;
 8470:         foreach my $type (@{$types}) {
 8471:             if (&usertools_access($uname,$udom,$type,undef,
 8472:                                   'requestcourses')) {
 8473:                 $canreq ++;
 8474:                 if (ref($request_domains) eq 'HASH') {
 8475:                     push(@{$request_domains->{$type}},$udom);
 8476:                 }
 8477:                 if ($dom eq $udom) {
 8478:                     $can_request->{$type} = 1;
 8479:                 }
 8480:             }
 8481:             if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '') &&
 8482:                 ($env{'environment.reqcrsotherdom.'.$type} ne '')) {
 8483:                 my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
 8484:                 if (@curr > 0) {
 8485:                     foreach my $item (@curr) {
 8486:                         if (ref($request_domains) eq 'HASH') {
 8487:                             my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
 8488:                             if ($otherdom ne '') {
 8489:                                 unless (exists($willtrust{$otherdom})) {
 8490:                                     $willtrust{$otherdom} = &will_trust('reqcrs',$env{'user.domain'},$otherdom);
 8491:                                 }
 8492:                                 if ($willtrust{$otherdom}) {
 8493:                                     if (ref($request_domains->{$type}) eq 'ARRAY') {
 8494:                                         unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
 8495:                                             push(@{$request_domains->{$type}},$otherdom);
 8496:                                         }
 8497:                                     } else {
 8498:                                         push(@{$request_domains->{$type}},$otherdom);
 8499:                                     }
 8500:                                 }
 8501:                             }
 8502:                         }
 8503:                     }
 8504:                     unless ($dom eq $env{'user.domain'}) {
 8505:                         $canreq ++;
 8506:                         if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
 8507:                             $can_request->{$type} = 1;
 8508:                         }
 8509:                     }
 8510:                 }
 8511:             }
 8512:         }
 8513:     }
 8514:     return $canreq;
 8515: }
 8516: 
 8517: # ---------------------------------------------- Custom access rule evaluation
 8518: 
 8519: sub customaccess {
 8520:     my ($priv,$uri)=@_;
 8521:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
 8522:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
 8523:     $udom = &LONCAPA::clean_domain($udom);
 8524:     $ucrs = &LONCAPA::clean_username($ucrs);
 8525:     my $access=0;
 8526:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
 8527: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
 8528: 	if ($type eq 'user') {
 8529: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
 8530: 		my ($tdom,$tuname)=split(m{/},$scope);
 8531: 		if ($tdom) {
 8532: 		    if ($tdom ne $env{'user.domain'}) { next; }
 8533: 		}
 8534: 		if ($tuname) {
 8535: 		    if ($tuname ne $env{'user.name'}) { next; }
 8536: 		}
 8537: 		$access=($effect eq 'allow');
 8538: 		last;
 8539: 	    }
 8540: 	} else {
 8541: 	    if ($role) {
 8542: 		if ($role ne $urole) { next; }
 8543: 	    }
 8544: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
 8545: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
 8546: 		if ($tdom) {
 8547: 		    if ($tdom ne $udom) { next; }
 8548: 		}
 8549: 		if ($tcrs) {
 8550: 		    if ($tcrs ne $ucrs) { next; }
 8551: 		}
 8552: 		if ($tsec) {
 8553: 		    if ($tsec ne $usec) { next; }
 8554: 		}
 8555: 		$access=($effect eq 'allow');
 8556: 		last;
 8557: 	    }
 8558: 	    if ($realm eq '' && $role eq '') {
 8559: 		$access=($effect eq 'allow');
 8560: 	    }
 8561: 	}
 8562:     }
 8563:     return $access;
 8564: }
 8565: 
 8566: # ------------------------------------------------- Check for a user privilege
 8567: 
 8568: sub allowed {
 8569:     my ($priv,$uri,$symb,$role,$clientip,$noblockcheck,$ignorecache,$nodeeplinkcheck,$nodeeplinkout)=@_;
 8570:     my $ver_orguri=$uri;
 8571:     $uri=&deversion($uri);
 8572:     my $orguri=$uri;
 8573:     $uri=&declutter($uri);
 8574: 
 8575:     if ($priv eq 'evb') {
 8576: # Evade communication block restrictions for specified role in a course or domain
 8577:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
 8578:             return $1;
 8579:         } else {
 8580:             return;
 8581:         }
 8582:     }
 8583: 
 8584:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
 8585: # Free bre access to adm and meta resources
 8586:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard|viewclasslist|aboutme|ext\.tool)$})) 
 8587: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
 8588: 	&& ($priv eq 'bre')) {
 8589: 	return 'F';
 8590:     }
 8591: 
 8592: # Free bre access to user's own portfolio contents
 8593:     my ($space,$domain,$name,@dir)=split('/',$uri);
 8594:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
 8595: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
 8596:         my %setters;
 8597:         my ($startblock,$endblock,$triggerblock,$by_ip,$blockdom) = 
 8598:             &Apache::loncommon::blockcheck(\%setters,'port',$clientip);
 8599:         if (($startblock && $endblock) || ($by_ip)) {
 8600:             return 'B';
 8601:         } else {
 8602:             return 'F';
 8603:         }
 8604:     }
 8605: 
 8606: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
 8607:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
 8608:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
 8609:         if (exists($env{'request.course.id'})) {
 8610:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 8611:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 8612:             if (($domain eq $cdom) && ($name eq $cnum)) {
 8613:                 my $courseprivid=$env{'request.course.id'};
 8614:                 $courseprivid=~s/\_/\//;
 8615:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
 8616:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
 8617:                     return $1; 
 8618:                 } else {
 8619:                     if ($env{'request.course.sec'}) {
 8620:                         $courseprivid.='/'.$env{'request.course.sec'};
 8621:                     }
 8622:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
 8623:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
 8624:                         return $2;
 8625:                     }
 8626:                 }
 8627:             }
 8628:         }
 8629:     }
 8630: 
 8631: # Free bre to public access
 8632: 
 8633:     if ($priv eq 'bre') {
 8634:         my $copyright;
 8635:         unless ($uri =~ /ext\.tool/) {
 8636:             $copyright=&metadata($uri,'copyright');
 8637:         }
 8638: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
 8639:            return 'F'; 
 8640:         }
 8641:         if ($copyright eq 'priv') {
 8642:             $uri=~/([^\/]+)\/([^\/]+)\//;
 8643: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
 8644: 		return '';
 8645:             }
 8646:         }
 8647:         if ($copyright eq 'domain') {
 8648:             $uri=~/([^\/]+)\/([^\/]+)\//;
 8649: 	    unless (($env{'user.domain'} eq $1) ||
 8650:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
 8651: 		return '';
 8652:             }
 8653:         }
 8654:         if ($env{'request.role'}=~ /li\.\//) {
 8655:             # Library role, so allow browsing of resources in this domain.
 8656:             return 'F';
 8657:         }
 8658:         if ($copyright eq 'custom') {
 8659: 	    unless (&customaccess($priv,$uri)) { return ''; }
 8660:         }
 8661:     }
 8662:     # Domain coordinator is trying to create a course
 8663:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
 8664:         # uri is the requested domain in this case.
 8665:         # comparison to 'request.role.domain' shows if the user has selected
 8666:         # a role of dc for the domain in question.
 8667:         return 'F' if ($uri eq $env{'request.role.domain'});
 8668:     }
 8669: 
 8670:     my $thisallowed='';
 8671:     my $statecond=0;
 8672:     my $courseprivid='';
 8673: 
 8674:     my $ownaccess;
 8675:     # Community Coordinator or Assistant Co-author browsing resource space.
 8676:     if (($priv eq 'bro') && ($env{'user.author'})) {
 8677:         if ($uri eq '') {
 8678:             $ownaccess = 1;
 8679:         } else {
 8680:             if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
 8681:                 my $udom = $env{'user.domain'};
 8682:                 my $uname = $env{'user.name'};
 8683:                 if ($uri =~ m{^\Q$udom\E/?$}) {
 8684:                     $ownaccess = 1;
 8685:                 } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
 8686:                     unless ($uri =~ m{\.\./}) {
 8687:                         $ownaccess = 1;
 8688:                     }
 8689:                 } elsif (($udom ne 'public') && ($uname ne 'public')) {
 8690:                     my $now = time;
 8691:                     if ($uri =~ m{^([^/]+)/?$}) {
 8692:                         my $adom = $1;
 8693:                         foreach my $key (keys(%env)) {
 8694:                             if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
 8695:                                 my ($start,$end) = split(/\./,$env{$key});
 8696:                                 if (($now >= $start) && (!$end || $end > $now)) {
 8697:                                     $ownaccess = 1;
 8698:                                     last;
 8699:                                 }
 8700:                             }
 8701:                         }
 8702:                     } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
 8703:                         my $adom = $1;
 8704:                         my $aname = $2;
 8705:                         foreach my $role ('ca','aa') { 
 8706:                             if ($env{"user.role.$role./$adom/$aname"}) {
 8707:                                 my ($start,$end) =
 8708:                                     split(/\./,$env{"user.role.$role./$adom/$aname"});
 8709:                                 if (($now >= $start) && (!$end || $end > $now)) {
 8710:                                     $ownaccess = 1;
 8711:                                     last;
 8712:                                 }
 8713:                             }
 8714:                         }
 8715:                     }
 8716:                 }
 8717:             }
 8718:         }
 8719:     }
 8720: 
 8721: # Course
 8722: 
 8723:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
 8724:         unless (($priv eq 'bro') && (!$ownaccess)) {
 8725:             $thisallowed.=$1;
 8726:         }
 8727:     }
 8728: 
 8729: # Domain
 8730: 
 8731:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
 8732:        =~/\Q$priv\E\&([^\:]*)/) {
 8733:         unless (($priv eq 'bro') && (!$ownaccess)) {
 8734:             $thisallowed.=$1;
 8735:         }
 8736:     }
 8737: 
 8738: # User who is not author or co-author might still be able to edit
 8739: # resource of an author in the domain (e.g., if Domain Coordinator).
 8740:     if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
 8741:         (&allowed('mdc',$env{'request.course.id'}))) {
 8742:         if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
 8743:             $thisallowed.=$1;
 8744:         }
 8745:     }
 8746: 
 8747: # Course: uri itself is a course
 8748:     my $courseuri=$uri;
 8749:     $courseuri=~s/\_(\d)/\/$1/;
 8750:     $courseuri=~s/^([^\/])/\/$1/;
 8751: 
 8752:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
 8753:        =~/\Q$priv\E\&([^\:]*)/) {
 8754:         if ($priv eq 'mip') {
 8755:             my $rem = $1;
 8756:             if (($uri ne '') && ($env{'request.course.id'} eq $uri) &&
 8757:                 ($env{'course.'.$env{'request.course.id'}.'.internal.courseowner'} eq $env{'user.name'}.':'.$env{'user.domain'})) {
 8758:                 my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 8759:                 if ($cdom ne '') {
 8760:                     my %passwdconf = &get_passwdconf($cdom);
 8761:                     if (ref($passwdconf{'crsownerchg'}) eq 'HASH') {
 8762:                         if (ref($passwdconf{'crsownerchg'}{'by'}) eq 'ARRAY') {
 8763:                             if (@{$passwdconf{'crsownerchg'}{'by'}}) {
 8764:                                 my @inststatuses = split(':',$env{'environment.inststatus'});
 8765:                                 unless (@inststatuses) {
 8766:                                     @inststatuses = ('default');
 8767:                                 }
 8768:                                 foreach my $status (@inststatuses) {
 8769:                                     if (grep(/^\Q$status\E$/,@{$passwdconf{'crsownerchg'}{'by'}})) {
 8770:                                         $thisallowed.=$rem;
 8771:                                     }
 8772:                                 }
 8773:                             }
 8774:                         }
 8775:                     }
 8776:                 }
 8777:             }
 8778:         } else {
 8779:             unless (($priv eq 'bro') && (!$ownaccess)) {
 8780:                 $thisallowed.=$1;
 8781:             }
 8782:         }
 8783:     }
 8784: 
 8785: # URI is an uploaded document for this course, default permissions don't matter
 8786: # not allowing 'edit' access (editupload) to uploaded course docs
 8787:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
 8788: 	$thisallowed='';
 8789:         my ($match)=&is_on_map($uri);
 8790:         if ($match) {
 8791:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
 8792:                   =~/\Q$priv\E\&([^\:]*)/) {
 8793:                 my $value = $1;
 8794:                 my $deeplinkblock;
 8795:                 unless ($nodeeplinkcheck) {
 8796:                     $deeplinkblock = &deeplink_check($priv,$symb,$uri);
 8797:                 }
 8798:                 if ($deeplinkblock) {
 8799:                     $thisallowed='D';
 8800:                 } elsif ($noblockcheck) {
 8801:                     $thisallowed.=$value;
 8802:                 } else {
 8803:                     my @blockers = &has_comm_blocking($priv,$symb,$uri,$ignorecache);
 8804:                     if (@blockers > 0) {
 8805:                         $thisallowed = 'B';
 8806:                     } else {
 8807:                         $thisallowed.=$value;
 8808:                     }
 8809:                 }
 8810:             }
 8811:         } else {
 8812:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
 8813:             if ($refuri) {
 8814:                 if ($refuri =~ m|^/adm/|) {
 8815:                     $thisallowed='F';
 8816:                 } else {
 8817:                     $refuri=&declutter($refuri);
 8818:                     my ($match) = &is_on_map($refuri);
 8819:                     if ($match) {
 8820:                         my $deeplinkblock;
 8821:                         unless ($nodeeplinkcheck) {
 8822:                             $deeplinkblock = &deeplink_check($priv,$symb,$refuri);
 8823:                         }
 8824:                         if ($deeplinkblock) {
 8825:                             $thisallowed='D';
 8826:                         } elsif ($noblockcheck) {
 8827:                             $thisallowed='F';
 8828:                         } else {
 8829:                             my @blockers = &has_comm_blocking($priv,'',$refuri,'',1);
 8830:                             if (@blockers > 0) {
 8831:                                 $thisallowed = 'B';
 8832:                             } else {
 8833:                                 $thisallowed='F';
 8834:                             }
 8835:                         }
 8836:                     }
 8837:                 }
 8838:             }
 8839:         }
 8840:     }
 8841: 
 8842:     if ($priv eq 'bre'
 8843: 	&& $thisallowed ne 'F' 
 8844: 	&& $thisallowed ne '2'
 8845: 	&& &is_portfolio_url($uri)) {
 8846: 	$thisallowed = &portfolio_access($uri,$clientip);
 8847:     }
 8848: 
 8849: # Full access at system, domain or course-wide level? Exit.
 8850:     if ($thisallowed=~/F/) {
 8851: 	return 'F';
 8852:     }
 8853: 
 8854: # If this is generating or modifying users, exit with special codes
 8855: 
 8856:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:vca:vaa:'=~/\:\Q$priv\E\:/) {
 8857: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
 8858: 	    my ($audom,$auname)=split('/',$uri);
 8859: # no author name given, so this just checks on the general right to make a co-author in this domain
 8860: 	    unless ($auname) { return $thisallowed; }
 8861: # an author name is given, so we are about to actually make a co-author for a certain account
 8862: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
 8863: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
 8864: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
 8865: 	} elsif (($priv eq 'vca') || ($priv eq 'vaa')) {
 8866:             my ($audom,$auname)=split('/',$uri);
 8867:             unless ($auname) { return $thisallowed; }
 8868:             unless (($env{'request.role'} eq "dc./$audom") ||
 8869:                     ($env{'request.role'} eq "ca./$uri")) {
 8870:                 return '';
 8871:             }
 8872: 	}
 8873: 	return $thisallowed;
 8874:     }
 8875: #
 8876: # Gathered so far: system, domain and course wide privileges
 8877: #
 8878: # Course: See if uri or referer is an individual resource that is part of 
 8879: # the course
 8880: 
 8881:     if ($env{'request.course.id'}) {
 8882: 
 8883:         if ($priv eq 'bre') {
 8884:             if (&is_coursetool_logo($uri)) {
 8885:                 return 'F';
 8886:             }
 8887:         }
 8888: 
 8889: # If this is modifying password (internal auth) domains must match for user and user's role.
 8890: 
 8891:         if ($priv eq 'mip') {
 8892:             if ($env{'user.domain'} eq $env{'request.role.domain'}) {
 8893:                 return $thisallowed;
 8894:             } else {
 8895:                 return '';
 8896:             }
 8897:         }
 8898: 
 8899:        $courseprivid=$env{'request.course.id'};
 8900:        if ($env{'request.course.sec'}) {
 8901:           $courseprivid.='/'.$env{'request.course.sec'};
 8902:        }
 8903:        $courseprivid=~s/\_/\//;
 8904:        my $checkreferer=1;
 8905:        my ($match,$cond)=&is_on_map($uri);
 8906:        if ($match) {
 8907:            $statecond=$cond;
 8908:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 8909:                =~/\Q$priv\E\&([^\:]*)/) {
 8910:                my $value = $1;
 8911:                if ($priv eq 'bre') {
 8912:                    my $deeplinkblock;
 8913:                    unless ($nodeeplinkcheck) {
 8914:                        $deeplinkblock = &deeplink_check($priv,$symb,$uri);
 8915:                    }
 8916:                    if ($deeplinkblock) {
 8917:                        $thisallowed = 'D';
 8918:                    } elsif ($noblockcheck) {
 8919:                        $thisallowed.=$value;
 8920:                    } else {
 8921:                        my @blockers = &has_comm_blocking($priv,$symb,$uri,$ignorecache);
 8922:                        if (@blockers > 0) {
 8923:                            $thisallowed = 'B';
 8924:                        } else {
 8925:                            $thisallowed.=$value;
 8926:                        }
 8927:                    }
 8928:                } else {
 8929:                    $thisallowed.=$value;
 8930:                }
 8931:                $checkreferer=0;
 8932:            }
 8933:        }
 8934: 
 8935:        if ($checkreferer) {
 8936: 	  my $refuri=$env{'httpref.'.$orguri};
 8937:             unless ($refuri) {
 8938:                 foreach my $key (keys(%env)) {
 8939: 		    if ($key=~/^httpref\..*\*/) {
 8940: 			my $pattern=$key;
 8941:                         $pattern=~s/^httpref\.\/res\///;
 8942:                         $pattern=~s/\*/\[\^\/\]\+/g;
 8943:                         $pattern=~s/\//\\\//g;
 8944:                         if ($orguri=~/$pattern/) {
 8945: 			    $refuri=$env{$key};
 8946:                         }
 8947:                     }
 8948:                 }
 8949:             }
 8950: 
 8951:          if ($refuri) { 
 8952: 	  $refuri=&declutter($refuri);
 8953:           my ($match,$cond)=&is_on_map($refuri);
 8954:             if ($match) {
 8955:               my $refstatecond=$cond;
 8956:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 8957:                   =~/\Q$priv\E\&([^\:]*)/) {
 8958:                   my $value = $1;
 8959:                   if ($priv eq 'bre') {
 8960:                       my $deeplinkblock;
 8961:                       unless ($nodeeplinkcheck) {
 8962:                           $deeplinkblock = &deeplink_check($priv,$symb,$refuri);
 8963:                       }
 8964:                       if ($deeplinkblock) {
 8965:                           $thisallowed = 'D';
 8966:                       } elsif ($noblockcheck) {
 8967:                           $thisallowed.=$value;
 8968:                       } else {
 8969:                           my @blockers = &has_comm_blocking($priv,'',$refuri,'',1);
 8970:                           if (@blockers > 0) {
 8971:                               $thisallowed = 'B';
 8972:                           } else {
 8973:                               $thisallowed.=$value;
 8974:                           }
 8975:                       }
 8976:                   } else {
 8977:                       $thisallowed.=$value;
 8978:                   }
 8979:                   $uri=$refuri;
 8980:                   $statecond=$refstatecond;
 8981:               }
 8982:           }
 8983:         }
 8984:        }
 8985:    }
 8986: 
 8987: #
 8988: # Gathered now: all privileges that could apply, and condition number
 8989: # 
 8990: #
 8991: # Full or no access?
 8992: #
 8993: 
 8994:     if ($thisallowed=~/F/) {
 8995: 	return 'F';
 8996:     }
 8997: 
 8998:     unless ($thisallowed) {
 8999:         return '';
 9000:     }
 9001: 
 9002: # Restrictions exist, deal with them
 9003: #
 9004: #   C:according to course preferences
 9005: #   R:according to resource settings
 9006: #   L:unless locked
 9007: #   X:according to user session state
 9008: #
 9009: 
 9010: # Possibly locked functionality, check all courses
 9011: # In roles.tab, L (unless locked) available for bre, pch, plc, pac and sma.
 9012: # Locks might take effect only after 10 minutes cache expiration for other
 9013: # courses, and 2 minutes for current course, in which user has st or ta role
 9014: # which is neither expired nor a future role (unless current course).
 9015: 
 9016:     my ($needlockcheck,$now,$crsonly);
 9017:     if ($thisallowed=~/L/) {
 9018:         $now = time;
 9019:         if ($priv eq 'bre') {
 9020:             if ($uri ne '') {
 9021:                 if ($orguri =~ m{^/+res/}) {
 9022:                     if ($uri =~ m{^lib/templates/}) {
 9023:                         if ($env{'request.course.id'}) {
 9024:                             $crsonly = 1;
 9025:                             $needlockcheck = 1;
 9026:                         }
 9027:                     } else {
 9028:                         $needlockcheck = 1;
 9029:                     }
 9030:                 } elsif ($env{'request.course.id'}) {
 9031:                     my ($crsdom,$crsnum) = split('_',$env{'request.course.id'});
 9032:                     if (($uri =~ m{^(adm|uploaded|public)/$crsdom/$crsnum/}) ||
 9033:                         ($uri =~ m{^adm/$match_domain/$match_username/\d+/(smppg|bulletinboard)$})) {
 9034:                         $crsonly = 1;
 9035:                     }
 9036:                     $needlockcheck = 1;
 9037:                 }
 9038:             }
 9039:         } elsif (($priv eq 'pch') || ($priv eq 'plc') || ($priv eq 'pac') || ($priv eq 'sma')) {
 9040:             $needlockcheck = 1;
 9041:         }
 9042:     }
 9043:     if ($needlockcheck) {
 9044:         foreach my $envkey (keys(%env)) {
 9045:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
 9046:                my $courseid=$2;
 9047:                my $roleid=$1.'.'.$2;
 9048:                $courseid=~s/^\///;
 9049:                unless ($env{'request.role'} eq $roleid) {
 9050:                    my ($start,$end) = split(/\./,$env{$envkey});
 9051:                    next unless (($now >= $start) && (!$end || $end > $now));
 9052:                }
 9053:                my $expiretime=600;
 9054:                if ($env{'request.role'} eq $roleid) {
 9055: 		  $expiretime=120;
 9056:                }
 9057: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
 9058:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
 9059:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
 9060: 		   &coursedescription($courseid,{'freshen_cache' => 1});
 9061:                }
 9062:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
 9063:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
 9064: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
 9065:                        &log($env{'user.domain'},$env{'user.name'},
 9066:                             $env{'user.home'},
 9067:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
 9068:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 9069:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 9070: 		       return '';
 9071:                    }
 9072:                }
 9073:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
 9074:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
 9075: 		   if ($env{$prefix.'priv.'.$priv.'.lock.expire'}>time) {
 9076:                        &log($env{'user.domain'},$env{'user.name'},
 9077:                             $env{'user.home'},
 9078:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
 9079:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 9080:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 9081: 		       return '';
 9082:                    }
 9083:                }
 9084: 	   }
 9085:        }
 9086:     }
 9087: 
 9088: #
 9089: # Rest of the restrictions depend on selected course
 9090: #
 9091: 
 9092:     unless ($env{'request.course.id'}) {
 9093: 	if ($thisallowed eq 'A') {
 9094: 	    return 'A';
 9095:         } elsif ($thisallowed eq 'B') {
 9096:             return 'B';
 9097: 	} else {
 9098: 	    return '1';
 9099: 	}
 9100:     }
 9101: 
 9102: #
 9103: # Now user is definitely in a course
 9104: #
 9105: 
 9106: 
 9107: # Course preferences
 9108: 
 9109:    if ($thisallowed=~/C/) {
 9110:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 9111:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
 9112:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
 9113: 	   =~/\Q$rolecode\E/) {
 9114: 	   if (($priv ne 'pch') && ($priv ne 'plc') && ($priv ne 'pac')) {
 9115: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 9116: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
 9117: 			$env{'request.course.id'});
 9118: 	   }
 9119:            return '';
 9120:        }
 9121: 
 9122:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
 9123: 	   =~/\Q$unamedom\E/) {
 9124: 	   if (($priv ne 'pch') && ($priv ne 'plc') && ($priv ne 'pac')) {
 9125: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
 9126: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
 9127: 			$env{'request.course.id'});
 9128: 	   }
 9129:            return '';
 9130:        }
 9131:    }
 9132: 
 9133: # Resource preferences
 9134: 
 9135:    if ($thisallowed=~/R/) {
 9136:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 9137:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
 9138: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
 9139: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 9140: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
 9141: 	   }
 9142: 	   return '';
 9143:        }
 9144:    }
 9145: 
 9146: # Restricted for deeplinked session?
 9147: 
 9148:     if ($env{'request.deeplink.login'}) {
 9149:         if ($env{'acc.deeplinkout'} && !$nodeeplinkout) {
 9150:             if (!$symb) { $symb=&symbread($uri,1); }
 9151:             if (($symb) && ($env{'acc.deeplinkout'}=~/\&\Q$symb\E\&/)) {
 9152:                 return '';
 9153:             }
 9154:         }
 9155:     }
 9156: 
 9157: # Restricted by state or randomout?
 9158: 
 9159:    if ($thisallowed=~/X/) {
 9160:       if ($env{'acc.randomout'}) {
 9161: 	 if (!$symb) { $symb=&symbread($uri,1); }
 9162:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
 9163:             return ''; 
 9164:          }
 9165:       }
 9166:       if (&condval($statecond)) {
 9167: 	 return '2';
 9168:       } else {
 9169:          return '';
 9170:       }
 9171:    }
 9172: 
 9173:     if ($thisallowed eq 'A') {
 9174: 	return 'A';
 9175:     } elsif ($thisallowed eq 'B') {
 9176:         return 'B';
 9177:     } elsif ($thisallowed eq 'D') {
 9178:         return 'D';
 9179:     }
 9180:    return 'F';
 9181: }
 9182: 
 9183: # ------------------------------------------- Check construction space access
 9184: 
 9185: sub constructaccess {
 9186:     my ($url,$setpriv)=@_;
 9187: 
 9188: # We do not allow editing of previous versions of files
 9189:     if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
 9190: 
 9191: # Get username and domain from URL
 9192:     my ($ownername,$ownerdomain,$ownerhome);
 9193: 
 9194:     ($ownerdomain,$ownername) =
 9195:         ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)(?:/daxepage|/daxeopen)?/priv/($match_domain)/($match_username)(?:/|$)});
 9196: 
 9197: # The URL does not really point to any authorspace, forget it
 9198:     unless (($ownername) && ($ownerdomain)) { return ''; }
 9199: 
 9200: # Now we need to see if the user has access to the authorspace of
 9201: # $ownername at $ownerdomain
 9202: 
 9203:     if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
 9204: # Real author for this?
 9205:        $ownerhome = $env{'user.home'};
 9206:        if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
 9207:           return ($ownername,$ownerdomain,$ownerhome);
 9208:        }
 9209:     } elsif (&is_course($ownerdomain,$ownername)) {
 9210: # Course Authoring Space?
 9211:         if ($env{'request.course.id'}) {
 9212:             if (($ownername eq $env{'course.'.$env{'request.course.id'}.'.num'}) &&
 9213:                 ($ownerdomain eq $env{'course.'.$env{'request.course.id'}.'.domain'})) {
 9214:                 if (&allowed('mdc',$env{'request.course.id'})) {
 9215:                     $ownerhome = $env{'course.'.$env{'request.course.id'}.'.home'};
 9216:                     return ($ownername,$ownerdomain,$ownerhome);
 9217:                 }
 9218:             }
 9219:         }
 9220:         return '';
 9221:     } else {
 9222: # Co-author for this?
 9223:         if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
 9224:             exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
 9225:             $ownerhome = &homeserver($ownername,$ownerdomain);
 9226:             return ($ownername,$ownerdomain,$ownerhome);
 9227:         }
 9228:     }
 9229: 
 9230: # We don't have any access right now. If we are not possibly going to do anything about this,
 9231: # we might as well leave
 9232:    unless ($setpriv) { return ''; }
 9233: 
 9234: # Backdoor access?
 9235:     my $allowed=&allowed('eco',$ownerdomain);
 9236: # Nope
 9237:     unless ($allowed) { return ''; }
 9238: # Looks like we may have access, but could be locked by the owner of the construction space
 9239:     if ($allowed eq 'U') {
 9240:         my %blocked=&get('environment',['domcoord.author'],
 9241:                          $ownerdomain,$ownername);
 9242: # Is blocked by owner
 9243:         if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
 9244:     }
 9245:     if (($allowed eq 'F') || ($allowed eq 'U')) {
 9246: # Grant temporary access
 9247:         my $then=$env{'user.login.time'};
 9248:         my $update=$env{'user.update.time'};
 9249:         if (!$update) { $update = $then; }
 9250:         my $refresh=$env{'user.refresh.time'};
 9251:         if (!$refresh) { $refresh = $update; }
 9252:         my $now = time;
 9253:         &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
 9254:                            $now,'ca','constructaccess');
 9255:         $ownerhome = &homeserver($ownername,$ownerdomain);
 9256:         return($ownername,$ownerdomain,$ownerhome);
 9257:     }
 9258: # No business here
 9259:     return '';
 9260: }
 9261: 
 9262: # ----------------------------------------------------------- Content Blocking
 9263: 
 9264: {
 9265: # Caches for faster Course Contents display where content blocking
 9266: # is in operation (i.e., interval param set) for timed quiz.
 9267: #
 9268: # User for whom data are being temporarily cached.
 9269: my $cacheduser='';
 9270: # Course for which data are being temporarily cached.
 9271: my $cachedcid='';
 9272: # Cached blockers for this user (a hash of blocking items). 
 9273: my %cachedblockers=();
 9274: # When the data were last cached.
 9275: my $cachedlast='';
 9276: 
 9277: sub load_all_blockers {
 9278:     my ($uname,$udom)=@_;
 9279:     if (($uname ne '') && ($udom ne '')) { 
 9280:         if (($cacheduser eq $uname.':'.$udom) &&
 9281:             ($cachedcid eq $env{'request.course.id'}) &&
 9282:             (abs($cachedlast-time)<5)) {
 9283:             return;
 9284:         }
 9285:     }
 9286:     $cachedlast=time;
 9287:     $cacheduser=$uname.':'.$udom;
 9288:     $cachedcid=$env{'request.course.id'};
 9289:     %cachedblockers = &get_commblock_resources();
 9290:     return;
 9291: }
 9292: 
 9293: sub get_comm_blocks {
 9294:     my ($cdom,$cnum) = @_;
 9295:     if ($cdom eq '' || $cnum eq '') {
 9296:         return unless ($env{'request.course.id'});
 9297:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 9298:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 9299:     }
 9300:     my %commblocks;
 9301:     my $hashid=$cdom.'_'.$cnum;
 9302:     my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
 9303:     if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
 9304:         %commblocks = %{$blocksref};
 9305:     } else {
 9306:         %commblocks = &dump('comm_block',$cdom,$cnum);
 9307:         my $cachetime = 600;
 9308:         &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
 9309:     }
 9310:     return %commblocks;
 9311: }
 9312: 
 9313: sub get_commblock_resources {
 9314:     my ($blocks) = @_;
 9315:     my %blockers = ();
 9316:     return %blockers unless ($env{'request.course.id'});
 9317:     my $courseurl = &courseid_to_courseurl($env{'request.course.id'});
 9318:     if ($env{'request.course.sec'}) {
 9319:         $courseurl .= '/'.$env{'request.course.sec'};
 9320:     }
 9321:     return %blockers if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseurl} =~/evb\&([^\:]*)/);
 9322:     my %commblocks;
 9323:     if (ref($blocks) eq 'HASH') {
 9324:         %commblocks = %{$blocks};
 9325:     } else {
 9326:         %commblocks = &get_comm_blocks();
 9327:     }
 9328:     return %blockers unless (keys(%commblocks) > 0); 
 9329:     my $navmap = Apache::lonnavmaps::navmap->new();
 9330:     return %blockers unless (ref($navmap));
 9331:     my $now = time;
 9332:     foreach my $block (keys(%commblocks)) {
 9333:         if ($block =~ /^(\d+)____(\d+)$/) {
 9334:             my ($start,$end) = ($1,$2);
 9335:             if ($start <= $now && $end >= $now) {
 9336:                 if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
 9337:                     if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
 9338:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
 9339:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
 9340:                                 $blockers{$block}{maps} = $commblocks{$block}{'blocks'}{'docs'}{'maps'}; 
 9341:                             }
 9342:                         }
 9343:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
 9344:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
 9345:                                 $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
 9346:                             }
 9347:                         }
 9348:                     }
 9349:                 }
 9350:             }
 9351:         } elsif ($block =~ /^firstaccess____(.+)$/) {
 9352:             my $item = $1;
 9353:             if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
 9354:                 if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
 9355:                     my (@interval,$mapname);
 9356:                     my $type = 'map';
 9357:                     if ($item eq 'course') {
 9358:                         $type = 'course';
 9359:                         @interval=&EXT("resource.0.interval");
 9360:                     } else {
 9361:                         if ($item =~ /___\d+___/) {
 9362:                             $type = 'resource';
 9363:                             @interval=&EXT("resource.0.interval",$item);
 9364:                         } else {
 9365:                             $mapname = &deversion($item);
 9366:                             if (ref($navmap)) {
 9367:                                 my $timelimit = $navmap->get_mapparam(undef,$mapname,'0.interval');
 9368:                                 @interval = ($timelimit,'map');
 9369:                             }
 9370:                         }
 9371:                     }
 9372:                     if ($interval[0] =~ /^(\d+)/) {
 9373:                         my $timelimit = $1; 
 9374:                         my $first_access;
 9375:                         if ($type eq 'resource') {
 9376:                             $first_access=&get_first_access($interval[1],$item);
 9377:                         } elsif ($type eq 'map') {
 9378:                             $first_access=&get_first_access($interval[1],undef,$item);
 9379:                         } else {
 9380:                             $first_access=&get_first_access($interval[1]);
 9381:                         }
 9382:                         if ($first_access) {
 9383:                             my $timesup = $first_access+$timelimit;
 9384:                             if ($timesup > $now) {
 9385:                                 my $activeblock;
 9386:                                 if ($type eq 'resource') {
 9387:                                     if (ref($navmap)) {
 9388:                                         my $res = $navmap->getBySymb($item);
 9389:                                         if ($res->answerable()) {
 9390:                                             $activeblock = 1;
 9391:                                         }
 9392:                                     }
 9393:                                 } elsif ($type eq 'map') {
 9394:                                     my $mapsymb = &symbread($mapname,1);
 9395:                                     if (($mapsymb) && (ref($navmap))) {
 9396:                                         my $mapres = $navmap->getBySymb($mapsymb);
 9397:                                         if (ref($mapres)) {
 9398:                                             my $first = $mapres->map_start();
 9399:                                             my $finish = $mapres->map_finish();
 9400:                                             my $it = $navmap->getIterator($first,$finish,undef,0,0);
 9401:                                             if (ref($it)) {
 9402:                                                 my $res;
 9403:                                                 while ($res = $it->next(undef,1)) {
 9404:                                                     next unless (ref($res));
 9405:                                                     my $symb = $res->symb();
 9406:                                                     next if (($symb eq $mapsymb) || ($symb eq ''));
 9407:                                                     @interval=&EXT("resource.0.interval",$symb);
 9408:                                                     if ($interval[1] eq 'map') {
 9409:                                                         if ($res->answerable()) {
 9410:                                                             $activeblock = 1;
 9411:                                                             last;
 9412:                                                         }
 9413:                                                     }
 9414:                                                 }
 9415:                                             }
 9416:                                         }
 9417:                                     }
 9418:                                 }
 9419:                                 if ($activeblock) {
 9420:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
 9421:                                          if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
 9422:                                              $blockers{$block}{'maps'} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
 9423:                                          }
 9424:                                     }
 9425:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
 9426:                                         if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
 9427:                                             $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
 9428:                                         }
 9429:                                     }
 9430:                                 }
 9431:                             }
 9432:                         }
 9433:                     }
 9434:                 }
 9435:             }
 9436:         }
 9437:     }
 9438:     return %blockers;
 9439: }
 9440: 
 9441: sub has_comm_blocking {
 9442:     my ($priv,$symb,$uri,$ignoresymbdb,$noenccheck,$blocked,$blocks) = @_;
 9443:     my @blockers;
 9444:     return unless ($env{'request.course.id'});
 9445:     return unless ($priv eq 'bre');
 9446:     return if ($env{'request.state'} eq 'construct');
 9447:     my $courseurl = &courseid_to_courseurl($env{'request.course.id'});
 9448:     if ($env{'request.course.sec'}) {
 9449:         $courseurl .= '/'.$env{'request.course.sec'};
 9450:     }
 9451:     return if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseurl} =~/evb\&([^\:]*)/);
 9452:     my %blockinfo;
 9453:     if (ref($blocks) eq 'HASH') {
 9454:         %blockinfo = &get_commblock_resources($blocks);
 9455:     } else {
 9456:         &load_all_blockers($env{'user.name'},$env{'user.domain'});
 9457:         %blockinfo = %cachedblockers;
 9458:     }
 9459:     return unless (keys(%blockinfo) > 0);
 9460:     my (%possibles,@symbs);
 9461:     if (!$symb) {
 9462:         $symb = &symbread($uri,1,1,1,\%possibles,$ignoresymbdb,$noenccheck);
 9463:     }
 9464:     if ($symb) {
 9465:         @symbs = ($symb);
 9466:     } elsif (keys(%possibles)) { 
 9467:         @symbs = keys(%possibles);
 9468:     }
 9469:     my $noblock;
 9470:     foreach my $symb (@symbs) {
 9471:         last if ($noblock);
 9472:         my ($map,$resid,$resurl)=&decode_symb($symb);
 9473:         foreach my $block (keys(%blockinfo)) {
 9474:             if ($block =~ /^firstaccess____(.+)$/) {
 9475:                 my $item = $1;
 9476:                 unless ($blocked) {
 9477:                     if (($item eq $map) || ($item eq $symb)) {
 9478:                         $noblock = 1;
 9479:                         last;
 9480:                     }
 9481:                 }
 9482:             }
 9483:             if (ref($blockinfo{$block}) eq 'HASH') {
 9484:                 if (ref($blockinfo{$block}{'resources'}) eq 'HASH') {
 9485:                     if ($blockinfo{$block}{'resources'}{$symb}) {
 9486:                         unless (grep(/^\Q$block\E$/,@blockers)) {
 9487:                             push(@blockers,$block);
 9488:                         }
 9489:                     }
 9490:                 }
 9491:                 if (ref($blockinfo{$block}{'maps'}) eq 'HASH') {
 9492:                     if ($blockinfo{$block}{'maps'}{$map}) {
 9493:                         unless (grep(/^\Q$block\E$/,@blockers)) {
 9494:                             push(@blockers,$block);
 9495:                         }
 9496:                     }
 9497:                 }
 9498:             }
 9499:         }
 9500:     }
 9501:     unless ($noblock) { 
 9502:         return @blockers;
 9503:     }
 9504:     return;
 9505: }
 9506: }
 9507: 
 9508: sub deeplink_check {
 9509:     my ($priv,$symb,$uri) = @_;
 9510:     return unless ($env{'request.course.id'});
 9511:     return unless ($priv eq 'bre');
 9512:     return if ($env{'request.state'} eq 'construct');
 9513:     return if ($env{'request.role.adv'});
 9514:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 9515:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 9516:     my (%possibles,@symbs);
 9517:     if (!$symb) {
 9518:         $symb = &symbread($uri,1,1,1,\%possibles);
 9519:     }
 9520:     if ($symb) {
 9521:         @symbs = ($symb);
 9522:     } elsif (keys(%possibles)) {
 9523:         @symbs = keys(%possibles);
 9524:     }
 9525: 
 9526:     my ($deeplink_symb,$allow);
 9527:     if ($env{'request.deeplink.login'}) {
 9528:         $deeplink_symb = &Apache::loncommon::deeplink_login_symb($cnum,$cdom);
 9529:     }
 9530:     foreach my $symb (@symbs) {
 9531:         last if ($allow);
 9532:         my $deeplink = &EXT("resource.0.deeplink",$symb);
 9533:         if ($deeplink eq '') {
 9534:             $allow = 1;
 9535:         } else {
 9536:             my ($state,$others,$listed,$scope,$protect) = split(/,/,$deeplink);
 9537:             if ($state ne 'only') {
 9538:                 $allow = 1;
 9539:             } else {
 9540:                 my $check_deeplink_entry;
 9541:                 if ($protect ne 'none') {
 9542:                     my ($acctype,$item) = split(/:/,$protect);
 9543:                     if (($acctype eq 'ltic') && ($env{'user.linkprotector'})) {
 9544:                         if (grep(/^\Q$item\Ec$/,split(/,/,$env{'user.linkprotector'}))) {
 9545:                             $check_deeplink_entry = 1
 9546:                         }
 9547:                     } elsif (($acctype eq 'ltid') && ($env{'user.linkprotector'})) {
 9548:                         if (grep(/^\Q$item\Ed$/,split(/,/,$env{'user.linkprotector'}))) {
 9549:                             $check_deeplink_entry = 1;
 9550:                         }
 9551:                     } elsif (($acctype eq 'key') && ($env{'user.deeplinkkey'})) {
 9552:                         if (grep(/^\Q$item\E$/,split(/,/,$env{'user.deeplinkkey'}))) {
 9553:                             $check_deeplink_entry = 1;
 9554:                         }
 9555:                     }
 9556:                 }
 9557:                 if (($protect eq 'none') || ($check_deeplink_entry)) {
 9558:                     if ($scope eq 'res') {
 9559:                         if ($symb eq $deeplink_symb) {
 9560:                             $allow = 1;
 9561:                         }
 9562:                     } elsif (($scope eq 'map') || ($scope eq 'rec')) {
 9563:                         my ($map_from_symb,$map_from_login);
 9564:                         $map_from_symb = &deversion((&decode_symb($symb))[0]);
 9565:                         if ($deeplink_symb =~ /\.(page|sequence)$/) {
 9566:                             $map_from_login = &deversion((&decode_symb($deeplink_symb))[2]);
 9567:                         } else {
 9568:                             $map_from_login = &deversion((&decode_symb($deeplink_symb))[0]);
 9569:                         }
 9570:                         if (($map_from_symb) && ($map_from_login)) {
 9571:                             if ($map_from_symb eq $map_from_login) {
 9572:                                 $allow = 1;
 9573:                             } elsif ($scope eq 'rec') {
 9574:                                 my @recurseup = &get_map_hierarchy($map_from_symb,$env{'request.course.id'});
 9575:                                 if (grep(/^\Q$map_from_login\E$/,@recurseup)) {
 9576:                                     $allow = 1;
 9577:                                 }
 9578:                             }
 9579:                         }
 9580:                     }
 9581:                 }
 9582:             }
 9583:         }
 9584:     }
 9585:     return if ($allow);
 9586:     return 1;
 9587: }
 9588: 
 9589: # -------------------------------- Deversion and split uri into path an filename   
 9590: 
 9591: #
 9592: #   Removes the version from a URI and
 9593: #   splits it in to its filename and path to the filename.
 9594: #   Seems like File::Basename could have done this more clearly.
 9595: #   Parameters:
 9596: #      $uri   - input URI
 9597: #   Returns:
 9598: #     Two element list consisting of 
 9599: #     $pathname  - the URI up to and excluding the trailing /
 9600: #     $filename  - The part of the URI following the last /
 9601: #  NOTE:
 9602: #    Another realization of this is simply:
 9603: #    use File::Basename;
 9604: #    ...
 9605: #    $uri = shift;
 9606: #    $filename = basename($uri);
 9607: #    $path     = dirname($uri);
 9608: #    return ($filename, $path);
 9609: #
 9610: #     The implementation below is probably faster however.
 9611: #
 9612: sub split_uri_for_cond {
 9613:     my $uri=&deversion(&declutter(shift));
 9614:     my @uriparts=split(/\//,$uri);
 9615:     my $filename=pop(@uriparts);
 9616:     my $pathname=join('/',@uriparts);
 9617:     return ($pathname,$filename);
 9618: }
 9619: # --------------------------------------------------- Is a resource on the map?
 9620: 
 9621: sub is_on_map {
 9622:     my ($pathname,$filename) = &split_uri_for_cond(shift);
 9623:     #Trying to find the conditional for the file
 9624:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
 9625: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
 9626:     if ($match) {
 9627: 	return (1,$1);
 9628:     } else {
 9629: 	return (0,0);
 9630:     }
 9631: }
 9632: 
 9633: # --------------------------------------------------------- Get symb from alias
 9634: 
 9635: sub get_symb_from_alias {
 9636:     my $symb=shift;
 9637:     my ($map,$resid,$url)=&decode_symb($symb);
 9638: # Already is a symb
 9639:     if ($url) { return $symb; }
 9640: # Must be an alias
 9641:     my $aliassymb='';
 9642:     my %bighash;
 9643:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 9644:                             &GDBM_READER(),0640)) {
 9645:         my $rid=$bighash{'mapalias_'.$symb};
 9646: 	if ($rid) {
 9647: 	    my ($mapid,$resid)=split(/\./,$rid);
 9648: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
 9649: 				    $resid,$bighash{'src_'.$rid});
 9650: 	}
 9651:         untie %bighash;
 9652:     }
 9653:     return $aliassymb;
 9654: }
 9655: 
 9656: # ----------------------------------------------------------------- Define Role
 9657: 
 9658: sub definerole {
 9659:   if (allowed('mcr','/')) {
 9660:     my ($rolename,$sysrole,$domrole,$courole,$uname,$udom)=@_;
 9661:     foreach my $role (split(':',$sysrole)) {
 9662: 	my ($crole,$cqual)=split(/\&/,$role);
 9663:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
 9664:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
 9665: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 9666:                return "refused:s:$crole&$cqual"; 
 9667:             }
 9668:         }
 9669:     }
 9670:     foreach my $role (split(':',$domrole)) {
 9671: 	my ($crole,$cqual)=split(/\&/,$role);
 9672:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
 9673:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
 9674: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
 9675:                return "refused:d:$crole&$cqual"; 
 9676:             }
 9677:         }
 9678:     }
 9679:     foreach my $role (split(':',$courole)) {
 9680: 	my ($crole,$cqual)=split(/\&/,$role);
 9681:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
 9682:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
 9683: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 9684:                return "refused:c:$crole&$cqual"; 
 9685:             }
 9686:         }
 9687:     }
 9688:     my $uhome;
 9689:     if (($uname ne '') && ($udom ne '')) {
 9690:         $uhome = &homeserver($uname,$udom);
 9691:         return $uhome if ($uhome eq 'no_host');
 9692:     } else {
 9693:         $uname = $env{'user.name'};
 9694:         $udom = $env{'user.domain'};
 9695:         $uhome = $env{'user.home'};
 9696:     }
 9697:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
 9698:                 "$udom:$uname:rolesdef_$rolename=".
 9699:                 escape($sysrole.'_'.$domrole.'_'.$courole);
 9700:     return reply($command,$uhome);
 9701:   } else {
 9702:     return 'refused';
 9703:   }
 9704: }
 9705: 
 9706: # ---------------- Make a metadata query against the network of library servers
 9707: 
 9708: sub metadata_query {
 9709:     my ($query,$custom,$customshow,$server_array,$domains_hash)=@_;
 9710:     my %rhash;
 9711:     my %libserv = &all_library();
 9712:     my @server_list = (defined($server_array) ? @$server_array
 9713:                                               : keys(%libserv) );
 9714:     for my $server (@server_list) {
 9715:         my $domains = ''; 
 9716:         if (ref($domains_hash) eq 'HASH') {
 9717:             $domains = $domains_hash->{$server}; 
 9718:         }
 9719: 	unless ($custom or $customshow) {
 9720: 	    my $reply=&reply("querysend:".&escape($query).':::'.&escape($domains),$server);
 9721: 	    $rhash{$server}=$reply;
 9722: 	}
 9723: 	else {
 9724: 	    my $reply=&reply("querysend:".&escape($query).':'.
 9725: 			     &escape($custom).':'.&escape($customshow).':'.&escape($domains),
 9726: 			     $server);
 9727: 	    $rhash{$server}=$reply;
 9728: 	}
 9729:     }
 9730:     return \%rhash;
 9731: }
 9732: 
 9733: # ----------------------------------------- Send log queries and wait for reply
 9734: 
 9735: sub log_query {
 9736:     my ($uname,$udom,$query,%filters)=@_;
 9737:     my $uhome=&homeserver($uname,$udom);
 9738:     if ($uhome eq 'no_host') { return 'error: no_host'; }
 9739:     my $uhost=&hostname($uhome);
 9740:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
 9741:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
 9742:                        $uhome);
 9743:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
 9744:     return get_query_reply($queryid);
 9745: }
 9746: 
 9747: # -------------------------- Update MySQL table for portfolio file
 9748: 
 9749: sub update_portfolio_table {
 9750:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
 9751:     if ($group ne '') {
 9752:         $file_name =~s /^\Q$group\E//;
 9753:     }
 9754:     my $homeserver = &homeserver($uname,$udom);
 9755:     my $queryid=
 9756:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
 9757:                ':'.&escape($file_name).':'.$action,$homeserver);
 9758:     my $reply = &get_query_reply($queryid);
 9759:     return $reply;
 9760: }
 9761: 
 9762: # -------------------------- Update MySQL allusers table
 9763: 
 9764: sub update_allusers_table {
 9765:     my ($uname,$udom,$names) = @_;
 9766:     my $homeserver = &homeserver($uname,$udom);
 9767:     my $queryid=
 9768:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
 9769:                'lastname='.&escape($names->{'lastname'}).'%%'.
 9770:                'firstname='.&escape($names->{'firstname'}).'%%'.
 9771:                'middlename='.&escape($names->{'middlename'}).'%%'.
 9772:                'generation='.&escape($names->{'generation'}).'%%'.
 9773:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
 9774:                'id='.&escape($names->{'id'}),$homeserver);
 9775:     return;
 9776: }
 9777: 
 9778: # ------- Request retrieval of institutional classlists for course(s)
 9779: 
 9780: sub fetch_enrollment_query {
 9781:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
 9782:     my ($homeserver,$sleep,$loopmax);
 9783:     my $maxtries = 1;
 9784:     if ($context eq 'automated') {
 9785:         $homeserver = $perlvar{'lonHostID'};
 9786:         $sleep = 2;
 9787:         $loopmax = 100;
 9788:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
 9789:     } else {
 9790:         $homeserver = &homeserver($cnum,$dom);
 9791:     }
 9792:     my $host=&hostname($homeserver);
 9793:     my $cmd = '';
 9794:     foreach my $affiliate (keys(%{$affiliatesref})) {
 9795:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
 9796:     }
 9797:     $cmd =~ s/%%$//;
 9798:     $cmd = &escape($cmd);
 9799:     my $query = 'fetchenrollment';
 9800:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
 9801:     unless ($queryid=~/^\Q$host\E\_/) { 
 9802:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
 9803:         return 'error: '.$queryid;
 9804:     }
 9805:     my $reply = &get_query_reply($queryid,$sleep,$loopmax);
 9806:     my $tries = 1;
 9807:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 9808:         $reply = &get_query_reply($queryid,$sleep,$loopmax);
 9809:         $tries ++;
 9810:     }
 9811:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 9812:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 9813:     } else {
 9814:         my @responses = split(/:/,$reply);
 9815:         if (grep { $_ eq $homeserver } &current_machine_ids()) {
 9816:             foreach my $line (@responses) {
 9817:                 my ($key,$value) = split(/=/,$line,2);
 9818:                 $$replyref{$key} = $value;
 9819:             }
 9820:         } else {
 9821:             my $pathname = LONCAPA::tempdir();
 9822:             foreach my $line (@responses) {
 9823:                 my ($key,$value) = split(/=/,$line);
 9824:                 $$replyref{$key} = $value;
 9825:                 if ($value > 0) {
 9826:                     foreach my $item (@{$$affiliatesref{$key}}) {
 9827:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
 9828:                         my $destname = $pathname.'/'.$filename;
 9829:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
 9830:                         if ($xml_classlist =~ /^error/) {
 9831:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
 9832:                         } else {
 9833:                             if ( open(FILE,">",$destname) ) {
 9834:                                 print FILE &unescape($xml_classlist);
 9835:                                 close(FILE);
 9836:                             } else {
 9837:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
 9838:                             }
 9839:                         }
 9840:                     }
 9841:                 }
 9842:             }
 9843:         }
 9844:         return 'ok';
 9845:     }
 9846:     return 'error';
 9847: }
 9848: 
 9849: sub get_query_reply {
 9850:     my ($queryid,$sleep,$loopmax) = @_;
 9851:     if (($sleep eq '') || ($sleep !~ /^\d+\.?\d*$/)) {
 9852:         $sleep = 0.2;
 9853:     }
 9854:     if (($loopmax eq '') || ($loopmax =~ /\D/)) {
 9855:         $loopmax = 100;
 9856:     }
 9857:     my $replyfile=LONCAPA::tempdir().$queryid;
 9858:     my $reply='';
 9859:     for (1..$loopmax) {
 9860: 	sleep($sleep);
 9861:         if (-e $replyfile.'.end') {
 9862: 	    if (open(my $fh,"<",$replyfile)) {
 9863: 		$reply = join('',<$fh>);
 9864: 		close($fh);
 9865: 	   } else { return 'error: reply_file_error'; }
 9866:            return &unescape($reply);
 9867: 	}
 9868:     }
 9869:     return 'timeout:'.$queryid;
 9870: }
 9871: 
 9872: sub courselog_query {
 9873: #
 9874: # possible filters:
 9875: # url: url or symb
 9876: # username
 9877: # domain
 9878: # action: view, submit, grade
 9879: # start: timestamp
 9880: # end: timestamp
 9881: #
 9882:     my (%filters)=@_;
 9883:     unless ($env{'request.course.id'}) { return 'no_course'; }
 9884:     if ($filters{'url'}) {
 9885: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
 9886:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
 9887:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
 9888:     }
 9889:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 9890:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 9891:     return &log_query($cname,$cdom,'courselog',%filters);
 9892: }
 9893: 
 9894: sub userlog_query {
 9895: #
 9896: # possible filters:
 9897: # action: log check role
 9898: # start: timestamp
 9899: # end: timestamp
 9900: #
 9901:     my ($uname,$udom,%filters)=@_;
 9902:     return &log_query($uname,$udom,'userlog',%filters);
 9903: }
 9904: 
 9905: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
 9906: 
 9907: sub auto_run {
 9908:     my ($cnum,$cdom) = @_;
 9909:     my $response = 0;
 9910:     my $settings;
 9911:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
 9912:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
 9913:         $settings = $domconfig{'autoenroll'};
 9914:         if ($settings->{'run'} eq '1') {
 9915:             $response = 1;
 9916:         }
 9917:     } else {
 9918:         my $homeserver;
 9919:         if (&is_course($cdom,$cnum)) {
 9920:             $homeserver = &homeserver($cnum,$cdom);
 9921:         } else {
 9922:             $homeserver = &domain($cdom,'primary');
 9923:         }
 9924:         if ($homeserver ne 'no_host') {
 9925:             $response = &reply('autorun:'.$cdom,$homeserver);
 9926:         }
 9927:     }
 9928:     return $response;
 9929: }
 9930: 
 9931: sub auto_get_sections {
 9932:     my ($cnum,$cdom,$inst_coursecode) = @_;
 9933:     my $homeserver;
 9934:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) { 
 9935:         $homeserver = &homeserver($cnum,$cdom);
 9936:     }
 9937:     if (!defined($homeserver)) { 
 9938:         if ($cdom =~ /^$match_domain$/) {
 9939:             $homeserver = &domain($cdom,'primary');
 9940:         }
 9941:     }
 9942:     my @secs;
 9943:     if (defined($homeserver)) {
 9944:         my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
 9945:         unless ($response eq 'refused') {
 9946:             @secs = split(/:/,$response);
 9947:         }
 9948:     }
 9949:     return @secs;
 9950: }
 9951: 
 9952: sub auto_new_course {
 9953:     my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
 9954:     my $homeserver = &homeserver($cnum,$cdom);
 9955:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
 9956:     return $response;
 9957: }
 9958: 
 9959: sub auto_validate_courseID {
 9960:     my ($cnum,$cdom,$inst_course_id) = @_;
 9961:     my $homeserver = &homeserver($cnum,$cdom);
 9962:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
 9963:     return $response;
 9964: }
 9965: 
 9966: sub auto_validate_instcode {
 9967:     my ($cnum,$cdom,$instcode,$owner) = @_;
 9968:     my ($homeserver,$response);
 9969:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
 9970:         $homeserver = &homeserver($cnum,$cdom);
 9971:     }
 9972:     if (!defined($homeserver)) {
 9973:         if ($cdom =~ /^$match_domain$/) {
 9974:             $homeserver = &domain($cdom,'primary');
 9975:         }
 9976:     }
 9977:     $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
 9978:                         &escape($instcode).':'.&escape($owner),$homeserver));
 9979:     my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
 9980:     return ($outcome,$description,$defaultcredits);
 9981: }
 9982: 
 9983: sub auto_validate_inst_crosslist {
 9984:     my ($cnum,$cdom,$instcode,$inst_xlist,$coowner) = @_;
 9985:     my ($homeserver,$response);
 9986:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
 9987:         $homeserver = &homeserver($cnum,$cdom);
 9988:     }
 9989:     if (!defined($homeserver)) {
 9990:         if ($cdom =~ /^$match_domain$/) {
 9991:             $homeserver = &domain($cdom,'primary');
 9992:         }
 9993:     }
 9994:     unless (($homeserver eq '') || ($homeserver eq 'no_host')) {
 9995:         $response=&reply('autovalidateinstcrosslist:'.$cdom.':'.
 9996:                          &escape($instcode).':'.&escape($inst_xlist).':'.
 9997:                          &escape($coowner),$homeserver);
 9998:     }
 9999:     return $response;
10000: }
10001: 
10002: sub auto_create_password {
10003:     my ($cnum,$cdom,$authparam,$udom) = @_;
10004:     my ($homeserver,$response);
10005:     my $create_passwd = 0;
10006:     my $authchk = '';
10007:     if ($udom =~ /^$match_domain$/) {
10008:         $homeserver = &domain($udom,'primary');
10009:     }
10010:     if ($homeserver eq '') {
10011:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
10012:             $homeserver = &homeserver($cnum,$cdom);
10013:         }
10014:     }
10015:     if ($homeserver eq '') {
10016:         $authchk = 'nodomain';
10017:     } else {
10018:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
10019:         if ($response eq 'refused') {
10020:             $authchk = 'refused';
10021:         } else {
10022:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
10023:         }
10024:     }
10025:     return ($authparam,$create_passwd,$authchk);
10026: }
10027: 
10028: sub auto_photo_permission {
10029:     my ($cnum,$cdom,$students) = @_;
10030:     my $homeserver = &homeserver($cnum,$cdom);
10031:     my ($outcome,$perm_reqd,$conditions) = 
10032: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
10033:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
10034: 	return (undef,undef);
10035:     }
10036:     return ($outcome,$perm_reqd,$conditions);
10037: }
10038: 
10039: sub auto_checkphotos {
10040:     my ($uname,$udom,$pid) = @_;
10041:     my $homeserver = &homeserver($uname,$udom);
10042:     my ($result,$resulttype);
10043:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
10044: 				   &escape($uname).':'.&escape($pid),
10045: 				   $homeserver));
10046:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
10047: 	return (undef,undef);
10048:     }
10049:     if ($outcome) {
10050:         ($result,$resulttype) = split(/:/,$outcome);
10051:     } 
10052:     return ($result,$resulttype);
10053: }
10054: 
10055: sub auto_photochoice {
10056:     my ($cnum,$cdom) = @_;
10057:     my $homeserver = &homeserver($cnum,$cdom);
10058:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
10059: 						       &escape($cdom),
10060: 						       $homeserver)));
10061:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
10062: 	return (undef,undef);
10063:     }
10064:     return ($update,$comment);
10065: }
10066: 
10067: sub auto_photoupdate {
10068:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
10069:     my $homeserver = &homeserver($cnum,$dom);
10070:     my $host=&hostname($homeserver);
10071:     my $cmd = '';
10072:     my $maxtries = 1;
10073:     foreach my $affiliate (keys(%{$affiliatesref})) {
10074:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
10075:     }
10076:     $cmd =~ s/%%$//;
10077:     $cmd = &escape($cmd);
10078:     my $query = 'institutionalphotos';
10079:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
10080:     unless ($queryid=~/^\Q$host\E\_/) {
10081:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
10082:         return 'error: '.$queryid;
10083:     }
10084:     my $reply = &get_query_reply($queryid);
10085:     my $tries = 1;
10086:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
10087:         $reply = &get_query_reply($queryid);
10088:         $tries ++;
10089:     }
10090:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
10091:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
10092:     } else {
10093:         my @responses = split(/:/,$reply);
10094:         my $outcome = shift(@responses); 
10095:         foreach my $item (@responses) {
10096:             my ($key,$value) = split(/=/,$item);
10097:             $$photo{$key} = $value;
10098:         }
10099:         return $outcome;
10100:     }
10101:     return 'error';
10102: }
10103: 
10104: sub auto_instcode_format {
10105:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
10106: 	$cat_order) = @_;
10107:     my $courses = '';
10108:     my @homeservers;
10109:     if ($caller eq 'global') {
10110: 	my %servers = &get_servers($codedom,'library');
10111: 	foreach my $tryserver (keys(%servers)) {
10112: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
10113: 		push(@homeservers,$tryserver);
10114: 	    }
10115:         }
10116:     } elsif ($caller eq 'requests') {
10117:         if ($codedom =~ /^$match_domain$/) {
10118:             my $chome = &domain($codedom,'primary');
10119:             unless ($chome eq 'no_host') {
10120:                 push(@homeservers,$chome);
10121:             }
10122:         }
10123:     } else {
10124:         push(@homeservers,&homeserver($caller,$codedom));
10125:     }
10126:     foreach my $code (keys(%{$instcodes})) {
10127:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
10128:     }
10129:     chop($courses);
10130:     my $ok_response = 0;
10131:     my $response;
10132:     while (@homeservers > 0 && $ok_response == 0) {
10133:         my $server = shift(@homeservers); 
10134:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
10135:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
10136:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
10137: 		split(/:/,$response);
10138:             %{$codes} = (%{$codes},&str2hash($codes_str));
10139:             push(@{$codetitles},&str2array($codetitles_str));
10140:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
10141:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
10142:             $ok_response = 1;
10143:         }
10144:     }
10145:     if ($ok_response) {
10146:         return 'ok';
10147:     } else {
10148:         return $response;
10149:     }
10150: }
10151: 
10152: sub auto_instcode_defaults {
10153:     my ($domain,$returnhash,$code_order) = @_;
10154:     my @homeservers;
10155: 
10156:     my %servers = &get_servers($domain,'library');
10157:     foreach my $tryserver (keys(%servers)) {
10158: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
10159: 	    push(@homeservers,$tryserver);
10160: 	}
10161:     }
10162: 
10163:     my $response;
10164:     foreach my $server (@homeservers) {
10165:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
10166:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
10167: 	
10168: 	foreach my $pair (split(/\&/,$response)) {
10169: 	    my ($name,$value)=split(/\=/,$pair);
10170: 	    if ($name eq 'code_order') {
10171: 		@{$code_order} = split(/\&/,&unescape($value));
10172: 	    } else {
10173: 		$returnhash->{&unescape($name)}=&unescape($value);
10174: 	    }
10175: 	}
10176: 	return 'ok';
10177:     }
10178: 
10179:     return $response;
10180: }
10181: 
10182: sub auto_possible_instcodes {
10183:     my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
10184:     unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') && 
10185:             (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
10186:         return;
10187:     }
10188:     my (@homeservers,$uhome);
10189:     if (defined(&domain($domain,'primary'))) {
10190:         $uhome=&domain($domain,'primary');
10191:         push(@homeservers,&domain($domain,'primary'));
10192:     } else {
10193:         my %servers = &get_servers($domain,'library');
10194:         foreach my $tryserver (keys(%servers)) {
10195:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
10196:                 push(@homeservers,$tryserver);
10197:             }
10198:         }
10199:     }
10200:     my $response;
10201:     foreach my $server (@homeservers) {
10202:         $response=&reply('autopossibleinstcodes:'.$domain,$server);
10203:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
10204:         my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) = 
10205:             split(':',$response);
10206:         @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
10207:         @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
10208:         foreach my $item (split('&',$cat_title)) {   
10209:             my ($name,$value)=split('=',$item);
10210:             $cat_titles->{&unescape($name)}=&thaw_unescape($value);
10211:         }
10212:         foreach my $item (split('&',$cat_order)) {
10213:             my ($name,$value)=split('=',$item);
10214:             $cat_orders->{&unescape($name)}=&thaw_unescape($value);
10215:         }
10216:         return 'ok';
10217:     }
10218:     return $response;
10219: }
10220: 
10221: sub auto_courserequest_checks {
10222:     my ($dom) = @_;
10223:     my ($homeserver,%validations);
10224:     if ($dom =~ /^$match_domain$/) {
10225:         $homeserver = &domain($dom,'primary');
10226:     }
10227:     unless ($homeserver eq 'no_host') {
10228:         my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
10229:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
10230:             my @items = split(/&/,$response);
10231:             foreach my $item (@items) {
10232:                 my ($key,$value) = split('=',$item);
10233:                 $validations{&unescape($key)} = &thaw_unescape($value);
10234:             }
10235:         }
10236:     }
10237:     return %validations; 
10238: }
10239: 
10240: sub auto_courserequest_validation {
10241:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist,$custominfo) = @_;
10242:     my ($homeserver,$response);
10243:     if ($dom =~ /^$match_domain$/) {
10244:         $homeserver = &domain($dom,'primary');
10245:     }
10246:     unless ($homeserver eq 'no_host') {
10247:         my $customdata;
10248:         if (ref($custominfo) eq 'HASH') {
10249:             $customdata = &freeze_escape($custominfo);
10250:         }
10251:         $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
10252:                                     ':'.&escape($crstype).':'.&escape($inststatuslist).
10253:                                     ':'.&escape($instcode).':'.&escape($instseclist).':'.
10254:                                     $customdata,$homeserver));
10255:     }
10256:     return $response;
10257: }
10258: 
10259: sub auto_validate_class_sec {
10260:     my ($cdom,$cnum,$owners,$inst_class) = @_;
10261:     my $homeserver = &homeserver($cnum,$cdom);
10262:     my $ownerlist;
10263:     if (ref($owners) eq 'ARRAY') {
10264:         $ownerlist = join(',',@{$owners});
10265:     } else {
10266:         $ownerlist = $owners;
10267:     }
10268:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
10269:                         &escape($ownerlist).':'.$cdom,$homeserver);
10270:     return $response;
10271: }
10272: 
10273: sub auto_instsec_reformat {
10274:     my ($cdom,$action,$instsecref) = @_;
10275:     return unless(($action eq 'clutter') || ($action eq 'declutter'));
10276:     my @homeservers;
10277:     if (defined(&domain($cdom,'primary'))) {
10278:         push(@homeservers,&domain($cdom,'primary'));
10279:     } else {
10280:         my %servers = &get_servers($cdom,'library');
10281:         foreach my $tryserver (keys(%servers)) {
10282:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
10283:                 push(@homeservers,$tryserver);
10284:             }
10285:         }
10286:     }
10287:     my $response;
10288:     my %reformatted = %{$instsecref};
10289:     foreach my $server (@homeservers) {
10290:         if (ref($instsecref) eq 'HASH') {
10291:             my $info = &freeze_escape($instsecref);
10292:             my $response=&reply('autoinstsecreformat:'.$cdom.':'.
10293:                                 $action.':'.$info,$server);
10294:             next if ($response =~ /(con_lost|error|no_such_host|refused|unknown_command)/);
10295:             my @items = split(/&/,$response);
10296:             foreach my $item (@items) {
10297:                 my ($key,$value) = split(/=/,$item);
10298:                 $reformatted{&unescape($key)} = &thaw_unescape($value);
10299:             }
10300:         }
10301:     }
10302:     return %reformatted;
10303: }
10304: 
10305: sub auto_validate_instclasses {
10306:     my ($cdom,$cnum,$owners,$classesref) = @_;
10307:     my ($homeserver,%validations);
10308:     $homeserver = &homeserver($cnum,$cdom);
10309:     unless ($homeserver eq 'no_host') {
10310:         my $ownerlist;
10311:         if (ref($owners) eq 'ARRAY') {
10312:             $ownerlist = join(',',@{$owners});
10313:         } else {
10314:             $ownerlist = $owners;
10315:         }
10316:         if (ref($classesref) eq 'HASH') {
10317:             my $classes = &freeze_escape($classesref);
10318:             my $response=&reply('autovalidateinstclasses:'.&escape($ownerlist).
10319:                                 ':'.$cdom.':'.$classes,$homeserver);
10320:             unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
10321:                 my @items = split(/&/,$response);
10322:                 foreach my $item (@items) {
10323:                     my ($key,$value) = split('=',$item);
10324:                     $validations{&unescape($key)} = &thaw_unescape($value);
10325:                 }
10326:             }
10327:         }
10328:     }
10329:     return %validations;
10330: }
10331: 
10332: sub auto_crsreq_update {
10333:     my ($cdom,$cnum,$crstype,$action,$ownername,$ownerdomain,$fullname,$title,
10334:         $code,$accessstart,$accessend,$inbound) = @_;
10335:     my ($homeserver,%crsreqresponse);
10336:     if ($cdom =~ /^$match_domain$/) {
10337:         $homeserver = &domain($cdom,'primary');
10338:     }
10339:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
10340:         my $info;
10341:         if (ref($inbound) eq 'HASH') {
10342:             $info = &freeze_escape($inbound);
10343:         }
10344:         my $response=&reply('autocrsrequpdate:'.$cdom.':'.$cnum.':'.&escape($crstype).
10345:                             ':'.&escape($action).':'.&escape($ownername).':'.
10346:                             &escape($ownerdomain).':'.&escape($fullname).':'.
10347:                             &escape($title).':'.&escape($code).':'.
10348:                             &escape($accessstart).':'.&escape($accessend).':'.$info,
10349:                             $homeserver);
10350:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
10351:             my @items = split(/&/,$response);
10352:             foreach my $item (@items) {
10353:                 my ($key,$value) = split('=',$item);
10354:                 $crsreqresponse{&unescape($key)} = &thaw_unescape($value);
10355:             }
10356:         }
10357:     }
10358:     return \%crsreqresponse;
10359: }
10360: 
10361: sub auto_export_grades {
10362:     my ($cdom,$cnum,$inforef,$gradesref) = @_;
10363:     my ($homeserver,%exportresponse);
10364:     if ($cdom =~ /^$match_domain$/) {
10365:         $homeserver = &domain($cdom,'primary');
10366:     }
10367:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
10368:         my $info;
10369:         if (ref($inforef) eq 'HASH') {
10370:             $info = &freeze_escape($inforef);
10371:         }
10372:         if (ref($gradesref) eq 'HASH') {
10373:             my $grades = &freeze_escape($gradesref);
10374:             my $response=&reply('encrypt:autoexportgrades:'.$cdom.':'.$cnum.':'.
10375:                                 $info.':'.$grades,$homeserver);
10376:             unless ($response =~ /(con_lost|error|no_such_host|refused|unknown_command)/) {
10377:                 my @items = split(/&/,$response);
10378:                 foreach my $item (@items) {
10379:                     my ($key,$value) = split('=',$item);
10380:                     $exportresponse{&unescape($key)} = &thaw_unescape($value);
10381:                 }
10382:             }
10383:         }
10384:     }
10385:     return \%exportresponse;
10386: }
10387: 
10388: sub check_instcode_cloning {
10389:     my ($codedefaults,$code_order,$cloner,$clonefromcode,$clonetocode) = @_;
10390:     unless ((ref($codedefaults) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
10391:         return;
10392:     }
10393:     my $canclone;
10394:     if (@{$code_order} > 0) {
10395:         my $instcoderegexp ='^';
10396:         my @clonecodes = split(/\&/,$cloner);
10397:         foreach my $item (@{$code_order}) {
10398:             if (grep(/^\Q$item\E=/,@clonecodes)) {
10399:                 foreach my $pair (@clonecodes) {
10400:                     my ($key,$val) = split(/\=/,$pair,2);
10401:                     $val = &unescape($val);
10402:                     if ($key eq $item) {
10403:                         $instcoderegexp .= '('.$val.')';
10404:                         last;
10405:                     }
10406:                 }
10407:             } else {
10408:                 $instcoderegexp .= $codedefaults->{$item};
10409:             }
10410:         }
10411:         $instcoderegexp .= '$';
10412:         my (@from,@to);
10413:         eval {
10414:                (@from) = ($clonefromcode =~ /$instcoderegexp/);
10415:                (@to) = ($clonetocode =~ /$instcoderegexp/);
10416:         };
10417:         if ((@from > 0) && (@to > 0)) {
10418:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
10419:             if (!@diffs) {
10420:                 $canclone = 1;
10421:             }
10422:         }
10423:     }
10424:     return $canclone;
10425: }
10426: 
10427: sub default_instcode_cloning {
10428:     my ($clonedom,$domdefclone,$clonefromcode,$clonetocode,$codedefaultsref,$codeorderref) = @_;
10429:     my (%codedefaults,@code_order,$canclone);
10430:     if ((ref($codedefaultsref) eq 'HASH') && (ref($codeorderref) eq 'ARRAY')) {
10431:         %codedefaults = %{$codedefaultsref};
10432:         @code_order = @{$codeorderref};
10433:     } elsif ($clonedom) {
10434:         &auto_instcode_defaults($clonedom,\%codedefaults,\@code_order);
10435:     }
10436:     if (($domdefclone) && (@code_order)) {
10437:         my @clonecodes = split(/\+/,$domdefclone);
10438:         my $instcoderegexp ='^';
10439:         foreach my $item (@code_order) {
10440:             if (grep(/^\Q$item\E$/,@clonecodes)) {
10441:                 $instcoderegexp .= '('.$codedefaults{$item}.')';
10442:             } else {
10443:                 $instcoderegexp .= $codedefaults{$item};
10444:             }
10445:         }
10446:         $instcoderegexp .= '$';
10447:         my (@from,@to);
10448:         eval {
10449:             (@from) = ($clonefromcode =~ /$instcoderegexp/);
10450:             (@to) = ($clonetocode =~ /$instcoderegexp/);
10451:         };
10452:         if ((@from > 0) && (@to > 0)) {
10453:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
10454:             if (!@diffs) {
10455:                 $canclone = 1;
10456:             }
10457:         }
10458:     }
10459:     return $canclone;
10460: }
10461: 
10462: # ------------------------------------------------------- Course Group routines
10463: 
10464: sub get_coursegroups {
10465:     my ($cdom,$cnum,$group,$namespace) = @_;
10466:     return(&dump($namespace,$cdom,$cnum,$group));
10467: }
10468: 
10469: sub modify_coursegroup {
10470:     my ($cdom,$cnum,$groupsettings) = @_;
10471:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
10472: }
10473: 
10474: sub toggle_coursegroup_status {
10475:     my ($cdom,$cnum,$group,$action) = @_;
10476:     my ($from_namespace,$to_namespace);
10477:     if ($action eq 'delete') {
10478:         $from_namespace = 'coursegroups';
10479:         $to_namespace = 'deleted_groups';
10480:     } else {
10481:         $from_namespace = 'deleted_groups';
10482:         $to_namespace = 'coursegroups';
10483:     }
10484:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
10485:     if (my $tmp = &error(%curr_group)) {
10486:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
10487:         return ('read error',$tmp);
10488:     } else {
10489:         my %savedsettings = %curr_group; 
10490:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
10491:         my $deloutcome;
10492:         if ($result eq 'ok') {
10493:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
10494:         } else {
10495:             return ('write error',$result);
10496:         }
10497:         if ($deloutcome eq 'ok') {
10498:             return 'ok';
10499:         } else {
10500:             return ('delete error',$deloutcome);
10501:         }
10502:     }
10503: }
10504: 
10505: sub modify_group_roles {
10506:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context,
10507:         $othdomby,$requester) = @_;
10508:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
10509:     my $role = 'gr/'.&escape($userprivs);
10510:     my ($uname,$udom) = split(/:/,$user);
10511:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context,
10512:                              $othdomby,$requester);
10513:     if ($result eq 'ok') {
10514:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
10515:     }
10516:     return $result;
10517: }
10518: 
10519: sub modify_coursegroup_membership {
10520:     my ($cdom,$cnum,$membership) = @_;
10521:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
10522:     return $result;
10523: }
10524: 
10525: sub get_active_groups {
10526:     my ($udom,$uname,$cdom,$cnum) = @_;
10527:     my $now = time;
10528:     my %groups = ();
10529:     foreach my $key (keys(%env)) {
10530:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
10531:             my ($start,$end) = split(/\./,$env{$key});
10532:             if (($end!=0) && ($end<$now)) { next; }
10533:             if (($start!=0) && ($start>$now)) { next; }
10534:             if ($1 eq $cdom && $2 eq $cnum) {
10535:                 $groups{$3} = $env{$key} ;
10536:             }
10537:         }
10538:     }
10539:     return %groups;
10540: }
10541: 
10542: sub get_group_membership {
10543:     my ($cdom,$cnum,$group) = @_;
10544:     return(&dump('groupmembership',$cdom,$cnum,$group));
10545: }
10546: 
10547: sub get_users_groups {
10548:     my ($udom,$uname,$courseid) = @_;
10549:     my @usersgroups;
10550:     my $cachetime=1800;
10551: 
10552:     my $hashid="$udom:$uname:$courseid";
10553:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
10554:     if (defined($cached)) {
10555:         @usersgroups = split(/:/,$grouplist);
10556:     } else {  
10557:         $grouplist = '';
10558:         my $courseurl = &courseid_to_courseurl($courseid);
10559:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
10560:         my $access_end = $env{'course.'.$courseid.
10561:                               '.default_enrollment_end_date'};
10562:         my $now = time;
10563:         foreach my $key (keys(%roleshash)) {
10564:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
10565:                 my $group = $1;
10566:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
10567:                     my $start = $2;
10568:                     my $end = $1;
10569:                     if ($start == -1) { next; } # deleted from group
10570:                     if (($start!=0) && ($start>$now)) { next; }
10571:                     if (($end!=0) && ($end<$now)) {
10572:                         if ($access_end && $access_end < $now) {
10573:                             if ($access_end - $end < 86400) {
10574:                                 push(@usersgroups,$group);
10575:                             }
10576:                         }
10577:                         next;
10578:                     }
10579:                     push(@usersgroups,$group);
10580:                 }
10581:             }
10582:         }
10583:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
10584:         $grouplist = join(':',@usersgroups);
10585:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
10586:     }
10587:     return @usersgroups;
10588: }
10589: 
10590: sub devalidate_getgroups_cache {
10591:     my ($udom,$uname,$cdom,$cnum)=@_;
10592:     my $courseid = $cdom.'_'.$cnum;
10593: 
10594:     my $hashid="$udom:$uname:$courseid";
10595:     &devalidate_cache_new('getgroups',$hashid);
10596: }
10597: 
10598: # ------------------------------------------------------------------ Plain Text
10599: 
10600: sub plaintext {
10601:     my ($short,$type,$cid,$forcedefault) = @_;
10602:     if ($short =~ m{^cr/}) {
10603: 	return (split('/',$short))[-1];
10604:     }
10605:     if (!defined($cid)) {
10606:         $cid = $env{'request.course.id'};
10607:     }
10608:     my %rolenames = (
10609:                       Course    => 'std',
10610:                       Community => 'alt1',
10611:                       Placement => 'std',
10612:                     );
10613:     if ($cid ne '') {
10614:         if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
10615:             unless ($forcedefault) {
10616:                 my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
10617:                 &Apache::lonlocal::mt_escape(\$roletext);
10618:                 return &Apache::lonlocal::mt($roletext);
10619:             }
10620:         }
10621:     }
10622:     if ((defined($type)) && (defined($rolenames{$type})) &&
10623:         (defined($rolenames{$type})) && 
10624:         (defined($prp{$short}{$rolenames{$type}}))) {
10625:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
10626:     } elsif ($cid ne '') {
10627:         my $crstype = $env{'course.'.$cid.'.type'};
10628:         if (($crstype ne '') && (defined($rolenames{$crstype})) &&
10629:             (defined($prp{$short}{$rolenames{$crstype}}))) {
10630:             return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
10631:         }
10632:     }
10633:     return &Apache::lonlocal::mt($prp{$short}{'std'});
10634: }
10635: 
10636: # ----------------------------------------------------------------- Assign Role
10637: 
10638: sub assignrole {
10639:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
10640:         $context,$othdomby,$requester,$reqsec,$reqrole)=@_;
10641:     my ($mrole,$rolelogcontext);
10642:     if ($role =~ /^cr\//) {
10643:         my $cwosec=$url;
10644:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
10645:         if ((!&allowed('ccr',$cwosec)) && (!&allowed('ccr',$udom))) {
10646:             my $refused = 1;
10647:             if ($context eq 'requestcourses') {
10648:                 if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
10649:                     if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
10650:                         if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
10651:                             my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
10652:                             my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
10653:                             if ($crsenv{'internal.courseowner'} eq
10654:                                 $env{'user.name'}.':'.$env{'user.domain'}) {
10655:                                 $refused = '';
10656:                             }
10657:                         }
10658:                     }
10659:                 }
10660:             } elsif (($context eq 'course') && ($othdomby eq 'othdombyuser')) {
10661:                 my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
10662:                 my ($sec) = ($url =~ m{^/\Q$cwosec\E/(.*)$});
10663:                 my $key = "$uname:$udom:$role:$sec";
10664:                 my %queuedrolereq = &Apache::lonnet::get('nohist_othdomqueued',[$key],$cdom,$cnum);
10665:                 if ((exists($queuedrolereq{$key})) && (ref($queuedrolereq{$key}) eq 'HASH')) {
10666:                     if (($queuedrolereq{$key}{'adj'} eq 'user') && ($queuedrolereq{$key}{'requester'} eq $requester)) {
10667:                         $refused = '';
10668:                     }
10669:                 }
10670:             }
10671:             if ($refused) {
10672:                 &logthis('Refused custom assignrole: '.
10673:                          $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
10674:                          ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
10675:                 return 'refused';
10676:             }
10677:         }
10678:         $mrole='cr';
10679:     } elsif ($role =~ /^gr\//) {
10680:         my $cwogrp=$url;
10681:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
10682:         if (!&allowed('mdg',$cwogrp)) {
10683:             my $refused = 1;
10684:             if (($refused) && ($othdomby eq 'othdombyuser') && ($requester ne '') && ($reqrole ne '')) {
10685:                 my ($cdom,$cnum) = ($cwogrp =~ m{^/?($match_domain)/($match_courseid)$});
10686:                 my $key = "$uname:$udom:$reqrole:$reqsec";
10687:                 my %queuedrolereq = &Apache::lonnet::get('nohist_othdomqueued',[$key],$cdom,$cnum);
10688:                 if ((exists($queuedrolereq{$key})) && (ref($queuedrolereq{$key}) eq 'HASH')) {
10689:                     if (($queuedrolereq{$key}{'adj'} eq 'user') && ($queuedrolereq{$key}{'requester'} eq $requester)) {
10690:                         $refused = '';
10691:                     }
10692:                 }
10693:             }
10694:             if ($refused) {
10695:                 &logthis('Refused group assignrole: '.
10696:                          $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
10697:                          $env{'user.name'}.' at '.$env{'user.domain'});
10698:                 return 'refused';
10699:             }
10700:         }
10701:         $mrole='gr';
10702:     } else {
10703:         my $cwosec=$url;
10704:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
10705:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
10706:             my $refused;
10707:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
10708:                 if (!(&allowed('c'.$role,$url))) {
10709:                     $refused = 1;
10710:                 }
10711:             } else {
10712:                 $refused = 1;
10713:             }
10714:             if ($refused) {
10715:                 my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
10716:                 if (!$selfenroll && ($othdomby ne 'othdombyuser') &&
10717:                    (($context eq 'course') || ($context eq 'ltienroll' && $env{'request.lti.login'}))) {
10718:                     my %crsenv;
10719:                     if ($role eq 'cc' || $role eq 'co') {
10720:                         %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
10721:                         if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
10722:                             if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
10723:                                 if ($crsenv{'internal.courseowner'} eq 
10724:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
10725:                                     $refused = '';
10726:                                 }
10727:                             }
10728:                         } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) { 
10729:                             if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
10730:                                 if ($crsenv{'internal.courseowner'} eq 
10731:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
10732:                                     $refused = '';
10733:                                 }
10734:                             }
10735:                         }
10736:                     }
10737:                 } elsif (($selfenroll == 1) && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
10738:                     if ($role eq 'st') {
10739:                         $refused = '';
10740:                     } elsif (($context eq 'ltienroll') && ($env{'request.lti.login'})) {
10741:                         $refused = '';
10742:                     }
10743:                 } elsif ($othdomby eq 'othdombyuser') {
10744:                     my ($key,%queuedrolereq);
10745:                     if ($context eq 'course') {
10746:                         my ($sec) = ($url =~ m{^/\Q$cwosec\E/(.*)$});
10747:                         $key = "$uname:$udom:$role:$sec";
10748:                         %queuedrolereq = &Apache::lonnet::get('nohist_othdomqueued',[$key],$cdom,$cnum);
10749:                         if ((exists($queuedrolereq{$key})) && (ref($queuedrolereq{$key}) eq 'HASH')) {
10750:                             if (($queuedrolereq{$key}{'adj'} eq 'user') && ($queuedrolereq{$key}{'requester'} eq $requester)) {
10751:                                 if ((($role eq 'cc') && ($cnum !~ /^$match_community$/)) || 
10752:                                     (($role eq 'co') && ($cnum =~ /^$match_community$/))) {
10753:                                     my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
10754:                                     if ($crsenv{'internal.courseowner'} eq $requester) {
10755:                                         $refused = '';
10756:                                     }
10757:                                 } elsif ($role =~ /^(?:in|ta|ep|st)$/) {
10758:                                     $refused = '';
10759:                                 }
10760:                             }
10761:                         }
10762:                     } elsif (($context eq 'author') && ($role =~ /^ca|aa$/)) {
10763:                         my $key = "$uname:$udom:$role"; 
10764:                         my ($audom,$auname) = ($url =~ m{^/($match_domain)/($match_username)$});
10765:                         if (($audom ne '') && ($auname ne '')) {
10766:                             my %queuedrolereq = &Apache::lonnet::get('nohist_othdomqueued',[$key],$audom,$auname);
10767:                             if ((exists($queuedrolereq{$key})) && (ref($queuedrolereq{$key}) eq 'HASH')) {
10768:                                 if (($queuedrolereq{$key}{'adj'} eq 'user') && ($queuedrolereq{$key}{'requester'} eq $requester)) {
10769:                                     $refused = '';
10770:                                 }
10771:                             }
10772:                         }
10773:                     } elsif (($context eq 'domain') && ($role ne 'dc') && ($role ne 'su')) {
10774:                         my $key = "$uname:$udom:$role";
10775:                         my ($roledom) = ($url =~ m{^/($match_domain)/\Q$role\E$});
10776:                         if ($roledom ne '') {
10777:                             my $confname = $roledom.'-domainconfig';
10778:                             my %queuedrolereq = &Apache::lonnet::get('nohist_othdomqueued',[$key],$roledom,$confname);
10779:                             if ((exists($queuedrolereq{$key})) && (ref($queuedrolereq{$key}) eq 'HASH')) {
10780:                                 if (($queuedrolereq{$key}{'adj'} eq 'user') && ($queuedrolereq{$key}{'requester'} eq $requester)) {
10781:                                     $refused = '';
10782:                                 }
10783:                             }
10784:                         }
10785:                     }
10786:                 } elsif ($context eq 'requestcourses') {
10787:                     my @possroles = ('st','ta','ep','in','cc','co');
10788:                     if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
10789:                         my $wrongcc;
10790:                         if ($cnum =~ /^$match_community$/) {
10791:                             $wrongcc = 1 if ($role eq 'cc');
10792:                         } else {
10793:                             $wrongcc = 1 if ($role eq 'co');
10794:                         }
10795:                         unless ($wrongcc) {
10796:                             my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
10797:                             if ($crsenv{'internal.courseowner'} eq 
10798:                                  $env{'user.name'}.':'.$env{'user.domain'}) {
10799:                                 $refused = '';
10800:                             }
10801:                         }
10802:                     }
10803:                 } elsif ($context eq 'requestauthor') {
10804:                     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) && 
10805:                         ($url eq '/'.$udom.'/') && ($role eq 'au')) {
10806:                         if ($env{'environment.requestauthor'} eq 'automatic') {
10807:                             $refused = '';
10808:                         } else {
10809:                             my %domdefaults = &get_domain_defaults($udom);
10810:                             if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
10811:                                 my $checkbystatus;
10812:                                 if ($env{'user.adv'}) { 
10813:                                     my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
10814:                                     if ($disposition eq 'automatic') {
10815:                                         $refused = '';
10816:                                     } elsif ($disposition eq '') {
10817:                                         $checkbystatus = 1;
10818:                                     } 
10819:                                 } else {
10820:                                     $checkbystatus = 1;
10821:                                 }
10822:                                 if ($checkbystatus) {
10823:                                     if ($env{'environment.inststatus'}) {
10824:                                         my @inststatuses = split(/,/,$env{'environment.inststatus'});
10825:                                         foreach my $type (@inststatuses) {
10826:                                             if (($type ne '') &&
10827:                                                 ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
10828:                                                 $refused = '';
10829:                                             }
10830:                                         }
10831:                                     } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
10832:                                         $refused = '';
10833:                                     }
10834:                                 }
10835:                             }
10836:                         }
10837:                     }
10838:                 } elsif (($context eq 'author') && (($role eq 'ca' || $role eq 'aa'))) {
10839:                     if ($url =~ m{^/($match_domain)/($match_username)$}) {
10840:                         my ($audom,$auname) = ($1,$2);
10841:                         if ((&Apache::lonnet::allowed('v'.$role,"$audom/$auname")) &&
10842:                             ($env{"environment.internal.manager.$url"})) {
10843:                             $refused = '';
10844:                             $rolelogcontext = 'coauthor';
10845:                         }
10846:                     }
10847:                 }
10848:                 if ($refused) {
10849:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
10850:                              ' '.$role.' '.$end.' '.$start.' by '.
10851: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
10852:                     return 'refused';
10853:                 }
10854:             }
10855:         } elsif ($role eq 'au') {
10856:             if ($url ne '/'.$udom.'/') {
10857:                 &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
10858:                          ' to assign author role for '.$uname.':'.$udom.
10859:                          ' in domain: '.$url.' refused (wrong domain).');
10860:                 return 'refused';
10861:             }
10862:         }
10863:         $mrole=$role;
10864:     }
10865:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
10866:                 "$udom:$uname:$url".'_'."$mrole=$role";
10867:     if ($end) { $command.='_'.$end; }
10868:     if ($start) {
10869: 	if ($end) { 
10870:            $command.='_'.$start; 
10871:         } else {
10872:            $command.='_0_'.$start;
10873:         }
10874:     }
10875:     my $origstart = $start;
10876:     my $origend = $end;
10877:     my $delflag;
10878: # actually delete
10879:     if ($deleteflag) {
10880: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
10881: # modify command to delete the role
10882:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
10883:                 "$udom:$uname:$url".'_'."$mrole";
10884: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
10885: # set start and finish to negative values for userrolelog
10886:            $start=-1;
10887:            $end=-1;
10888:            $delflag = 1;
10889:         }
10890:     }
10891: # send command
10892:     my $answer=&reply($command,&homeserver($uname,$udom));
10893: # log new user role if status is ok
10894:     if ($answer eq 'ok') {
10895: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
10896:         if (($role eq 'cc') || ($role eq 'in') ||
10897:             ($role eq 'ep') || ($role eq 'ad') ||
10898:             ($role eq 'ta') || ($role eq 'st') ||
10899:             ($role=~/^cr/) || ($role eq 'gr') ||
10900:             ($role eq 'co')) {
10901: # for course roles, perform group memberships changes triggered by role change.
10902:             unless ($role =~ /^gr/) {
10903:                 &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
10904:                                                  $origstart,$selfenroll,$context);
10905:             }
10906:             &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
10907:                            $selfenroll,$context,$othdomby,$requester);
10908:         } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
10909:                  ($role eq 'au') || ($role eq 'dc') || ($role eq 'dh') ||
10910:                  ($role eq 'da')) {
10911:             &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
10912:                            $context,$othdomby,$requester);
10913:         } elsif (($role eq 'ca') || ($role eq 'aa')) {
10914:             if ($rolelogcontext eq '') {
10915:                 $rolelogcontext = $context;
10916:             }
10917:             &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
10918:                              $rolelogcontext,$othdomby,$requester); 
10919:         }
10920:         if ($role eq 'cc') {
10921:             &autoupdate_coowners($url,$end,$start,$uname,$udom);
10922:         }
10923:     }
10924:     return $answer;
10925: }
10926: 
10927: sub autoupdate_coowners {
10928:     my ($url,$end,$start,$uname,$udom) = @_;
10929:     my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
10930:     if (($cdom ne '') && ($cnum ne '')) {
10931:         my $now = time;
10932:         my %domdesign = &Apache::loncommon::get_domainconf($cdom);
10933:         if ($domdesign{$cdom.'.autoassign.co-owners'}) {
10934:             my %coursehash = &coursedescription($cdom.'_'.$cnum);
10935:             my $instcode = $coursehash{'internal.coursecode'};
10936:             my $xlists = $coursehash{'internal.crosslistings'};
10937:             if ($instcode ne '') {
10938:                 if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
10939:                     unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
10940:                         my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
10941:                         my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
10942:                         unless ($result eq 'valid') {
10943:                             if ($xlists ne '') {
10944:                                 foreach my $xlist (split(',',$xlists)) {
10945:                                     my ($inst_crosslist,$lcsec) = split(':',$xlist);
10946:                                     $result =
10947:                                         &auto_validate_inst_crosslist($cnum,$cdom,$instcode,
10948:                                                                       $inst_crosslist,$uname.':'.$udom);
10949:                                     last if ($result eq 'valid');
10950:                                 }
10951:                             }
10952:                         }
10953:                         if ($result eq 'valid') {
10954:                             if ($coursehash{'internal.co-owners'}) {
10955:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
10956:                                     push(@newcoowners,$coowner);
10957:                                 }
10958:                                 unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
10959:                                     push(@newcoowners,$uname.':'.$udom);
10960:                                 }
10961:                                 @newcoowners = sort(@newcoowners);
10962:                             } else {
10963:                                 push(@newcoowners,$uname.':'.$udom);
10964:                             }
10965:                         } elsif ($coursehash{'internal.co-owners'}) {
10966:                             foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
10967:                                 unless ($coowner eq $uname.':'.$udom) {
10968:                                     push(@newcoowners,$coowner);
10969:                                 }
10970:                             }
10971:                             unless (@newcoowners > 0) {
10972:                                 $delcoowners = 1;
10973:                                 $coowners = '';
10974:                             }
10975:                         }
10976:                         if (@newcoowners || $delcoowners) {
10977:                             &store_coowners($cdom,$cnum,$coursehash{'home'},
10978:                                             $delcoowners,@newcoowners);
10979:                         }
10980:                     }
10981:                 }
10982:             }
10983:         }
10984:     }
10985: }
10986: 
10987: sub store_coowners {
10988:     my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
10989:     my $cid = $cdom.'_'.$cnum;
10990:     my ($coowners,$delresult,$putresult);
10991:     if (@newcoowners) {
10992:         $coowners = join(',',@newcoowners);
10993:         my %coownershash = (
10994:                             'internal.co-owners' => $coowners,
10995:                            );
10996:         $putresult = &put('environment',\%coownershash,$cdom,$cnum);
10997:         if ($putresult eq 'ok') {
10998:             if ($env{'course.'.$cid.'.num'} eq $cnum) {
10999:                 &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
11000:             }
11001:         }
11002:     }
11003:     if ($delcoowners) {
11004:         $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
11005:         if ($delresult eq 'ok') {
11006:             if ($env{'course.'.$cid.'.internal.co-owners'}) {
11007:                 &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
11008:             }
11009:         }
11010:     }
11011:     if (($putresult eq 'ok') || ($delresult eq 'ok')) {
11012:         my %crsinfo =
11013:             &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
11014:         if (ref($crsinfo{$cid}) eq 'HASH') {
11015:             $crsinfo{$cid}{'co-owners'} = \@newcoowners;
11016:             my $cidput = &courseidput($cdom,\%crsinfo,$chome,'notime');
11017:         }
11018:     }
11019: }
11020: 
11021: # -------------------------------------------------- Modify user authentication
11022: # Overrides without validation
11023: 
11024: sub modifyuserauth {
11025:     my ($udom,$uname,$umode,$upass)=@_;
11026:     my $uhome=&homeserver($uname,$udom);
11027:     my $allowed;
11028:     if (&allowed('mau',$udom)) {
11029:         $allowed = 1;
11030:     } elsif (($umode eq 'internal') && ($udom eq $env{'user.domain'}) &&
11031:              ($env{'request.course.id'}) && (&allowed('mip',$env{'request.course.id'})) &&
11032:              (!$env{'course.'.$env{'request.course.id'}.'.internal.nopasswdchg'})) {
11033:         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
11034:         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
11035:         if (($cdom ne '') && ($cnum ne '')) {
11036:             my $is_owner = &is_course_owner($cdom,$cnum);
11037:             if ($is_owner) {
11038:                 $allowed = 1;
11039:             }
11040:         }
11041:     }
11042:     unless ($allowed) { return 'refused'; }
11043:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
11044:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
11045:              ' in domain '.$env{'request.role.domain'});  
11046:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
11047: 		     &escape($upass),$uhome);
11048:     my $ip = &get_requestor_ip();
11049:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
11050:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
11051:          '(Remote '.$ip.'): '.$reply);
11052:     &log($udom,,$uname,$uhome,
11053:         'Authentication changed by '.$env{'user.domain'}.', '.
11054:                                      $env{'user.name'}.', '.$umode.
11055:          '(Remote '.$ip.'): '.$reply);
11056:     unless ($reply eq 'ok') {
11057:         &logthis('Authentication mode error: '.$reply);
11058: 	return 'error: '.$reply;
11059:     }   
11060:     return 'ok';
11061: }
11062: 
11063: # --------------------------------------------------------------- Modify a user
11064: 
11065: sub modifyuser {
11066:     my ($udom,    $uname, $uid,
11067:         $umode,   $upass, $first,
11068:         $middle,  $last,  $gene,
11069:         $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
11070:     $udom= &LONCAPA::clean_domain($udom);
11071:     $uname=&LONCAPA::clean_username($uname);
11072:     my $showcandelete = 'none';
11073:     if (ref($candelete) eq 'ARRAY') {
11074:         if (@{$candelete} > 0) {
11075:             $showcandelete = join(', ',@{$candelete});
11076:         }
11077:     }
11078:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
11079:              $umode.', '.$first.', '.$middle.', '.
11080: 	     $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
11081:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
11082:                                      ' desiredhome not specified'). 
11083:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
11084:              ' in domain '.$env{'request.role.domain'});
11085:     my $uhome=&homeserver($uname,$udom,'true');
11086:     my $newuser;
11087:     if ($uhome eq 'no_host') {
11088:         $newuser = 1;
11089:         unless (($umode && ($upass ne '')) || ($umode eq 'localauth') ||
11090:                 ($umode eq 'lti')) {
11091:             return 'error: more information needed to create new user';
11092:         }
11093:     }
11094: # ----------------------------------------------------------------- Create User
11095:     if (($uhome eq 'no_host') && 
11096: 	(($umode && $upass) || ($umode eq 'localauth') || ($umode eq 'lti'))) {
11097:         my $unhome='';
11098:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
11099:             $unhome = $desiredhome;
11100: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
11101: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
11102:         } else { # load balancing routine for determining $unhome
11103:             my $loadm=10000000;
11104: 	    my %servers = &get_servers($udom,'library');
11105: 	    foreach my $tryserver (keys(%servers)) {
11106: 		my $answer=reply('load',$tryserver);
11107: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
11108: 		    $loadm=$answer;
11109: 		    $unhome=$tryserver;
11110: 		}
11111: 	    }
11112:         }
11113:         if (($unhome eq '') || ($unhome eq 'no_host')) {
11114: 	    return 'error: unable to find a home server for '.$uname.
11115:                    ' in domain '.$udom;
11116:         }
11117:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
11118:                          &escape($upass),$unhome);
11119: 	unless ($reply eq 'ok') {
11120:             return 'error: '.$reply;
11121:         }   
11122:         $uhome=&homeserver($uname,$udom,'true');
11123:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
11124: 	    return 'error: unable verify users home machine.';
11125:         }
11126:     }   # End of creation of new user
11127: # ---------------------------------------------------------------------- Add ID
11128:     if ($uid) {
11129:        $uid=~tr/A-Z/a-z/;
11130:        my %uidhash=&idrget($udom,$uname);
11131:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
11132:          && (!$forceid)) {
11133: 	  unless ($uid eq $uidhash{$uname}) {
11134: 	      return 'error: user id "'.$uid.'" does not match '.
11135:                   'current user id "'.$uidhash{$uname}.'".';
11136:           }
11137:        } else {
11138: 	  &idput($udom,{$uname => $uid},$uhome,'ids');
11139:        }
11140:     }
11141: # -------------------------------------------------------------- Add names, etc
11142:     my @tmp=&get('environment',
11143: 		   ['firstname','middlename','lastname','generation','id',
11144:                     'permanentemail','inststatus'],
11145: 		   $udom,$uname);
11146:     my (%names,%oldnames);
11147:     if ($tmp[0] =~ m/^error:.*/) { 
11148:         %names=(); 
11149:     } else {
11150:         %names = @tmp;
11151:         %oldnames = %names;
11152:     }
11153: #
11154: # If name, email and/or uid are blank (e.g., because an uploaded file
11155: # of users did not contain them), do not overwrite existing values
11156: # unless field is in $candelete array ref.  
11157: #
11158: 
11159:     my @fields = ('firstname','middlename','lastname','generation',
11160:                   'permanentemail','id');
11161:     my %newvalues;
11162:     if (ref($candelete) eq 'ARRAY') {
11163:         foreach my $field (@fields) {
11164:             if (grep(/^\Q$field\E$/,@{$candelete})) {
11165:                 if ($field eq 'firstname') {
11166:                     $names{$field} = $first;
11167:                 } elsif ($field eq 'middlename') {
11168:                     $names{$field} = $middle;
11169:                 } elsif ($field eq 'lastname') {
11170:                     $names{$field} = $last;
11171:                 } elsif ($field eq 'generation') { 
11172:                     $names{$field} = $gene;
11173:                 } elsif ($field eq 'permanentemail') {
11174:                     $names{$field} = $email;
11175:                 } elsif ($field eq 'id') {
11176:                     $names{$field}  = $uid;
11177:                 }
11178:             }
11179:         }
11180:     }
11181:     if ($first)  { $names{'firstname'}  = $first; }
11182:     if (defined($middle)) { $names{'middlename'} = $middle; }
11183:     if ($last)   { $names{'lastname'}   = $last; }
11184:     if (defined($gene))   { $names{'generation'} = $gene; }
11185:     if ($email) {
11186:        $email=~s/[^\w\@\.\-\,]//gs;
11187:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
11188:     }
11189:     if ($uid) { $names{'id'}  = $uid; }
11190:     if (defined($inststatus)) {
11191:         $names{'inststatus'} = '';
11192:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
11193:         if (ref($usertypes) eq 'HASH') {
11194:             my @okstatuses; 
11195:             foreach my $item (split(/:/,$inststatus)) {
11196:                 if (defined($usertypes->{$item})) {
11197:                     push(@okstatuses,$item);  
11198:                 }
11199:             }
11200:             if (@okstatuses) {
11201:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
11202:             }
11203:         }
11204:     }
11205:     my $logmsg = $udom.', '.$uname.', '.$uid.', '.
11206:                  $umode.', '.$first.', '.$middle.', '.
11207:                  $last.', '.$gene.', '.$email.', '.$inststatus;
11208:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
11209:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
11210:     } else {
11211:         $logmsg .= ' during self creation';
11212:     }
11213:     my $changed;
11214:     if ($newuser) {
11215:         $changed = 1;
11216:     } else {
11217:         foreach my $field (@fields) {
11218:             if ($names{$field} ne $oldnames{$field}) {
11219:                 $changed = 1;
11220:                 last;
11221:             }
11222:         }
11223:     }
11224:     unless ($changed) {
11225:         $logmsg = 'No changes in user information needed for: '.$logmsg;
11226:         &logthis($logmsg);
11227:         return 'ok';
11228:     }
11229:     my $reply = &put('environment', \%names, $udom,$uname);
11230:     if ($reply ne 'ok') { 
11231:         return 'error: '.$reply;
11232:     }
11233:     if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
11234:         &devalidate_cache_new('emailscache',$uname.':'.$udom);
11235:     }
11236:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
11237:     &devalidate_cache_new('namescache',$uname.':'.$udom);
11238:     $logmsg = 'Success modifying user '.$logmsg;
11239:     &logthis($logmsg);
11240:     return 'ok';
11241: }
11242: 
11243: # -------------------------------------------------------------- Modify student
11244: 
11245: sub modifystudent {
11246:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
11247:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
11248:         $selfenroll,$context,$inststatus,$credits,$instsec)=@_;
11249:     if (!$cid) {
11250: 	unless ($cid=$env{'request.course.id'}) {
11251: 	    return 'not_in_class';
11252: 	}
11253:     }
11254: # --------------------------------------------------------------- Make the user
11255:     my $reply=&modifyuser
11256: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
11257:          $desiredhome,$email,$inststatus);
11258:     unless ($reply eq 'ok') { return $reply; }
11259:     # This will cause &modify_student_enrollment to get the uid from the
11260:     # student's environment
11261:     $uid = undef if (!$forceid);
11262:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
11263:                                         $gene,$usec,$end,$start,$type,$locktype,
11264:                                         $cid,$selfenroll,$context,$credits,$instsec);
11265:     return $reply;
11266: }
11267: 
11268: sub modify_student_enrollment {
11269:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,
11270:         $locktype,$cid,$selfenroll,$context,$credits,$instsec,$othdomby,$requester) = @_;
11271:     my ($cdom,$cnum,$chome);
11272:     if (!$cid) {
11273: 	unless ($cid=$env{'request.course.id'}) {
11274: 	    return 'not_in_class';
11275: 	}
11276: 	$cdom=$env{'course.'.$cid.'.domain'};
11277: 	$cnum=$env{'course.'.$cid.'.num'};
11278:     } else {
11279: 	($cdom,$cnum)=split(/_/,$cid);
11280:     }
11281:     $chome=$env{'course.'.$cid.'.home'};
11282:     if (!$chome) {
11283: 	$chome=&homeserver($cnum,$cdom);
11284:     }
11285:     if (!$chome) { return 'unknown_course'; }
11286:     # Make sure the user exists
11287:     my $uhome=&homeserver($uname,$udom);
11288:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
11289: 	return 'error: no such user';
11290:     }
11291:     # Get student data if we were not given enough information
11292:     if (!defined($first)  || $first  eq '' || 
11293:         !defined($last)   || $last   eq '' || 
11294:         !defined($uid)    || $uid    eq '' || 
11295:         !defined($middle) || $middle eq '' || 
11296:         !defined($gene)   || $gene   eq '') {
11297:         # They did not supply us with enough data to enroll the student, so
11298:         # we need to pick up more information.
11299:         my %tmp = &get('environment',
11300:                        ['firstname','middlename','lastname', 'generation','id']
11301:                        ,$udom,$uname);
11302: 
11303:         #foreach my $key (keys(%tmp)) {
11304:         #    &logthis("key $key = ".$tmp{$key});
11305:         #}
11306:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
11307:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
11308:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
11309:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
11310:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
11311:     }
11312:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
11313:     my $user = "$uname:$udom";
11314:     my %old_entry = &get('classlist',[$user],$cdom,$cnum);
11315:     my $reply=cput('classlist',
11316: 		   {$user => 
11317: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits,$instsec) },
11318: 		   $cdom,$cnum);
11319:     if (($reply eq 'ok') || ($reply eq 'delayed')) {
11320:         &devalidate_getsection_cache($udom,$uname,$cid);
11321:     } else { 
11322: 	return 'error: '.$reply;
11323:     }
11324:     # Add student role to user
11325:     my $uurl='/'.$cid;
11326:     $uurl=~s/\_/\//g;
11327:     if ($usec) {
11328: 	$uurl.='/'.$usec;
11329:     }
11330:     my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
11331:                              $selfenroll,$context,$othdomby,$requester);
11332:     if ($result ne 'ok') {
11333:         if ($old_entry{$user} ne '') {
11334:             $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
11335:         } else {
11336:             $reply = &del('classlist',[$user],$cdom,$cnum);
11337:         }
11338:     }
11339:     return $result; 
11340: }
11341: 
11342: sub format_name {
11343:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
11344:     my $name;
11345:     if ($first ne 'lastname') {
11346: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
11347:     } else {
11348: 	if ($lastname=~/\S/) {
11349: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
11350: 	    $name=~s/\s+,/,/;
11351: 	} else {
11352: 	    $name.= $firstname.' '.$middlename.' '.$generation;
11353: 	}
11354:     }
11355:     $name=~s/^\s+//;
11356:     $name=~s/\s+$//;
11357:     $name=~s/\s+/ /g;
11358:     return $name;
11359: }
11360: 
11361: # ------------------------------------------------- Write to course preferences
11362: 
11363: sub writecoursepref {
11364:     my ($courseid,%prefs)=@_;
11365:     $courseid=~s/^\///;
11366:     $courseid=~s/\_/\//g;
11367:     my ($cdomain,$cnum)=split(/\//,$courseid);
11368:     my $chome=homeserver($cnum,$cdomain);
11369:     if (($chome eq '') || ($chome eq 'no_host')) { 
11370: 	return 'error: no such course';
11371:     }
11372:     my $cstring='';
11373:     foreach my $pref (keys(%prefs)) {
11374: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
11375:     }
11376:     $cstring=~s/\&$//;
11377:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
11378: }
11379: 
11380: # ---------------------------------------------------------- Make/modify course
11381: 
11382: sub createcourse {
11383:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
11384:         $course_owner,$crstype,$cnum,$context,$category,$callercontext)=@_;
11385:     $url=&declutter($url);
11386:     my $cid='';
11387:     if ($context eq 'requestcourses') {
11388:         my $can_create = 0;
11389:         my ($ownername,$ownerdom) = split(':',$course_owner);
11390:         if ($udom eq $ownerdom) {
11391:             my $reload;
11392:             if (($callercontext eq 'auto') &&
11393:                ($ownerdom eq $env{'user.domain'}) && ($ownername eq $env{'user.name'})) {
11394:                 $reload = 'reload';
11395:             }
11396:             if (&usertools_access($ownername,$ownerdom,$category,$reload,
11397:                                   $context)) {
11398:                 $can_create = 1;
11399:             }
11400:         } else {
11401:             my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
11402:                                            $category);
11403:             if ($userenv{'reqcrsotherdom.'.$category} ne '') {
11404:                 my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
11405:                 if (@curr > 0) {
11406:                     my @options = qw(approval validate autolimit);
11407:                     my $optregex = join('|',@options);
11408:                     if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
11409:                         $can_create = 1;
11410:                     }
11411:                 }
11412:             }
11413:         }
11414:         if ($can_create) {
11415:             unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
11416:                 unless (&allowed('ccc',$udom)) {
11417:                     return 'refused'; 
11418:                 }
11419:             }
11420:         } else {
11421:             return 'refused';
11422:         }
11423:     } elsif (!&allowed('ccc',$udom)) {
11424:         return 'refused';
11425:     }
11426: # --------------------------------------------------------------- Get Unique ID
11427:     my $uname;
11428:     if ($cnum =~ /^$match_courseid$/) {
11429:         my $chome=&homeserver($cnum,$udom,'true');
11430:         if (($chome eq '') || ($chome eq 'no_host')) {
11431:             $uname = $cnum;
11432:         } else {
11433:             $uname = &generate_coursenum($udom,$crstype);
11434:         }
11435:     } else {
11436:         $uname = &generate_coursenum($udom,$crstype);
11437:     }
11438:     return $uname if ($uname =~ /^error/);
11439: # -------------------------------------------------- Check supplied server name
11440:     if (!defined($course_server)) {
11441:         if (defined(&domain($udom,'primary'))) {
11442:             $course_server = &domain($udom,'primary');
11443:         } else {
11444:             $course_server = $env{'user.home'}; 
11445:         }
11446:     }
11447:     my %host_servers =
11448:         &get_servers($udom,'library');
11449:     unless ($host_servers{$course_server}) {
11450:         return 'error: invalid home server for course: '.$course_server;
11451:     }
11452: # ------------------------------------------------------------- Make the course
11453:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
11454:                       $course_server);
11455:     unless ($reply eq 'ok') { return 'error: '.$reply; }
11456:     my $uhome=&homeserver($uname,$udom,'true');
11457:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
11458: 	return 'error: no such course';
11459:     }
11460: # ----------------------------------------------------------------- Course made
11461: # log existence
11462:     my $now = time;
11463:     my $newcourse = {
11464:                     $udom.'_'.$uname => {
11465:                                      description => $description,
11466:                                      inst_code   => $inst_code,
11467:                                      owner       => $course_owner,
11468:                                      type        => $crstype,
11469:                                      creator     => $env{'user.name'}.':'.
11470:                                                     $env{'user.domain'},
11471:                                      created     => $now,
11472:                                      context     => $context,
11473:                                                 },
11474:                     };
11475:     &courseidput($udom,$newcourse,$uhome,'notime');
11476: # set toplevel url
11477:     my $topurl=$url;
11478:     unless ($nonstandard) {
11479: # ------------------------------------------ For standard courses, make top url
11480:         my $mapurl=&clutter($url);
11481:         if ($mapurl eq '/res/') { $mapurl=''; }
11482:         $env{'form.initmap'}=(<<ENDINITMAP);
11483: <map>
11484: <resource id="1" type="start"></resource>
11485: <resource id="2" src="$mapurl"></resource>
11486: <resource id="3" type="finish"></resource>
11487: <link index="1" from="1" to="2"></link>
11488: <link index="2" from="2" to="3"></link>
11489: </map>
11490: ENDINITMAP
11491:         $topurl=&declutter(
11492:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
11493:                           );
11494:     }
11495: # ----------------------------------------------------------- Write preferences
11496:     &writecoursepref($udom.'_'.$uname,
11497:                      ('description'              => $description,
11498:                       'url'                      => $topurl,
11499:                       'internal.creator'         => $env{'user.name'}.':'.
11500:                                                     $env{'user.domain'},
11501:                       'internal.created'         => $now,
11502:                       'internal.creationcontext' => $context)
11503:                     );
11504:     return '/'.$udom.'/'.$uname;
11505: }
11506: 
11507: # ------------------------------------------------------------------- Create ID
11508: sub generate_coursenum {
11509:     my ($udom,$crstype) = @_;
11510:     my $domdesc = &domain($udom);
11511:     return 'error: invalid domain' if ($domdesc eq '');
11512:     my $first;
11513:     if ($crstype eq 'Community') {
11514:         $first = '0';
11515:     } else {
11516:         $first = int(1+rand(9)); 
11517:     } 
11518:     my $uname=$first.
11519:         ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
11520:         substr($$.time,0,5).unpack("H8",pack("I32",time)).
11521:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
11522: # ----------------------------------------------- Make sure that does not exist
11523:     my $uhome=&homeserver($uname,$udom,'true');
11524:     unless (($uhome eq '') || ($uhome eq 'no_host')) {
11525:         if ($crstype eq 'Community') {
11526:             $first = '0';
11527:         } else {
11528:             $first = int(1+rand(9));
11529:         }
11530:         $uname=$first.
11531:                ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
11532:                substr($$.time,0,5).unpack("H8",pack("I32",time)).
11533:                unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
11534:         $uhome=&homeserver($uname,$udom,'true');
11535:         unless (($uhome eq '') || ($uhome eq 'no_host')) {
11536:             return 'error: unable to generate unique course-ID';
11537:         }
11538:     }
11539:     return $uname;
11540: }
11541: 
11542: sub is_course {
11543:     my ($cdom, $cnum) = scalar(@_) == 1 ? 
11544:          ($_[0] =~ /^($match_domain)_($match_courseid)$/)  :  @_;
11545: 
11546:     return unless (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/));
11547:     my $uhome=&homeserver($cnum,$cdom);
11548:     my $iscourse;
11549:     if (grep { $_ eq $uhome } current_machine_ids()) {
11550:         $iscourse = &LONCAPA::Lond::is_course($cdom,$cnum);
11551:     } else {
11552:         my $hashid = $cdom.':'.$cnum;
11553:         ($iscourse,my $cached) = &is_cached_new('iscourse',$hashid);
11554:         unless (defined($cached)) {
11555:             my %courses = &courseiddump($cdom, '.', 1, '.', '.',
11556:                                         $cnum,undef,undef,'.');
11557:             $iscourse = 0;
11558:             if (exists($courses{$cdom.'_'.$cnum})) {
11559:                 $iscourse = 1;
11560:             }
11561:             &do_cache_new('iscourse',$hashid,$iscourse,3600);
11562:         }
11563:     }
11564:     return unless ($iscourse);
11565:     return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
11566: }
11567: 
11568: sub store_userdata {
11569:     my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
11570:     my $result;
11571:     if ($datakey ne '') {
11572:         if (ref($storehash) eq 'HASH') {
11573:             if ($udom eq '' || $uname eq '') {
11574:                 $udom = $env{'user.domain'};
11575:                 $uname = $env{'user.name'};
11576:             }
11577:             my $uhome=&homeserver($uname,$udom);
11578:             if (($uhome eq '') || ($uhome eq 'no_host')) {
11579:                 $result = 'error: no_host';
11580:             } else {
11581:                 $storehash->{'ip'} = &get_requestor_ip();
11582:                 $storehash->{'host'} = $perlvar{'lonHostID'};
11583: 
11584:                 my $namevalue='';
11585:                 foreach my $key (keys(%{$storehash})) {
11586:                     $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
11587:                 }
11588:                 $namevalue=~s/\&$//;
11589:                 unless ($namespace eq 'courserequests') {
11590:                     $datakey = &escape($datakey);
11591:                 }
11592:                 $result =  &reply("store:$udom:$uname:$namespace:$datakey:".
11593:                                   $namevalue,$uhome);
11594:             }
11595:         } else {
11596:             $result = 'error: data to store was not a hash reference'; 
11597:         }
11598:     } else {
11599:         $result= 'error: invalid requestkey'; 
11600:     }
11601:     return $result;
11602: }
11603: 
11604: # ---------------------------------------------------------- Assign Custom Role
11605: 
11606: sub assigncustomrole {
11607:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,
11608:         $selfenroll,$context,$othdomby,$requester)=@_;
11609:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
11610:                        $end,$start,$deleteflag,$selfenroll,$context,$othdomby,
11611:                        $requester);
11612: }
11613: 
11614: # ----------------------------------------------------------------- Revoke Role
11615: 
11616: sub revokerole {
11617:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
11618:     my $now=time;
11619:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
11620: }
11621: 
11622: # ---------------------------------------------------------- Revoke Custom Role
11623: 
11624: sub revokecustomrole {
11625:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
11626:     my $now=time;
11627:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
11628:            $deleteflag,$selfenroll,$context);
11629: }
11630: 
11631: # ------------------------------------------------------------ Disk usage
11632: sub diskusage {
11633:     my ($udom,$uname,$directorypath,$getpropath)=@_;
11634:     $directorypath =~ s/\/$//;
11635:     my $listing=&reply('du2:'.&escape($directorypath).':'
11636:                        .&escape($getpropath).':'.&escape($uname).':'
11637:                        .&escape($udom),homeserver($uname,$udom));
11638:     if ($listing eq 'unknown_cmd') {
11639:         if ($getpropath) {
11640:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
11641:         }
11642:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
11643:     }
11644:     return $listing;
11645: }
11646: 
11647: sub is_locked {
11648:     my ($file_name, $domain, $user, $which) = @_;
11649:     my @check;
11650:     my $is_locked;
11651:     push (@check,$file_name);
11652:     my %locked = &get('file_permissions',\@check,
11653: 		      $env{'user.domain'},$env{'user.name'});
11654:     my ($tmp)=keys(%locked);
11655:     if ($tmp=~/^error:/) { undef(%locked); }
11656:     
11657:     if (ref($locked{$file_name}) eq 'ARRAY') {
11658:         $is_locked = 'false';
11659:         foreach my $entry (@{$locked{$file_name}}) {
11660:            if (ref($entry) eq 'ARRAY') {
11661:                $is_locked = 'true';
11662:                if (ref($which) eq 'ARRAY') {
11663:                    push(@{$which},$entry);
11664:                } else {
11665:                    last;
11666:                }
11667:            }
11668:        }
11669:     } else {
11670:         $is_locked = 'false';
11671:     }
11672:     return $is_locked;
11673: }
11674: 
11675: sub declutter_portfile {
11676:     my ($file) = @_;
11677:     $file =~ s{^(/portfolio/|portfolio/)}{/};
11678:     return $file;
11679: }
11680: 
11681: # ------------------------------------------------------------- Mark as Read Only
11682: 
11683: sub mark_as_readonly {
11684:     my ($domain,$user,$files,$what) = @_;
11685:     my %current_permissions = &dump('file_permissions',$domain,$user);
11686:     my ($tmp)=keys(%current_permissions);
11687:     if ($tmp=~/^error:/) { undef(%current_permissions); }
11688:     foreach my $file (@{$files}) {
11689: 	$file = &declutter_portfile($file);
11690:         push(@{$current_permissions{$file}},$what);
11691:     }
11692:     &put('file_permissions',\%current_permissions,$domain,$user);
11693:     return;
11694: }
11695: 
11696: # ------------------------------------------------------------Save Selected Files
11697: 
11698: sub save_selected_files {
11699:     my ($user, $path, @files) = @_;
11700:     my $filename = $user."savedfiles";
11701:     my @other_files = &files_not_in_path($user, $path);
11702:     open (OUT,'>',LONCAPA::tempdir().$filename);
11703:     foreach my $file (@files) {
11704:         print (OUT $env{'form.currentpath'}.$file."\n");
11705:     }
11706:     foreach my $file (@other_files) {
11707:         print (OUT $file."\n");
11708:     }
11709:     close (OUT);
11710:     return 'ok';
11711: }
11712: 
11713: sub clear_selected_files {
11714:     my ($user) = @_;
11715:     my $filename = $user."savedfiles";
11716:     open (OUT,'>',LONCAPA::tempdir().$filename);
11717:     print (OUT undef);
11718:     close (OUT);
11719:     return ("ok");    
11720: }
11721: 
11722: sub files_in_path {
11723:     my ($user, $path) = @_;
11724:     my $filename = $user."savedfiles";
11725:     my %return_files;
11726:     open (IN,'<',LONCAPA::tempdir().$filename);
11727:     while (my $line_in = <IN>) {
11728:         chomp ($line_in);
11729:         my @paths_and_file = split (m!/!, $line_in);
11730:         my $file_part = pop (@paths_and_file);
11731:         my $path_part = join ('/', @paths_and_file);
11732:         $path_part.='/';
11733:         my $path_and_file = $path_part.$file_part;
11734:         if ($path_part eq $path) {
11735:             $return_files{$file_part}= 'selected';
11736:         }
11737:     }
11738:     close (IN);
11739:     return (\%return_files);
11740: }
11741: 
11742: # called in portfolio select mode, to show files selected NOT in current directory
11743: sub files_not_in_path {
11744:     my ($user, $path) = @_;
11745:     my $filename = $user."savedfiles";
11746:     my @return_files;
11747:     my $path_part;
11748:     open(IN, '<',LONCAPA::tempdir().$filename);
11749:     while (my $line = <IN>) {
11750:         #ok, I know it's clunky, but I want it to work
11751:         my @paths_and_file = split(m|/|, $line);
11752:         my $file_part = pop(@paths_and_file);
11753:         chomp($file_part);
11754:         my $path_part = join('/', @paths_and_file);
11755:         $path_part .= '/';
11756:         my $path_and_file = $path_part.$file_part;
11757:         if ($path_part ne $path) {
11758:             push(@return_files, ($path_and_file));
11759:         }
11760:     }
11761:     close(OUT);
11762:     return (@return_files);
11763: }
11764: 
11765: #------------------------------Submitted/Handedback Portfolio Files Versioning
11766:  
11767: sub portfiles_versioning {
11768:     my ($symb,$domain,$stu_name,$portfiles,$versioned_portfiles) = @_;
11769:     my $portfolio_root = '/userfiles/portfolio';
11770:     return unless ((ref($portfiles) eq 'ARRAY') && (ref($versioned_portfiles) eq 'ARRAY'));
11771:     foreach my $file (@{$portfiles}) {
11772:         &unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
11773:         my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
11774:         my ($answer_name,$answer_ver,$answer_ext) = &file_name_version_ext($answer_file);
11775:         my $getpropath = 1;
11776:         my ($dir_list,$listerror) = &dirlist($portfolio_root.$directory,$domain,
11777:                                              $stu_name,$getpropath);
11778:         my $version = &get_next_version($answer_name,$answer_ext,$dir_list);
11779:         my $new_answer = 
11780:             &version_selected_portfile($domain,$stu_name,$directory,$answer_file,$version);
11781:         if ($new_answer ne 'problem getting file') {
11782:             push(@{$versioned_portfiles}, $directory.$new_answer);
11783:             &mark_as_readonly($domain,$stu_name,[$directory.$new_answer],
11784:                               [$symb,$env{'request.course.id'},'graded']);
11785:         }
11786:     }
11787: }
11788: 
11789: sub get_next_version {
11790:     my ($answer_name, $answer_ext, $dir_list) = @_;
11791:     my $version;
11792:     if (ref($dir_list) eq 'ARRAY') {
11793:         foreach my $row (@{$dir_list}) {
11794:             my ($file) = split(/\&/,$row,2);
11795:             my ($file_name,$file_version,$file_ext) =
11796:                 &file_name_version_ext($file);
11797:             if (($file_name eq $answer_name) &&
11798:                 ($file_ext eq $answer_ext)) {
11799:                      # gets here if filename and extension match,
11800:                      # regardless of version
11801:                 if ($file_version ne '') {
11802:                     # a versioned file is found  so save it for later
11803:                     if ($file_version > $version) {
11804:                         $version = $file_version;
11805:                     }
11806:                 }
11807:             }
11808:         }
11809:     }
11810:     $version ++;
11811:     return($version);
11812: }
11813: 
11814: sub version_selected_portfile {
11815:     my ($domain,$stu_name,$directory,$file_name,$version) = @_;
11816:     my ($answer_name,$answer_ver,$answer_ext) =
11817:         &file_name_version_ext($file_name);
11818:     my $new_answer;
11819:     $env{'form.copy'} =
11820:         &getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
11821:     if($env{'form.copy'} eq '-1') {
11822:         $new_answer = 'problem getting file';
11823:     } else {
11824:         $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
11825:         my $copy_result = 
11826:             &finishuserfileupload($stu_name,$domain,'copy',
11827:                                   '/portfolio'.$directory.$new_answer);
11828:     }
11829:     undef($env{'form.copy'});
11830:     return ($new_answer);
11831: }
11832: 
11833: sub file_name_version_ext {
11834:     my ($file)=@_;
11835:     my @file_parts = split(/\./, $file);
11836:     my ($name,$version,$ext);
11837:     if (@file_parts > 1) {
11838:         $ext=pop(@file_parts);
11839:         if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
11840:             $version=pop(@file_parts);
11841:         }
11842:         $name=join('.',@file_parts);
11843:     } else {
11844:         $name=join('.',@file_parts);
11845:     }
11846:     return($name,$version,$ext);
11847: }
11848: 
11849: #----------------------------------------------Get portfolio file permissions
11850: 
11851: sub get_portfile_permissions {
11852:     my ($domain,$user) = @_;
11853:     my %current_permissions = &dump('file_permissions',$domain,$user);
11854:     my ($tmp)=keys(%current_permissions);
11855:     if ($tmp=~/^error:/) { undef(%current_permissions); }
11856:     return \%current_permissions;
11857: }
11858: 
11859: #---------------------------------------------Get portfolio file access controls
11860: 
11861: sub get_access_controls {
11862:     my ($current_permissions,$group,$file) = @_;
11863:     my %access;
11864:     my $real_file = $file;
11865:     $file =~ s/\.meta$//;
11866:     if (defined($file)) {
11867:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
11868:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
11869:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
11870:             }
11871:         }
11872:     } else {
11873:         foreach my $key (keys(%{$current_permissions})) {
11874:             if ($key =~ /\0accesscontrol$/) {
11875:                 if (defined($group)) {
11876:                     if ($key !~ m-^\Q$group\E/-) {
11877:                         next;
11878:                     }
11879:                 }
11880:                 my ($fullpath) = split(/\0/,$key);
11881:                 if (ref($$current_permissions{$key}) eq 'HASH') {
11882:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
11883:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
11884:                     }
11885:                 }
11886:             }
11887:         }
11888:     }
11889:     return %access;
11890: }
11891: 
11892: sub modify_access_controls {
11893:     my ($file_name,$changes,$domain,$user)=@_;
11894:     my ($outcome,$deloutcome);
11895:     my %store_permissions;
11896:     my %new_values;
11897:     my %new_control;
11898:     my %translation;
11899:     my @deletions = ();
11900:     my $now = time;
11901:     if (exists($$changes{'activate'})) {
11902:         if (ref($$changes{'activate'}) eq 'HASH') {
11903:             my @newitems = sort(keys(%{$$changes{'activate'}}));
11904:             my $numnew = scalar(@newitems);
11905:             for (my $i=0; $i<$numnew; $i++) {
11906:                 my $newkey = $newitems[$i];
11907:                 my $newid = &Apache::loncommon::get_cgi_id();
11908:                 if ($newkey =~ /^\d+:/) { 
11909:                     $newkey =~ s/^(\d+)/$newid/;
11910:                     $translation{$1} = $newid;
11911:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
11912:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
11913:                     $translation{$1} = $newid;
11914:                 }
11915:                 $new_values{$file_name."\0".$newkey} = 
11916:                                           $$changes{'activate'}{$newitems[$i]};
11917:                 $new_control{$newkey} = $now;
11918:             }
11919:         }
11920:     }
11921:     my %todelete;
11922:     my %changed_items;
11923:     foreach my $action ('delete','update') {
11924:         if (exists($$changes{$action})) {
11925:             if (ref($$changes{$action}) eq 'HASH') {
11926:                 foreach my $key (keys(%{$$changes{$action}})) {
11927:                     my ($itemnum) = ($key =~ /^([^:]+):/);
11928:                     if ($action eq 'delete') { 
11929:                         $todelete{$itemnum} = 1;
11930:                     } else {
11931:                         $changed_items{$itemnum} = $key;
11932:                     }
11933:                 }
11934:             }
11935:         }
11936:     }
11937:     # get lock on access controls for file.
11938:     my $lockhash = {
11939:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
11940:                                                        ':'.$env{'user.domain'},
11941:                    }; 
11942:     my $tries = 0;
11943:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
11944:    
11945:     while (($gotlock ne 'ok') && $tries < 10) {
11946:         $tries ++;
11947:         sleep(0.1);
11948:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
11949:     }
11950:     if ($gotlock eq 'ok') {
11951:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
11952:         my ($tmp)=keys(%curr_permissions);
11953:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
11954:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
11955:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
11956:             if (ref($curr_controls) eq 'HASH') {
11957:                 foreach my $control_item (keys(%{$curr_controls})) {
11958:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
11959:                     if (defined($todelete{$itemnum})) {
11960:                         push(@deletions,$file_name."\0".$control_item);
11961:                     } else {
11962:                         if (defined($changed_items{$itemnum})) {
11963:                             $new_control{$changed_items{$itemnum}} = $now;
11964:                             push(@deletions,$file_name."\0".$control_item);
11965:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
11966:                         } else {
11967:                             $new_control{$control_item} = $$curr_controls{$control_item};
11968:                         }
11969:                     }
11970:                 }
11971:             }
11972:         }
11973:         my ($group);
11974:         if (&is_course($domain,$user)) {
11975:             ($group,my $file) = split(/\//,$file_name,2);
11976:         }
11977:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
11978:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
11979:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
11980:         #  remove lock
11981:         my @del_lock = ($file_name."\0".'locked_access_records');
11982:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
11983:         my $sqlresult =
11984:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
11985:                                     $group);
11986:     } else {
11987:         $outcome = "error: could not obtain lockfile\n";  
11988:     }
11989:     return ($outcome,$deloutcome,\%new_values,\%translation);
11990: }
11991: 
11992: sub make_public_indefinitely {
11993:     my (@requrl) = @_;
11994:     return &automated_portfile_access('public',\@requrl);
11995: }
11996: 
11997: sub automated_portfile_access {
11998:     my ($accesstype,$addsref,$delsref,$info) = @_;
11999:     unless (($accesstype eq 'public') || ($accesstype eq 'ip')) {
12000:         return 'invalid';
12001:     }
12002:     my %urls;
12003:     if (ref($addsref) eq 'ARRAY') {
12004:         foreach my $requrl (@{$addsref}) {
12005:             if (&is_portfolio_url($requrl)) {
12006:                 unless (exists($urls{$requrl})) {
12007:                     $urls{$requrl} = 'add';
12008:                 }
12009:             }
12010:         }
12011:     }
12012:     if (ref($delsref) eq 'ARRAY') {
12013:         foreach my $requrl (@{$delsref}) { 
12014:             if (&is_portfolio_url($requrl)) {
12015:                 unless (exists($urls{$requrl})) {
12016:                     $urls{$requrl} = 'delete'; 
12017:                 }
12018:             }
12019:         }
12020:     }
12021:     unless (keys(%urls)) {
12022:         return 'invalid';
12023:     }
12024:     my $ip;
12025:     if ($accesstype eq 'ip') {
12026:         if (ref($info) eq 'HASH') {
12027:             if ($info->{'ip'} ne '') {
12028:                 $ip = $info->{'ip'};
12029:             }
12030:         }
12031:         if ($ip eq '') {
12032:             return 'invalid';
12033:         }
12034:     }
12035:     my $errors;
12036:     my $now = time;
12037:     my %current_perms;
12038:     foreach my $requrl (sort(keys(%urls))) {
12039:         my $action;
12040:         if ($urls{$requrl} eq 'add') {
12041:             $action = 'activate';
12042:         } else {
12043:             $action = 'none';
12044:         }
12045:         my $aclnum = 0;
12046:         my (undef,$udom,$unum,$file_name,$group) =
12047:             &parse_portfolio_url($requrl);
12048:         unless (exists($current_perms{$unum.':'.$udom})) {
12049:             $current_perms{$unum.':'.$udom} = &get_portfile_permissions($udom,$unum);
12050:         }
12051:         my %access_controls = &get_access_controls($current_perms{$unum.':'.$udom},
12052:                                                    $group,$file_name);
12053:         foreach my $key (keys(%{$access_controls{$file_name}})) {
12054:             my ($num,$scope,$end,$start) = 
12055:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
12056:             if ($scope eq $accesstype) {
12057:                 if (($start <= $now) && ($end == 0)) {
12058:                     if ($accesstype eq 'ip') {
12059:                         if (ref($access_controls{$file_name}{$key}) eq 'HASH') {
12060:                             if (ref($access_controls{$file_name}{$key}{'ip'}) eq 'ARRAY') {
12061:                                 if (grep(/^\Q$ip\E$/,@{$access_controls{$file_name}{$key}{'ip'}})) {
12062:                                     if ($urls{$requrl} eq 'add') {
12063:                                         $action = 'none';
12064:                                         last;
12065:                                     } else {
12066:                                         $action = 'delete';
12067:                                         $aclnum = $num;
12068:                                         last;
12069:                                     }
12070:                                 }
12071:                             }
12072:                         }
12073:                     } elsif ($accesstype eq 'public') {
12074:                         if ($urls{$requrl} eq 'add') {
12075:                             $action = 'none';
12076:                             last;
12077:                         } else {
12078:                             $action = 'delete';
12079:                             $aclnum = $num;
12080:                             last;
12081:                         }
12082:                     }
12083:                 } elsif ($accesstype eq 'public') {
12084:                     $action = 'update';
12085:                     $aclnum = $num;
12086:                     last;
12087:                 }
12088:             }
12089:         }
12090:         if ($action eq 'none') {
12091:             next;
12092:         } else {
12093:             my %changes;
12094:             my $newend = 0;
12095:             my $newstart = $now;
12096:             my $newkey = $aclnum.':'.$accesstype.'_'.$newend.'_'.$newstart;
12097:             $changes{$action}{$newkey} = {
12098:                 type => $accesstype,
12099:                 time => {
12100:                     start => $newstart,
12101:                     end   => $newend,
12102:                 },
12103:             };
12104:             if ($accesstype eq 'ip') {
12105:                 $changes{$action}{$newkey}{'ip'} = [$ip];
12106:             }
12107:             my ($outcome,$deloutcome,$new_values,$translation) =
12108:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
12109:             unless ($outcome eq 'ok') {
12110:                 $errors .= $outcome.' ';
12111:             }
12112:         }
12113:     }
12114:     if ($errors) {
12115:         $errors =~ s/\s$//;
12116:         return $errors;
12117:     } else {
12118:         return 'ok';
12119:     }
12120: }
12121: 
12122: #------------------------------------------------------Get Marked as Read Only
12123: 
12124: sub get_marked_as_readonly {
12125:     my ($domain,$user,$what,$group) = @_;
12126:     my $current_permissions = &get_portfile_permissions($domain,$user);
12127:     my @readonly_files;
12128:     my $cmp1=$what;
12129:     if (ref($what)) { $cmp1=join('',@{$what}) };
12130:     while (my ($file_name,$value) = each(%{$current_permissions})) {
12131:         if (defined($group)) {
12132:             if ($file_name !~ m-^\Q$group\E/-) {
12133:                 next;
12134:             }
12135:         }
12136:         if (ref($value) eq "ARRAY"){
12137:             foreach my $stored_what (@{$value}) {
12138:                 my $cmp2=$stored_what;
12139:                 if (ref($stored_what) eq 'ARRAY') {
12140:                     $cmp2=join('',@{$stored_what});
12141:                 }
12142:                 if ($cmp1 eq $cmp2) {
12143:                     push(@readonly_files, $file_name);
12144:                     last;
12145:                 } elsif (!defined($what)) {
12146:                     push(@readonly_files, $file_name);
12147:                     last;
12148:                 }
12149:             }
12150:         }
12151:     }
12152:     return @readonly_files;
12153: }
12154: #-----------------------------------------------------------Get Marked as Read Only Hash
12155: 
12156: sub get_marked_as_readonly_hash {
12157:     my ($current_permissions,$group,$what) = @_;
12158:     my %readonly_files;
12159:     while (my ($file_name,$value) = each(%{$current_permissions})) {
12160:         if (defined($group)) {
12161:             if ($file_name !~ m-^\Q$group\E/-) {
12162:                 next;
12163:             }
12164:         }
12165:         if (ref($value) eq "ARRAY"){
12166:             foreach my $stored_what (@{$value}) {
12167:                 if (ref($stored_what) eq 'ARRAY') {
12168:                     foreach my $lock_descriptor(@{$stored_what}) {
12169:                         if ($lock_descriptor eq 'graded') {
12170:                             $readonly_files{$file_name} = 'graded';
12171:                         } elsif ($lock_descriptor eq 'handback') {
12172:                             $readonly_files{$file_name} = 'handback';
12173:                         } else {
12174:                             if (!exists($readonly_files{$file_name})) {
12175:                                 $readonly_files{$file_name} = 'locked';
12176:                             }
12177:                         }
12178:                     }
12179:                 } 
12180:             }
12181:         } 
12182:     }
12183:     return %readonly_files;
12184: }
12185: # ------------------------------------------------------------ Unmark as Read Only
12186: 
12187: sub unmark_as_readonly {
12188:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
12189:     # for portfolio submissions, $what contains [$symb,$crsid] 
12190:     my ($domain,$user,$what,$file_name,$group) = @_;
12191:     $file_name = &declutter_portfile($file_name);
12192:     my $symb_crs = $what;
12193:     if (ref($what)) { $symb_crs=join('',@$what); }
12194:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
12195:     my ($tmp)=keys(%current_permissions);
12196:     if ($tmp=~/^error:/) { undef(%current_permissions); }
12197:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
12198:     foreach my $file (@readonly_files) {
12199: 	my $clean_file = &declutter_portfile($file);
12200: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
12201: 	my $current_locks = $current_permissions{$file};
12202:         my @new_locks;
12203:         my @del_keys;
12204:         if (ref($current_locks) eq "ARRAY"){
12205:             foreach my $locker (@{$current_locks}) {
12206:                 my $compare=$locker;
12207:                 if (ref($locker) eq 'ARRAY') {
12208:                     $compare=join('',@{$locker});
12209:                     if ($compare ne $symb_crs) {
12210:                         push(@new_locks, $locker);
12211:                     }
12212:                 }
12213:             }
12214:             if (scalar(@new_locks) > 0) {
12215:                 $current_permissions{$file} = \@new_locks;
12216:             } else {
12217:                 push(@del_keys, $file);
12218:                 &del('file_permissions',\@del_keys, $domain, $user);
12219:                 delete($current_permissions{$file});
12220:             }
12221:         }
12222:     }
12223:     &put('file_permissions',\%current_permissions,$domain,$user);
12224:     return;
12225: }
12226: 
12227: # ------------------------------------------------------------ Directory lister
12228: 
12229: sub dirlist {
12230:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
12231:     $uri=~s/^\///;
12232:     $uri=~s/\/$//;
12233:     my ($udom, $uname);
12234:     if ($getuserdir) {
12235:         $udom = $userdomain;
12236:         $uname = $username;
12237:     } else {
12238:         (undef,$udom,$uname)=split(/\//,$uri);
12239:         if(defined($userdomain)) {
12240:             $udom = $userdomain;
12241:         }
12242:         if(defined($username)) {
12243:             $uname = $username;
12244:         }
12245:     }
12246:     my ($dirRoot,$listing,@listing_results);
12247: 
12248:     $dirRoot = $perlvar{'lonDocRoot'};
12249:     if (defined($getpropath)) {
12250:         $dirRoot = &propath($udom,$uname);
12251:         $dirRoot =~ s/\/$//;
12252:     } elsif (defined($getuserdir)) {
12253:         my $subdir=$uname.'__';
12254:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
12255:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
12256:                    ."/$udom/$subdir/$uname";
12257:     } elsif (defined($alternateRoot)) {
12258:         $dirRoot = $alternateRoot;
12259:     }
12260: 
12261:     if($udom) {
12262:         if($uname) {
12263:             my $uhome = &homeserver($uname,$udom);
12264:             if ($uhome eq 'no_host') {
12265:                 return ([],'no_host');
12266:             }
12267:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
12268:                               .$getuserdir.':'.&escape($dirRoot)
12269:                               .':'.&escape($uname).':'.&escape($udom),$uhome);
12270:             if ($listing eq 'unknown_cmd') {
12271:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
12272:             } else {
12273:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
12274:             }
12275:             if ($listing eq 'unknown_cmd') {
12276:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
12277:                 @listing_results = split(/:/,$listing);
12278:             } else {
12279:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
12280:             }
12281:             if (($listing eq 'no_such_host') || ($listing eq 'con_lost') || 
12282:                 ($listing eq 'rejected') || ($listing eq 'refused') ||
12283:                 ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
12284:                 return ([],$listing);
12285:             } else {
12286:                 return (\@listing_results);
12287:             }
12288:         } elsif(!$alternateRoot) {
12289:             my (%allusers,%listerror);
12290: 	    my %servers = &get_servers($udom,'library');
12291:  	    foreach my $tryserver (keys(%servers)) {
12292:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
12293:                                   &escape($udom),$tryserver);
12294:                 if ($listing eq 'unknown_cmd') {
12295: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
12296: 				      $udom, $tryserver);
12297:                 } else {
12298:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
12299:                 }
12300: 		if ($listing eq 'unknown_cmd') {
12301: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
12302: 				      $udom, $tryserver);
12303: 		    @listing_results = split(/:/,$listing);
12304: 		} else {
12305: 		    @listing_results =
12306: 			map { &unescape($_); } split(/:/,$listing);
12307: 		}
12308:                 if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
12309:                     ($listing eq 'rejected') || ($listing eq 'refused') ||
12310:                     ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
12311:                     $listerror{$tryserver} = $listing;
12312:                 } else {
12313: 		    foreach my $line (@listing_results) {
12314: 			my ($entry) = split(/&/,$line,2);
12315: 			$allusers{$entry} = 1;
12316: 		    }
12317: 		}
12318:             }
12319:             my @alluserslist=();
12320:             foreach my $user (sort(keys(%allusers))) {
12321:                 push(@alluserslist,$user.'&user');
12322:             }
12323: 
12324:             if (!%listerror) {
12325:                 # no errors
12326:                 return (\@alluserslist);
12327:             } elsif (scalar(keys(%servers)) == 1) {
12328:                 # one library server, one error 
12329:                 my ($key) = keys(%listerror);
12330:                 return (\@alluserslist, $listerror{$key});
12331:             } elsif ( grep { $_ eq 'con_lost' } values(%listerror) ) {
12332:                 # con_lost indicates that we might miss data from at least one
12333:                 # library server
12334:                 return (\@alluserslist, 'con_lost');
12335:             } else {
12336:                 # multiple library servers and no con_lost -> data should be
12337:                 # complete. 
12338:                 return (\@alluserslist);
12339:             }
12340: 
12341:         } else {
12342:             return ([],'missing username');
12343:         }
12344:     } elsif(!defined($getpropath)) {
12345:         my $path = $perlvar{'lonDocRoot'}.'/res/'; 
12346:         my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
12347:         return (\@all_domains);
12348:     } else {
12349:         return ([],'missing domain');
12350:     }
12351: }
12352: 
12353: # --------------------------------------------- GetFileTimestamp
12354: # This function utilizes dirlist and returns the date stamp for
12355: # when it was last modified.  It will also return an error of -1
12356: # if an error occurs
12357: 
12358: sub GetFileTimestamp {
12359:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
12360:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
12361:     $studentName   = &LONCAPA::clean_username($studentName);
12362:     my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
12363:                                     undef,$getuserdir);
12364:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
12365:         return -1;
12366:     }
12367:     if (ref($fileref) eq 'ARRAY') {
12368:         my @stats = split('&',$fileref->[0]);
12369:         # @stats contains first the filename, then the stat output
12370:         return $stats[10]; # so this is 10 instead of 9.
12371:     } else {
12372:         return -1;
12373:     }
12374: }
12375: 
12376: sub stat_file {
12377:     my ($uri) = @_;
12378:     $uri = &clutter_with_no_wrapper($uri);
12379: 
12380:     my ($udom,$uname,$file);
12381:     if ($uri =~ m-^/(uploaded|editupload)/-) {
12382: 	($udom,$uname,$file) =
12383: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
12384: 	$file = 'userfiles/'.$file;
12385:     }
12386:     if ($uri =~ m-^/res/-) {
12387: 	($udom,$uname) = 
12388: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
12389: 	$file = $uri;
12390:     }
12391: 
12392:     if (!$udom || !$uname || !$file) {
12393: 	# unable to handle the uri
12394: 	return ();
12395:     }
12396:     my $getpropath;
12397:     if ($file =~ /^userfiles\//) {
12398:         $getpropath = 1;
12399:     }
12400:     my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
12401:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
12402:         return ();
12403:     } else {
12404:         if (ref($listref) eq 'ARRAY') {
12405:             my @stats = split('&',$listref->[0]);
12406: 	    shift(@stats); #filename is first
12407: 	    return @stats;
12408:         }
12409:     }
12410:     return ();
12411: }
12412: 
12413: # --------------------------------------------------------- recursedirs
12414: # Recursive function to traverse either a specific user's Authoring Space
12415: # or corresponding Published Resource Space, and populate the hash ref:
12416: # $dirhashref with URLs of all directories, and if $filehashref hash
12417: # ref arg is provided, the URLs of any files, excluding versioned, .meta,
12418: # or .rights files in resource space, and .meta, .save, .log, .bak and
12419: # .rights files in Authoring Space.
12420: #
12421: # Inputs:
12422: #
12423: # $is_home - true if current server is home server for user's space
12424: # $recurse - if true will also traverse subdirectories recursively
12425: # $include - reference to hash containing allowed file extensions.  If provided,
12426: #             files which do not have a matching extension will be ignored.
12427: # $exclude - reference to hash containing excluded file extensions.  If provided,
12428: #             files which have a matching extension will be ignored.
12429: # $nonemptydir - if true, will only populate $fileshashref hash entry for a particular
12430: #             directory with first file found (with acceptable extension).
12431: # $addtopdir - if true, set $dirhashref->{'/'} = 1 
12432: # $toppath - Top level directory (i.e., /res/$dom/$uname or /priv/$dom/$uname
12433: # $relpath - Current path (relative to top level).
12434: # $dirhashref - reference to hash to populate with URLs of directories (Required)
12435: # $filehashref - reference to hash to populate with URLs of files (Optional)
12436: #
12437: # Returns: nothing
12438: #
12439: # Side Effects: populates $dirhashref, and $filehashref (if provided).
12440: #
12441: # Currently used by interface/londocs.pm to create linked select boxes for
12442: # directory and filename to import a Course "Author" resource into a course, and
12443: # also to create linked select boxes for Authoring Space and Directory to choose
12444: # save location for creation of a new "standard" problem from the Course Editor.
12445: #
12446: 
12447: sub recursedirs {
12448:     my ($is_home,$recurse,$include,$exclude,$nonemptydir,$addtopdir,$toppath,$relpath,$dirhashref,$filehashref) = @_;
12449:     return unless (ref($dirhashref) eq 'HASH');
12450:     my $docroot = $perlvar{'lonDocRoot'};
12451:     my $currpath = $docroot.$toppath;
12452:     if ($relpath ne '') {
12453:         $currpath .= "/$relpath";
12454:     }
12455:     my ($savefile,$checkinc,$checkexc);
12456:     if (ref($filehashref)) {
12457:         $savefile = 1;
12458:     }
12459:     if (ref($include) eq 'HASH') {
12460:         $checkinc = 1;
12461:     }
12462:     if (ref($exclude) eq 'HASH') {
12463:         $checkexc = 1;
12464:     }
12465:     if ($is_home) {
12466:         if ((-e $currpath) && (opendir(my $dirh,$currpath))) {
12467:             my $filecount = 0;
12468:             foreach my $item (sort { lc($a) cmp lc($b) } grep(!/^\.+$/,readdir($dirh))) {
12469:                 next if ($item eq '');
12470:                 if (-d "$currpath/$item") {
12471:                     my $newpath;
12472:                     if ($relpath ne '') {
12473:                         $newpath = "$relpath/$item";
12474:                     } else {
12475:                         $newpath = $item;
12476:                     }
12477:                     $dirhashref->{&Apache::lonlocal::js_escape($newpath)} = 1;
12478:                     if ($recurse) {
12479:                         &recursedirs($is_home,$recurse,$include,$exclude,$nonemptydir,$addtopdir,$toppath,$newpath,$dirhashref,$filehashref);
12480:                     }
12481:                 } elsif (($savefile) || ($relpath eq '')) {
12482:                     next if ($nonemptydir && $filecount);
12483:                     if ($checkinc || $checkexc) {
12484:                         my ($extension) = ($item =~ /\.(\w+)$/);
12485:                         if ($checkinc) {
12486:                             next unless ($extension && $include->{$extension});
12487:                         }
12488:                         if ($checkexc) {
12489:                             next if ($extension && $exclude->{$extension});
12490:                         }
12491:                     }
12492:                     if (($relpath eq '') && (!exists($dirhashref->{'/'}))) {
12493:                         $dirhashref->{'/'} = 1;
12494:                     }
12495:                     if ($savefile) {
12496:                         if ($relpath eq '') {
12497:                             $filehashref->{'/'}{$item} = 1;
12498:                         } else {
12499:                             $filehashref->{&Apache::lonlocal::js_escape($relpath)}{$item} = 1;
12500:                         }
12501:                     }
12502:                     $filecount ++;
12503:                 }
12504:             }
12505:             closedir($dirh);
12506:         }
12507:     } else {
12508:         my ($dirlistref,$listerror) =
12509:             &dirlist($toppath.$relpath);
12510:         my @dir_lines;
12511:         my $dirptr=16384;
12512:         if (ref($dirlistref) eq 'ARRAY') {
12513:             my $filecount = 0;
12514:             foreach my $dir_line (sort
12515:                               {
12516:                                   my ($afile)=split('&',$a,2);
12517:                                   my ($bfile)=split('&',$b,2);
12518:                                   return (lc($afile) cmp lc($bfile));
12519:                               } (@{$dirlistref})) {
12520:                 my ($item,$dom,undef,$testdir,undef,undef,undef,undef,$size,undef,$mtime,undef,undef,undef,$obs,undef) =
12521:                     split(/\&/,$dir_line,16);
12522:                 $item =~ s/\s+$//;
12523:                 next if (($item =~ /^\.\.?$/) || ($obs));
12524:                 if ($dirptr&$testdir) {
12525:                     my $newpath;
12526:                     if ($relpath) {
12527:                         $newpath = "$relpath/$item";
12528:                     } else {
12529:                         $newpath = $item;
12530:                     }
12531:                     $dirhashref->{&Apache::lonlocal::js_escape($newpath)} = 1;
12532:                     if ($recurse) {
12533:                         &recursedirs($is_home,$recurse,$include,$exclude,$nonemptydir,$addtopdir,$toppath,$newpath,$dirhashref,$filehashref);
12534:                     }
12535:                 } elsif (($savefile) || ($relpath eq '')) {
12536:                     next if ($nonemptydir && $filecount);
12537:                     if ($checkinc || $checkexc) {
12538:                         my $extension;
12539:                         if ($checkinc) {
12540:                             next unless ($extension && $include->{$extension});
12541:                         }
12542:                         if ($checkexc) {
12543:                             next if ($extension && $exclude->{$extension});
12544:                         }
12545:                     }
12546:                     if (($relpath eq '') && (!exists($dirhashref->{'/'}))) {
12547:                         $dirhashref->{'/'} = 1;
12548:                     }
12549:                     if ($savefile) {
12550:                         if ($relpath eq '') {
12551:                             $filehashref->{'/'}{$item} = 1;
12552:                         } else {
12553:                             $filehashref->{&Apache::lonlocal::js_escape($relpath)}{$item} = 1;
12554:                         }
12555:                     }
12556:                     $filecount ++; 
12557:                 }
12558:             }
12559:         }
12560:     }
12561:     if ($addtopdir) {
12562:         if (($relpath eq '') && (!exists($dirhashref->{'/'}))) {
12563:             $dirhashref->{'/'} = 1;
12564:         }
12565:     }
12566:     return;
12567: }
12568: 
12569: sub priv_exclude {
12570:     return {
12571:              meta => 1,
12572:              save => 1,
12573:              log => 1,
12574:              bak => 1,
12575:              rights => 1,
12576:              DS_Store => 1,
12577:            };
12578: }
12579: 
12580: # -------------------------------------------------------- Value of a Condition
12581: 
12582: # gets the value of a specific preevaluated condition
12583: #    stored in the string  $env{user.state.<cid>}
12584: # or looks up a condition reference in the bighash and if if hasn't
12585: # already been evaluated recurses into docondval to get the value of
12586: # the condition, then memoizing it to 
12587: #   $env{user.state.<cid>.<condition>}
12588: sub directcondval {
12589:     my $number=shift;
12590:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
12591: 	&Apache::lonuserstate::evalstate();
12592:     }
12593:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
12594: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
12595:     } elsif ($number =~ /^_/) {
12596: 	my $sub_condition;
12597: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
12598: 		&GDBM_READER(),0640)) {
12599: 	    $sub_condition=$bighash{'conditions'.$number};
12600: 	    untie(%bighash);
12601: 	}
12602: 	my $value = &docondval($sub_condition);
12603: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
12604: 	return $value;
12605:     }
12606:     if ($env{'user.state.'.$env{'request.course.id'}}) {
12607:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
12608:     } else {
12609:        return 2;
12610:     }
12611: }
12612: 
12613: # get the collection of conditions for this resource
12614: sub condval {
12615:     my $condidx=shift;
12616:     my $allpathcond='';
12617:     foreach my $cond (split(/\|/,$condidx)) {
12618: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
12619: 	    $allpathcond.=
12620: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
12621: 	}
12622:     }
12623:     $allpathcond=~s/\|$//;
12624:     return &docondval($allpathcond);
12625: }
12626: 
12627: #evaluates an expression of conditions
12628: sub docondval {
12629:     my ($allpathcond) = @_;
12630:     my $result=0;
12631:     if ($env{'request.course.id'}
12632: 	&& defined($allpathcond)) {
12633: 	my $operand='|';
12634: 	my @stack;
12635: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
12636: 	    if ($chunk eq '(') {
12637: 		push @stack,($operand,$result);
12638: 	    } elsif ($chunk eq ')') {
12639: 		my $before=pop @stack;
12640: 		if (pop @stack eq '&') {
12641: 		    $result=$result>$before?$before:$result;
12642: 		} else {
12643: 		    $result=$result>$before?$result:$before;
12644: 		}
12645: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
12646: 		$operand=$chunk;
12647: 	    } else {
12648: 		my $new=directcondval($chunk);
12649: 		if ($operand eq '&') {
12650: 		    $result=$result>$new?$new:$result;
12651: 		} else {
12652: 		    $result=$result>$new?$result:$new;
12653: 		}
12654: 	    }
12655: 	}
12656:     }
12657:     return $result;
12658: }
12659: 
12660: # ---------------------------------------------------- Devalidate courseresdata
12661: 
12662: sub devalidatecourseresdata {
12663:     my ($coursenum,$coursedomain)=@_;
12664:     my $hashid=$coursenum.':'.$coursedomain;
12665:     &devalidate_cache_new('courseres',$hashid);
12666: }
12667: 
12668: 
12669: # --------------------------------------------------- Course Resourcedata Query
12670: #
12671: #  Parameters:
12672: #      $coursenum    - Number of the course.
12673: #      $coursedomain - Domain at which the course was created.
12674: #  Returns:
12675: #     A hash of the course parameters along (I think) with timestamps
12676: #     and version info.
12677: 
12678: sub get_courseresdata {
12679:     my ($coursenum,$coursedomain)=@_;
12680:     my $coursehom=&homeserver($coursenum,$coursedomain);
12681:     my $hashid=$coursenum.':'.$coursedomain;
12682:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
12683:     my %dumpreply;
12684:     unless (defined($cached)) {
12685: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
12686: 	$result=\%dumpreply;
12687: 	my ($tmp) = keys(%dumpreply);
12688: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
12689: 	    &do_cache_new('courseres',$hashid,$result,600);
12690: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
12691: 	    return $tmp;
12692: 	} elsif ($tmp =~ /^(error)/) {
12693: 	    $result=undef;
12694: 	    &do_cache_new('courseres',$hashid,$result,600);
12695: 	}
12696:     }
12697:     return $result;
12698: }
12699: 
12700: sub devalidateuserresdata {
12701:     my ($uname,$udom)=@_;
12702:     my $hashid="$udom:$uname";
12703:     &devalidate_cache_new('userres',$hashid);
12704: }
12705: 
12706: sub get_userresdata {
12707:     my ($uname,$udom)=@_;
12708:     #most student don\'t have any data set, check if there is some data
12709:     if (&EXT_cache_status($udom,$uname)) { return undef; }
12710: 
12711:     my $hashid="$udom:$uname";
12712:     my ($result,$cached)=&is_cached_new('userres',$hashid);
12713:     if (!defined($cached)) {
12714: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
12715: 	$result=\%resourcedata;
12716: 	&do_cache_new('userres',$hashid,$result,600);
12717:     }
12718:     my ($tmp)=keys(%$result);
12719:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
12720: 	return $result;
12721:     }
12722:     #error 2 occurs when the .db doesn't exist
12723:     if ($tmp!~/error: 2 /) {
12724:         if ((!defined($cached)) || ($tmp ne 'con_lost')) {
12725: 	    &logthis("<font color=\"blue\">WARNING:".
12726: 		     " Trying to get resource data for ".
12727: 		     $uname." at ".$udom.": ".
12728: 		     $tmp."</font>");
12729:         }
12730:     } elsif ($tmp=~/error: 2 /) {
12731: 	#&EXT_cache_set($udom,$uname);
12732: 	&do_cache_new('userres',$hashid,undef,600);
12733: 	undef($tmp); # not really an error so don't send it back
12734:     }
12735:     return $tmp;
12736: }
12737: #----------------------------------------------- resdata - return resource data
12738: #  Purpose:
12739: #    Return resource data for either users or for a course.
12740: #  Parameters:
12741: #     $name      - Course/user name.
12742: #     $domain    - Name of the domain the user/course is registered on.
12743: #     $type      - Type of thing $name is (must be 'course' or 'user')
12744: #     $mapp      - decluttered URL of enclosing map  
12745: #     $recursed  - Ref to scalar -- set to 1, if nested maps have been recursed.
12746: #     $recurseup - Ref to array of map URLs, starting with map containing
12747: #                  $mapp up through hierarchy of nested maps to top level map.  
12748: #     $courseid  - CourseID (first part of param identifier).
12749: #     $modifier  - Middle part of param identifier.
12750: #     $what      - Last part of param identifier.
12751: #     @which     - Array of names of resources desired.
12752: #  Returns:
12753: #     The value of the first reasource in @which that is found in the
12754: #     resource hash.
12755: #  Exceptional Conditions:
12756: #     If the $type passed in is not valid (not the string 'course' or 
12757: #     'user', an undefined  reference is returned.
12758: #     If none of the resources are found, an undef is returned
12759: sub resdata {
12760:     my ($name,$domain,$type,$mapp,$recursed,$recurseup,$courseid,
12761:         $modifier,$what,@which)=@_;
12762:     my $result;
12763:     if ($type eq 'course') {
12764: 	$result=&get_courseresdata($name,$domain);
12765:     } elsif ($type eq 'user') {
12766: 	$result=&get_userresdata($name,$domain);
12767:     }
12768:     if (!ref($result)) { return $result; }    
12769:     foreach my $item (@which) {
12770:         if ($item->[1] eq 'course') {
12771:             if ((ref($recurseup) eq 'ARRAY') && (ref($recursed) eq 'SCALAR')) {
12772:                 unless ($$recursed) {
12773:                     @{$recurseup} = &get_map_hierarchy($mapp,$courseid);
12774:                     $$recursed = 1;
12775:                 }
12776:                 foreach my $item (@${recurseup}) {
12777:                     my $norecursechk=$courseid.$modifier.$item.'___(all).'.$what;
12778:                     last if (defined($result->{$norecursechk}));
12779:                     my $recursechk=$courseid.$modifier.$item.'___(rec).'.$what;
12780:                     if (defined($result->{$recursechk})) { return [$result->{$recursechk},'map']; }
12781:                 }
12782:             }
12783:         }
12784:         if (defined($result->{$item->[0]})) {
12785: 	    return [$result->{$item->[0]},$item->[1]];
12786: 	}
12787:     }
12788:     return undef;
12789: }
12790: 
12791: sub get_domain_lti {
12792:     my ($cdom,$context) = @_;
12793:     my ($name,$cachename,%lti);
12794:     if ($context eq 'consumer') {
12795:         $name = 'ltitools';
12796:     } elsif ($context eq 'provider') {
12797:         $name = 'lti';
12798:     } elsif ($context eq 'linkprot') {
12799:         $name = 'ltisec';
12800:     } else {
12801:         return %lti;
12802:     }
12803:     if ($context eq 'linkprot') {
12804:         $cachename = $context;
12805:     } else {
12806:         $cachename = $name;
12807:     }
12808:     my ($result,$cached)=&is_cached_new($cachename,$cdom);
12809:     if (defined($cached)) {
12810:         if (ref($result) eq 'HASH') {
12811:             %lti = %{$result};
12812:         }
12813:     } else {
12814:         my %domconfig = &get_dom('configuration',[$name],$cdom);
12815:         if (ref($domconfig{$name}) eq 'HASH') {
12816:             if ($context eq 'linkprot') {
12817:                 if (ref($domconfig{$name}{'linkprot'}) eq 'HASH') {
12818:                     %lti = %{$domconfig{$name}{'linkprot'}};
12819:                 }
12820:             } else {
12821:                 %lti = %{$domconfig{$name}};
12822:             }
12823:         }
12824:         my $cachetime = 24*60*60;
12825:         &do_cache_new($cachename,$cdom,\%lti,$cachetime);
12826:     }
12827:     return %lti;
12828: }
12829: 
12830: sub get_course_lti {
12831:     my ($cnum,$cdom,$context) = @_;
12832:     my ($name,$cachename,%lti);
12833:     if ($context eq 'consumer') {
12834:         $name = 'ltitools';
12835:         $cachename = 'courseltitools';
12836:     } elsif ($context eq 'provider') {
12837:         $name = 'lti';
12838:         $cachename = 'courselti';
12839:     } else {
12840:         return %lti;
12841:     }
12842:     my $hashid=$cdom.'_'.$cnum;
12843:     my ($result,$cached)=&is_cached_new($cachename,$hashid);
12844:     if (defined($cached)) {
12845:         if (ref($result) eq 'HASH') {
12846:             %lti = %{$result};
12847:         }
12848:     } else {
12849:         %lti = &dump($name,$cdom,$cnum,undef,undef,undef,1);
12850:         my $cachetime = 24*60*60;
12851:         &do_cache_new($cachename,$hashid,\%lti,$cachetime);
12852:     }
12853:     return %lti;
12854: }
12855: 
12856: sub courselti_itemid {
12857:     my ($cnum,$cdom,$url,$method,$params,$context) = @_;
12858:     my ($chome,$itemid);
12859:     $chome = &homeserver($cnum,$cdom);
12860:     return if ($chome eq 'no_host');
12861:     if (ref($params) eq 'HASH') {
12862:         my $rep;
12863:         if (grep { $_ eq $chome } current_machine_ids()) {
12864:             $rep = LONCAPA::Lond::crslti_itemid($cdom,$cnum,$url,$method,$params,$perlvar{'lonVersion'});
12865:         } else {
12866:             my $escurl = &escape($url);
12867:             my $escmethod = &escape($method);
12868:             my $items = &freeze_escape($params);
12869:             $rep = &reply("encrypt:lti:$cdom:$cnum:$context:$escurl:$escmethod:$items",$chome);
12870:         }
12871:         unless (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
12872:                 ($rep eq 'unknown_cmd')) {
12873:             $itemid = $rep;
12874:         }
12875:     }
12876:     return $itemid;
12877: }
12878: 
12879: sub domainlti_itemid {
12880:     my ($cdom,$url,$method,$params,$context) = @_;
12881:     my ($primary_id,$itemid);
12882:     $primary_id = &domain($cdom,'primary');
12883:     return if ($primary_id eq '');
12884:     if (ref($params) eq 'HASH') {
12885:         my $rep;
12886:         if (grep { $_ eq $primary_id } current_machine_ids()) {
12887:             $rep = LONCAPA::Lond::domlti_itemid($cdom,$context,$url,$method,$params,$perlvar{'lonVersion'});
12888:         } else {
12889:             my $cnum = '';
12890:             my $escurl = &escape($url);
12891:             my $escmethod = &escape($method);
12892:             my $items = &freeze_escape($params);
12893:             $rep = &reply("encrypt:lti:$cdom:$cnum:$context:$escurl:$escmethod:$items",$primary_id);
12894:         }
12895:         unless (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
12896:                 ($rep eq 'unknown_cmd')) {
12897:             $itemid = $rep;
12898:         }
12899:     }
12900:     return $itemid;
12901: }
12902: 
12903: sub get_ltitools_id {
12904:     my ($context,$cdom,$cnum,$title) = @_;
12905:     my ($lockhash,$tries,$gotlock,$id,$error);
12906: 
12907:     # get lock on ltitools db
12908:     $lockhash = {
12909:                    lock => $env{'user.name'}.
12910:                            ':'.$env{'user.domain'},
12911:                 };
12912:     $tries = 0;
12913:     if ($context eq 'domain') {
12914:         $gotlock = &newput_dom('ltitools',$lockhash,$cdom);
12915:     } else {
12916:         $gotlock = &newput('ltitools',$lockhash,$cdom,$cnum);
12917:     }
12918:     while (($gotlock ne 'ok') && ($tries<10)) {
12919:         $tries ++;
12920:         sleep (0.1);
12921:         if ($context eq 'domain') {
12922:             $gotlock = &newput_dom('ltitools',$lockhash,$cdom);
12923:         } else {
12924:             $gotlock = &newput('ltitools',$lockhash,$cdom,$cnum);
12925:         }
12926:     }
12927:     if ($gotlock eq 'ok') {
12928:         my %currids;
12929:         if ($context eq 'domain') {
12930:             %currids = &dump_dom('ltitools',$cdom);
12931:         } else {
12932:             %currids = &dump('ltitools',$cdom,$cnum);
12933:         }
12934:         if ($currids{'lock'}) {
12935:             delete($currids{'lock'});
12936:             if (keys(%currids)) {
12937:                 my @curr = sort { $a <=> $b } keys(%currids);
12938:                 if ($curr[-1] =~ /^\d+$/) {
12939:                     $id = 1 + $curr[-1];
12940:                 }
12941:             } else {
12942:                 $id = 1;
12943:             }
12944:             if ($id) {
12945:                 if ($context eq 'domain') {
12946:                     unless (&newput_dom('ltitools',{ $id => $title },$cdom) eq 'ok') {
12947:                         $error = 'nostore';
12948:                     }
12949:                 } else {
12950:                     unless (&newput('ltitools',{ $id => $title },$cdom,$cnum) eq 'ok') {
12951:                         $error = 'nostore';
12952:                     }
12953:                 }
12954:             } else {
12955:                 $error = 'nonumber';
12956:             }
12957:         }
12958:         my $dellockoutcome;
12959:         if ($context eq 'domain') {
12960:             $dellockoutcome = &del_dom('ltitools',['lock'],$cdom);
12961:         } else {
12962:             $dellockoutcome = &del('ltitools',['lock'],$cdom,$cnum);
12963:         }
12964:     } else {
12965:         $error = 'nolock';
12966:     }
12967:     return ($id,$error);
12968: }
12969: 
12970: sub count_supptools {
12971:     my ($cnum,$cdom,$ignorecache,$reload)=@_;
12972:     my $hashid=$cnum.':'.$cdom;
12973:     my ($numexttools,$cached);
12974:     unless ($ignorecache) {
12975:         ($numexttools,$cached) = &is_cached_new('supptools',$hashid);
12976:     }
12977:     unless (defined($cached)) {
12978:         my $chome=&homeserver($cnum,$cdom);
12979:         $numexttools = 0;
12980:         unless ($chome eq 'no_host') {
12981:             my ($supplemental) = &Apache::loncommon::get_supplemental($cnum,$cdom,$reload);
12982:             if (ref($supplemental) eq 'HASH') {
12983:                 if ((ref($supplemental->{'ids'}) eq 'HASH') && (ref($supplemental->{'hidden'}) eq 'HASH')) {
12984:                     foreach my $key (keys(%{$supplemental->{'ids'}})) {
12985:                         if ($key =~ m{^/adm/$cdom/$cnum/\d+/ext\.tool$}) {
12986:                             $numexttools ++;
12987:                         }
12988:                     }
12989:                 }
12990:             }
12991:         }
12992:         &do_cache_new('supptools',$hashid,$numexttools,600);
12993:     }
12994:     return $numexttools;
12995: }
12996: 
12997: sub has_unhidden_suppfiles {
12998:     my ($cnum,$cdom,$ignorecache,$possdel)=@_;
12999:     my $hashid=$cnum.':'.$cdom;
13000:     my ($showsupp,$cached);
13001:     unless ($ignorecache) {
13002:         ($showsupp,$cached) = &is_cached_new('showsupp',$hashid);
13003:     }
13004:     unless (defined($cached)) {
13005:         my $chome=&homeserver($cnum,$cdom);
13006:         unless ($chome eq 'no_host') {
13007:             my ($supplemental) = &Apache::loncommon::get_supplemental($cnum,$cdom,$ignorecache,$possdel);
13008:             if (ref($supplemental) eq 'HASH') {
13009:                 if ((ref($supplemental->{'ids'}) eq 'HASH') && (ref($supplemental->{'hidden'}) eq 'HASH')) {
13010:                     foreach my $key (keys(%{$supplemental->{'ids'}})) {
13011:                         next if ($key =~ /\.sequence$/);
13012:                         if (ref($supplemental->{'ids'}->{$key}) eq 'ARRAY') {
13013:                             foreach my $id (@{$supplemental->{'ids'}->{$key}}) {
13014:                                 unless ($supplemental->{'hidden'}->{$id}) {
13015:                                     $showsupp = 1;
13016:                                     last;
13017:                                 }
13018:                             }
13019:                         }
13020:                         last if ($showsupp);
13021:                     }
13022:                 }
13023:             }
13024:         }
13025:         &do_cache_new('showsupp',$hashid,$showsupp,600);
13026:     }
13027:     return $showsupp;
13028: }
13029: 
13030: #
13031: # EXT resource caching routines
13032: #
13033: 
13034: {
13035: # Cache (5 seconds) of map hierarchy for speedup of navmaps display
13036: #
13037: # The course for which we cache
13038: my $cachedmapkey='';
13039: # The cached recursive maps for this course
13040: my %cachedmaps=();
13041: # When this was last done
13042: my $cachedmaptime='';
13043: 
13044: sub clear_EXT_cache_status {
13045:     &delenv('cache.EXT.');
13046: }
13047: 
13048: sub EXT_cache_status {
13049:     my ($target_domain,$target_user) = @_;
13050:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
13051:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
13052:         # We know already the user has no data
13053:         return 1;
13054:     } else {
13055:         return 0;
13056:     }
13057: }
13058: 
13059: sub EXT_cache_set {
13060:     my ($target_domain,$target_user) = @_;
13061:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
13062:     #&appenv({$cachename => time});
13063: }
13064: 
13065: # --------------------------------------------------------- Value of a Variable
13066: sub EXT {
13067: 
13068:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse,$cid,$recurseupref)=@_;
13069:     unless ($varname) { return ''; }
13070:     #get real user name/domain, courseid and symb
13071:     my $courseid;
13072:     my $publicuser;
13073:     if ($symbparm) {
13074: 	$symbparm=&get_symb_from_alias($symbparm);
13075:     }
13076:     if (!($uname && $udom)) {
13077:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
13078:       if (!$symbparm) {	$symbparm=$cursymb; }
13079:     } else {
13080: 	$courseid=$env{'request.course.id'};
13081:     }
13082:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
13083:     my $rest;
13084:     if (defined($therest[0])) {
13085:        $rest=join('.',@therest);
13086:     } else {
13087:        $rest='';
13088:     }
13089: 
13090:     my $qualifierrest=$qualifier;
13091:     if ($rest) { $qualifierrest.='.'.$rest; }
13092:     my $spacequalifierrest=$space;
13093:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
13094:     if ($realm eq 'user') {
13095: # --------------------------------------------------------------- user.resource
13096: 	if ($space eq 'resource') {
13097: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
13098: 		  || defined($Apache::lonhomework::parsing_a_task))
13099: 		 &&
13100: 		 ($symbparm eq &symbread()) ) {
13101: 		# if we are in the middle of processing the resource the
13102: 		# get the value we are planning on committing
13103:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
13104:                     return $Apache::lonhomework::results{$qualifierrest};
13105:                 } else {
13106:                     return $Apache::lonhomework::history{$qualifierrest};
13107:                 }
13108: 	    } else {
13109: 		my %restored;
13110: 		if ($publicuser || $env{'request.state'} eq 'construct') {
13111: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
13112: 		} else {
13113: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
13114: 		}
13115: 		return $restored{$qualifierrest};
13116: 	    }
13117: # ----------------------------------------------------------------- user.access
13118:         } elsif ($space eq 'access') {
13119: 	    # FIXME - not supporting calls for a specific user
13120:             return &allowed($qualifier,$rest);
13121: # ------------------------------------------ user.preferences, user.environment
13122:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
13123: 	    if (($uname eq $env{'user.name'}) &&
13124: 		($udom eq $env{'user.domain'})) {
13125: 		return $env{join('.',('environment',$qualifierrest))};
13126: 	    } else {
13127: 		my %returnhash;
13128: 		if (!$publicuser) {
13129: 		    %returnhash=&userenvironment($udom,$uname,
13130: 						 $qualifierrest);
13131: 		}
13132: 		return $returnhash{$qualifierrest};
13133: 	    }
13134: # ----------------------------------------------------------------- user.course
13135:         } elsif ($space eq 'course') {
13136: 	    # FIXME - not supporting calls for a specific user
13137:             return $env{join('.',('request.course',$qualifier))};
13138: # ------------------------------------------------------------------- user.role
13139:         } elsif ($space eq 'role') {
13140: 	    # FIXME - not supporting calls for a specific user
13141:             my ($role,$where)=split(/\./,$env{'request.role'});
13142:             if ($qualifier eq 'value') {
13143: 		return $role;
13144:             } elsif ($qualifier eq 'extent') {
13145:                 return $where;
13146:             }
13147: # ----------------------------------------------------------------- user.domain
13148:         } elsif ($space eq 'domain') {
13149:             return $udom;
13150: # ------------------------------------------------------------------- user.name
13151:         } elsif ($space eq 'name') {
13152:             return $uname;
13153: # ---------------------------------------------------- Any other user namespace
13154:         } else {
13155: 	    my %reply;
13156: 	    if (!$publicuser) {
13157: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
13158: 	    }
13159: 	    return $reply{$qualifierrest};
13160:         }
13161:     } elsif ($realm eq 'query') {
13162: # ---------------------------------------------- pull stuff out of query string
13163:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
13164: 						[$spacequalifierrest]);
13165: 	return $env{'form.'.$spacequalifierrest}; 
13166:    } elsif ($realm eq 'request') {
13167: # ------------------------------------------------------------- request.browser
13168:         if ($space eq 'browser') {
13169:             return $env{'browser.'.$qualifier};
13170: # ------------------------------------------------------------ request.filename
13171:         } else {
13172:             return $env{'request.'.$spacequalifierrest};
13173:         }
13174:     } elsif ($realm eq 'course') {
13175: # ---------------------------------------------------------- course.description
13176:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
13177:     } elsif ($realm eq 'resource') {
13178: 
13179: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
13180: 	    if (!$symbparm) { $symbparm=&symbread(); }
13181: 	}
13182: 
13183:         if ($qualifier eq '') {
13184: 	    if ($space eq 'title') {
13185: 	        if (!$symbparm) { $symbparm = $env{'request.filename'}; }
13186: 	        return &gettitle($symbparm);
13187: 	    }
13188: 	
13189: 	    if ($space eq 'map') {
13190: 	        my ($map) = &decode_symb($symbparm);
13191: 	        return &symbread($map);
13192: 	    }
13193:             if ($space eq 'maptitle') {
13194:                 my ($map) = &decode_symb($symbparm);
13195:                 return &gettitle($map);
13196:             }
13197: 	    if ($space eq 'filename') {
13198: 	        if ($symbparm) {
13199: 		    return &clutter((&decode_symb($symbparm))[2]);
13200: 	        }
13201: 	        return &hreflocation('',$env{'request.filename'});
13202: 	    }
13203: 
13204:             if ((defined($courseid)) && ($courseid eq $env{'request.course.id'}) && $symbparm) {
13205:                 if ($space eq 'visibleparts') {
13206:                     my $navmap = Apache::lonnavmaps::navmap->new();
13207:                     my $item;
13208:                     if (ref($navmap)) {
13209:                         my $res = $navmap->getBySymb($symbparm);
13210:                         my $parts = $res->parts();
13211:                         if (ref($parts) eq 'ARRAY') {
13212:                             $item = join(',',@{$parts});
13213:                         }
13214:                         undef($navmap);
13215:                     }
13216:                     return $item;
13217:                 }
13218:             }
13219:         }
13220: 
13221: 	my ($section, $group, @groups, @recurseup, $recursed);
13222:         if (ref($recurseupref) eq 'ARRAY') {
13223:             @recurseup = @{$recurseupref};
13224:             $recursed = 1;
13225:         }
13226: 	my ($courselevelm,$courseleveli,$courselevel,$mapp);
13227:         if (($courseid eq '') && ($cid)) {
13228:             $courseid = $cid;
13229:         }
13230: 	if (($symbparm && $courseid) && 
13231: 	    (($courseid eq $env{'request.course.id'}) || ($courseid eq $cid)))  {
13232: 
13233: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
13234: 
13235: # ----------------------------------------------------- Cascading lookup scheme
13236: 	    my $symbp=$symbparm;
13237: 	    $mapp=&deversion((&decode_symb($symbp))[0]);
13238: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
13239:             my $recurseparm=$mapp.'___(rec).'.$spacequalifierrest;
13240: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
13241: 	    if (($env{'user.name'} eq $uname) &&
13242: 		($env{'user.domain'} eq $udom)) {
13243: 		$section=$env{'request.course.sec'};
13244:                 @groups = split(/:/,$env{'request.course.groups'});  
13245:                 @groups=&sort_course_groups($courseid,@groups); 
13246: 	    } else {
13247: 		if (! defined($usection)) {
13248: 		    $section=&getsection($udom,$uname,$courseid);
13249: 		} else {
13250: 		    $section = $usection;
13251: 		}
13252:                 @groups = &get_users_groups($udom,$uname,$courseid);
13253: 	    }
13254: 
13255: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
13256: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
13257:             my $secleveli=$courseid.'.['.$section.'].'.$recurseparm;
13258: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
13259: 
13260: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
13261: 	    my $courselevelr=$courseid.'.'.$symbparm;
13262:             $courseleveli=$courseid.'.'.$recurseparm;
13263: 	    $courselevelm=$courseid.'.'.$mapparm;
13264: 
13265: # ----------------------------------------------------------- first, check user
13266: 
13267: 	    my $userreply=&resdata($uname,$udom,'user',$mapp,\$recursed,
13268:                                    \@recurseup,$courseid,'.',$spacequalifierrest, 
13269: 				       ([$courselevelr,'resource'],
13270: 					[$courselevelm,'map'     ],
13271:                                         [$courseleveli,'map'     ],
13272: 					[$courselevel, 'course'  ]));
13273: 	    if (defined($userreply)) { return &get_reply($userreply); }
13274: 
13275: # ------------------------------------------------ second, check some of course
13276:             my $coursereply;
13277:             if (@groups > 0) {
13278:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
13279:                                        $recurseparm,$mapparm,$spacequalifierrest,
13280:                                        $mapp,\$recursed,\@recurseup);
13281:                 if (defined($coursereply)) { return &get_reply($coursereply); } 
13282:             }
13283: 
13284: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
13285: 				  $env{'course.'.$courseid.'.domain'},
13286: 				  'course',$mapp,\$recursed,\@recurseup,
13287:                                   $courseid,'.['.$section.'].',$spacequalifierrest,
13288: 				  ([$seclevelr,   'resource'],
13289: 				   [$seclevelm,   'map'     ],
13290:                                    [$secleveli,   'map'     ],
13291: 				   [$seclevel,    'course'  ],
13292: 				   [$courselevelr,'resource']));
13293: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
13294: 
13295: # ------------------------------------------------------ third, check map parms
13296: 	    my %parmhash=();
13297: 	    my $thisparm='';
13298: 	    if (tie(%parmhash,'GDBM_File',
13299: 		    $env{'request.course.fn'}.'_parms.db',
13300: 		    &GDBM_READER(),0640)) {
13301: 		$thisparm=$parmhash{$symbparm};
13302: 		untie(%parmhash);
13303: 	    }
13304: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
13305: 	}
13306: # ------------------------------------------ fourth, look in resource metadata
13307:  
13308:         my $what = $spacequalifierrest;
13309: 	$what=~s/\./\_/;
13310: 	my $filename;
13311: 	if (!$symbparm) { $symbparm=&symbread(); }
13312: 	if ($symbparm) {
13313: 	    $filename=(&decode_symb($symbparm))[2];
13314: 	} else {
13315: 	    $filename=$env{'request.filename'};
13316: 	}
13317:         my $toolsymb;
13318:         if (($filename =~ /ext\.tool$/) && ($what ne '0_gradable')) {
13319:             $toolsymb = $symbparm;
13320:         }
13321: 	my $metadata=&metadata($filename,$what,$toolsymb);
13322: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
13323: 	$metadata=&metadata($filename,'parameter_'.$what,$toolsymb);
13324: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
13325: 
13326: # ----------------------------------------------- fifth, look in rest of course
13327: 	if ($symbparm && defined($courseid) && 
13328: 	    $courseid eq $env{'request.course.id'}) {
13329: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
13330: 				     $env{'course.'.$courseid.'.domain'},
13331: 				     'course',$mapp,\$recursed,\@recurseup,
13332:                                      $courseid,'.',$spacequalifierrest,
13333: 				     ([$courselevelm,'map'   ],
13334:                                       [$courseleveli,'map'   ],
13335: 				      [$courselevel, 'course']));
13336: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
13337: 	}
13338: # ------------------------------------------------------------------ Cascade up
13339: 	unless ($space eq '0') {
13340: 	    my @parts=split(/_/,$space);
13341: 	    my $id=pop(@parts);
13342: 	    my $part=join('_',@parts);
13343: 	    if ($part eq '') { $part='0'; }
13344: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
13345: 				 $symbparm,$udom,$uname,$section,1);
13346: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
13347: 	}
13348: 	if ($recurse) { return undef; }
13349: 	my $pack_def=&packages_tab_default($filename,$varname,$toolsymb);
13350: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
13351: # ---------------------------------------------------- Any other user namespace
13352:     } elsif ($realm eq 'environment') {
13353: # ----------------------------------------------------------------- environment
13354: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
13355: 	    return $env{'environment.'.$spacequalifierrest};
13356: 	} else {
13357: 	    if ($uname eq 'anonymous' && $udom eq '') {
13358: 		return '';
13359: 	    }
13360: 	    my %returnhash=&userenvironment($udom,$uname,
13361: 					    $spacequalifierrest);
13362: 	    return $returnhash{$spacequalifierrest};
13363: 	}
13364:     } elsif ($realm eq 'system') {
13365: # ----------------------------------------------------------------- system.time
13366: 	if ($space eq 'time') {
13367: 	    return time;
13368:         }
13369:     } elsif ($realm eq 'server') {
13370: # ----------------------------------------------------------------- system.time
13371: 	if ($space eq 'name') {
13372: 	    return $ENV{'SERVER_NAME'};
13373:         }
13374:     } elsif ($realm eq 'client') {
13375:         if ($space eq 'remote_addr') {
13376:             return &get_requestor_ip();
13377:         }
13378:     }
13379:     return '';
13380: }
13381: 
13382: sub get_reply {
13383:     my ($reply_value) = @_;
13384:     if (ref($reply_value) eq 'ARRAY') {
13385:         if (wantarray) {
13386: 	    return @$reply_value;
13387:         }
13388:         return $reply_value->[0];
13389:     } else {
13390:         return $reply_value;
13391:     }
13392: }
13393: 
13394: sub check_group_parms {
13395:     my ($courseid,$groups,$symbparm,$recurseparm,$mapparm,$what,$mapp,
13396:         $recursed,$recurseupref) = @_;
13397:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$recurseparm,'map'],
13398:                   [$what,'course']);
13399:     my $coursereply;
13400:     foreach my $group (@{$groups}) {
13401:         my @groupitems = ();
13402:         foreach my $level (@levels) {
13403:              my $item = $courseid.'.['.$group.'].'.$level->[0];
13404:              push(@groupitems,[$item,$level->[1]]);
13405:         }
13406:         my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
13407:                                    $env{'course.'.$courseid.'.domain'},
13408:                                    'course',$mapp,$recursed,$recurseupref,
13409:                                    $courseid,'.['.$group.'].',$what,
13410:                                    @groupitems);
13411:         last if (defined($coursereply));
13412:     }
13413:     return $coursereply;
13414: }
13415: 
13416: sub get_map_hierarchy {
13417:     my ($mapname,$courseid) = @_;
13418:     my @recurseup = ();
13419:     if ($mapname) {
13420:         if (($cachedmapkey eq $courseid) &&
13421:             (abs($cachedmaptime-time)<5)) {
13422:             if (ref($cachedmaps{$mapname}) eq 'ARRAY') {
13423:                 return @{$cachedmaps{$mapname}};
13424:             }
13425:         }
13426:         my $navmap = Apache::lonnavmaps::navmap->new();
13427:         if (ref($navmap)) {
13428:             @recurseup = $navmap->recurseup_maps($mapname);
13429:             undef($navmap);
13430:             $cachedmaps{$mapname} = \@recurseup;
13431:             $cachedmaptime=time;
13432:             $cachedmapkey=$courseid;
13433:         }
13434:     }
13435:     return @recurseup;
13436: }
13437: 
13438: }
13439: 
13440: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
13441:     my ($courseid,@groups) = @_;
13442:     @groups = sort(@groups);
13443:     return @groups;
13444: }
13445: 
13446: sub packages_tab_default {
13447:     my ($uri,$varname,$toolsymb)=@_;
13448:     my (undef,$part,$name)=split(/\./,$varname);
13449: 
13450:     my (@extension,@specifics,$do_default);
13451:     foreach my $package (split(/,/,&metadata($uri,'packages',$toolsymb))) {
13452: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
13453: 	if ($pack_type eq 'default') {
13454: 	    $do_default=1;
13455: 	} elsif ($pack_type eq 'extension') {
13456: 	    push(@extension,[$package,$pack_type,$pack_part]);
13457: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
13458: 	    # only look at packages defaults for packages that this id is
13459: 	    push(@specifics,[$package,$pack_type,$pack_part]);
13460: 	}
13461:     }
13462:     # first look for a package that matches the requested part id
13463:     foreach my $package (@specifics) {
13464: 	my (undef,$pack_type,$pack_part)=@{$package};
13465: 	next if ($pack_part ne $part);
13466: 	if (defined($packagetab{"$pack_type&$name&default"})) {
13467: 	    return $packagetab{"$pack_type&$name&default"};
13468: 	}
13469:     }
13470:     # look for any possible matching non extension_ package
13471:     foreach my $package (@specifics) {
13472: 	my (undef,$pack_type,$pack_part)=@{$package};
13473: 	if (defined($packagetab{"$pack_type&$name&default"})) {
13474: 	    return $packagetab{"$pack_type&$name&default"};
13475: 	}
13476: 	if ($pack_type eq 'part') { $pack_part='0'; }
13477: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
13478: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
13479: 	}
13480:     }
13481:     # look for any posible extension_ match
13482:     foreach my $package (@extension) {
13483: 	my ($package,$pack_type)=@{$package};
13484: 	if (defined($packagetab{"$pack_type&$name&default"})) {
13485: 	    return $packagetab{"$pack_type&$name&default"};
13486: 	}
13487: 	if (defined($packagetab{$package."&$name&default"})) {
13488: 	    return $packagetab{$package."&$name&default"};
13489: 	}
13490:     }
13491:     # look for a global default setting
13492:     if ($do_default && defined($packagetab{"default&$name&default"})) {
13493: 	return $packagetab{"default&$name&default"};
13494:     }
13495:     return undef;
13496: }
13497: 
13498: sub add_prefix_and_part {
13499:     my ($prefix,$part)=@_;
13500:     my $keyroot;
13501:     if (defined($prefix) && $prefix !~ /^__/) {
13502: 	# prefix that has a part already
13503: 	$keyroot=$prefix;
13504:     } elsif (defined($prefix)) {
13505: 	# prefix that is missing a part
13506: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
13507:     } else {
13508: 	# no prefix at all
13509: 	if (defined($part)) { $keyroot='_'.$part; }
13510:     }
13511:     return $keyroot;
13512: }
13513: 
13514: # ---------------------------------------------------------------- Get metadata
13515: 
13516: my %metaentry;
13517: my %importedpartids;
13518: my %importedrespids;
13519: sub metadata {
13520:     my ($uri,$what,$toolsymb,$liburi,$prefix,$depthcount)=@_;
13521:     $uri=&declutter($uri);
13522:     # if it is a non metadata possible uri return quickly
13523:     if (($uri eq '') || 
13524: 	(($uri =~ m|^/*adm/|) && 
13525: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard|ext\.tool)$})) ||
13526:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
13527: 	return undef;
13528:     }
13529:     if (($uri =~ /^priv/ || $uri=~m{^home/httpd/html/priv}) 
13530: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
13531: 	return undef;
13532:     }
13533:     my $filename=$uri;
13534:     $uri=~s/\.meta$//;
13535: #
13536: # Is the metadata already cached?
13537: # Look at timestamp of caching
13538: # Everything is cached by the main uri, libraries are never directly cached
13539: #
13540:     if (!defined($liburi)) {
13541: 	my ($result,$cached)=&is_cached_new('meta',$uri);
13542: 	if (defined($cached)) { return $result->{':'.$what}; }
13543:     }
13544: 
13545: #
13546: # If the uri is for an external tool the file from
13547: # which metadata should be retrieved depends on whether
13548: # the tool had been configured to be gradable (set in the Course
13549: # Editor or Resource Editor).
13550: #
13551: # If a valid symb has been included as the third arg in the call
13552: # to &metadata() that can be used to retrieve the value of
13553: # parameter_0_gradable set for the resource, and included in the
13554: # uploaded map containing the tool. The value is retrieved via
13555: # &EXT(), if a valid symb is available.  Otherwise the value of
13556: # gradable in the exttool_$marker.db file for the tool instance
13557: # is retrieved via &get().
13558: #
13559: # When lonuserstate::traceroute() calls lonnet::EXT() for 
13560: # hiddenresource and encrypturl (during course initialization)
13561: # the map-level parameter for resource.0.gradable included in the 
13562: # uploaded map containing the tool will not yet have been stored
13563: # in the user_course_parms.db file for the user's session, so in 
13564: # this case fall back to retrieving gradable status from the
13565: # exttool_$marker.db file.
13566: #
13567: # In order to avoid an infinite loop, &metadata() will return
13568: # before a call to &EXT(), if the uri is for an external tool
13569: # and the $what for which metadata is being requested is
13570: # parameter_0_gradable or 0_gradable.
13571: #
13572: 
13573:     if ($uri =~ /ext\.tool$/) {
13574:         if (($what eq 'parameter_0_gradable') || ($what eq '0_gradable')) {
13575:             return;
13576:         } else {
13577:             my ($checked,$use_passback);
13578:             if ($toolsymb ne '') {
13579:                 (undef,undef,my $tooluri) = &decode_symb($toolsymb);
13580:                 if (($tooluri eq $uri) && (&EXT('resource.0.gradable',$toolsymb))) {
13581:                     $checked = 1;
13582:                     if (&EXT('resource.0.gradable',$toolsymb) =~ /^yes$/i) {
13583:                         $use_passback = 1;
13584:                     }
13585:                 }
13586:             }
13587:             unless ($checked) {
13588:                 my ($ignore,$cdom,$cnum,$marker) = split(m{/},$uri);
13589:                 $marker=~s/\D//g;
13590:                 if ($marker) {
13591:                     my %toolsettings=&get('exttool_'.$marker,['gradable'],$cdom,$cnum);
13592:                     $use_passback = $toolsettings{'gradable'};
13593:                 }
13594:             }
13595:             if ($use_passback) {
13596:                 $filename = '/home/httpd/html/res/lib/templates/LTIpassback.tool';
13597:             } else {
13598:                 $filename = '/home/httpd/html/res/lib/templates/LTIstandard.tool';
13599:             }
13600:         }
13601:     }
13602: 
13603:     {
13604: # Imported parts would go here
13605:         my @origfiletagids=();
13606:         my $importedparts=0;
13607: 
13608: # Imported responseids would go here
13609:         my $importedresponses=0;
13610: #
13611: # Is this a recursive call for a library?
13612: #
13613: #	if (! exists($metacache{$uri})) {
13614: #	    $metacache{$uri}={};
13615: #	}
13616: 	my $cachetime = 60*60;
13617:         if ($liburi) {
13618: 	    $liburi=&declutter($liburi);
13619:             $filename=$liburi;
13620:         } else {
13621: 	    &devalidate_cache_new('meta',$uri);
13622: 	    undef(%metaentry);
13623: 	}
13624:         my %metathesekeys=();
13625:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
13626: 	my $metastring;
13627: 	if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
13628: 	    my $which = &hreflocation('','/'.($liburi || $uri));
13629: 	    $metastring = 
13630: 		&Apache::lonnet::ssi_body($which,
13631: 					  ('grade_target' => 'meta'));
13632: 	    $cachetime = 1; # only want this cached in the child not long term
13633: 	} elsif (($uri !~ m -^(editupload)/-) && 
13634:                  ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
13635: 	    my $file=&filelocation('',&clutter($filename));
13636: 	    #push(@{$metaentry{$uri.'.file'}},$file);
13637: 	    $metastring=&getfile($file);
13638: 	}
13639:         my $parser=HTML::LCParser->new(\$metastring);
13640:         my $token;
13641:         undef %metathesekeys;
13642:         while ($token=$parser->get_token) {
13643: 	    if ($token->[0] eq 'S') {
13644: 		if (defined($token->[2]->{'package'})) {
13645: #
13646: # This is a package - get package info
13647: #
13648: 		    my $package=$token->[2]->{'package'};
13649: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
13650: 		    if (defined($token->[2]->{'id'})) { 
13651: 			$keyroot.='_'.$token->[2]->{'id'}; 
13652: 		    }
13653: 		    if ($metaentry{':packages'}) {
13654: 			$metaentry{':packages'}.=','.$package.$keyroot;
13655: 		    } else {
13656: 			$metaentry{':packages'}=$package.$keyroot;
13657: 		    }
13658: 		    foreach my $pack_entry (keys(%packagetab)) {
13659: 			my $part=$keyroot;
13660: 			$part=~s/^\_//;
13661: 			if ($pack_entry=~/^\Q$package\E\&/ || 
13662: 			    $pack_entry=~/^\Q$package\E_0\&/) {
13663: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
13664: 			    # ignore package.tab specified default values
13665:                             # here &package_tab_default() will fetch those
13666: 			    if ($subp eq 'default') { next; }
13667: 			    my $value=$packagetab{$pack_entry};
13668: 			    my $unikey;
13669: 			    if ($pack =~ /_0$/) {
13670: 				$unikey='parameter_0_'.$name;
13671: 				$part=0;
13672: 			    } else {
13673: 				$unikey='parameter'.$keyroot.'_'.$name;
13674: 			    }
13675: 			    if ($subp eq 'display') {
13676: 				$value.=' [Part: '.$part.']';
13677: 			    }
13678: 			    $metaentry{':'.$unikey.'.part'}=$part;
13679: 			    $metathesekeys{$unikey}=1;
13680: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
13681: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
13682: 			    }
13683: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
13684: 				$metaentry{':'.$unikey}=
13685: 				    $metaentry{':'.$unikey.'.default'};
13686: 			    }
13687: 			}
13688: 		    }
13689: 		} else {
13690: #
13691: # This is not a package - some other kind of start tag
13692: #
13693: 		    my $entry=$token->[1];
13694: 		    my $unikey='';
13695: 
13696: 		    if ($entry eq 'import') {
13697: #
13698: # Importing a library here
13699: #
13700:                         my $location=$parser->get_text('/import');
13701:                         my $dir=$filename;
13702:                         $dir=~s|[^/]*$||;
13703:                         $location=&filelocation($dir,$location);
13704: 
13705:                         my $importid=$token->[2]->{'id'};
13706:                         my $importmode=$token->[2]->{'importmode'};
13707: #
13708: # Check metadata for imported file to
13709: # see if it contained response items
13710: #
13711:                         my ($origfile,@libfilekeys);
13712:                         my %currmetaentry = %metaentry;
13713:                         @libfilekeys = split(/,/,&metadata($location,'keys',undef,undef,undef,
13714:                                                            $depthcount+1));
13715:                         if (grep(/^responseorder$/,@libfilekeys)) {
13716:                             my $libresponseorder = &metadata($location,'responseorder',undef,undef,
13717:                                                              undef,$depthcount+1);
13718:                             if ($libresponseorder ne '') {
13719:                                 if ($#origfiletagids<0) {
13720:                                     undef(%importedrespids);
13721:                                     undef(%importedpartids);
13722:                                 }
13723:                                 my @respids = split(/\s*,\s*/,$libresponseorder);
13724:                                 if (@respids) {
13725:                                     $importedrespids{$importid} = join(',',map { $importid.'_'.$_ } @respids);
13726:                                 }
13727:                                 if ($importedrespids{$importid} ne '') {
13728:                                     $importedresponses = 1;
13729: # We need to get the original file and the imported file to get the response order correct
13730: # Load and inspect original file
13731:                                     if ($#origfiletagids<0) {
13732:                                         my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
13733:                                         $origfile=&getfile($origfilelocation);
13734:                                         @origfiletagids=($origfile=~/<((?:\w+)response|import|part)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
13735:                                     }
13736:                                 }
13737:                             }
13738:                         }
13739: # Do not overwrite contents of %metaentry hash for resource itself with 
13740: # hash populated for imported library file
13741:                         %metaentry = %currmetaentry;
13742:                         undef(%currmetaentry);
13743:                         if ($importmode eq 'part') {
13744: # Import as part(s)
13745:                            $importedparts=1;
13746: # We need to get the original file and the imported file to get the part order correct
13747: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
13748: # Load and inspect original file if we didn't do that already
13749:                            if ($#origfiletagids<0) {
13750:                                undef(%importedrespids);
13751:                                undef(%importedpartids);
13752:                                if ($origfile eq '') {
13753:                                    my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
13754:                                    $origfile=&getfile($origfilelocation);
13755:                                    @origfiletagids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
13756:                                }
13757:                            }
13758:                            my @impfilepartids;
13759: # If <partorder> tag is included in metadata for the imported file
13760: # get the parts in the imported file from that.
13761:                            if (grep(/^partorder$/,@libfilekeys)) {
13762:                                %currmetaentry = %metaentry;
13763:                                my $libpartorder = &metadata($location,'partorder',undef,undef,undef,
13764:                                                             $depthcount+1);
13765:                                %metaentry = %currmetaentry;
13766:                                undef(%currmetaentry);
13767:                                if ($libpartorder ne '') {
13768:                                    @impfilepartids=split(/\s*,\s*/,$libpartorder);
13769:                                }
13770:                            } else {
13771: # If no <partorder> tag available, load and inspect imported file
13772:                                my $impfile=&getfile($location);
13773:                                @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
13774:                            }
13775:                            if ($#impfilepartids>=0) {
13776: # This problem had parts
13777:                                $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
13778:                            } else {
13779: # Importing by turning a single problem into a problem part
13780: # It gets the import-tags ID as part-ID
13781:                                $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
13782:                                $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
13783:                            }
13784:                         } else {
13785: # Import as problem or as normal import
13786:                             $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
13787:                             unless ($importmode eq 'problem') {
13788: # Normal import
13789:                                 if (defined($token->[2]->{'id'})) {
13790:                                     $unikey.='_'.$token->[2]->{'id'};
13791:                                 }
13792:                             }
13793: # Check metadata for imported file to
13794: # see if it contained parts
13795:                             if (grep(/^partorder$/,@libfilekeys)) {
13796:                                 %currmetaentry = %metaentry;
13797:                                 my $libpartorder = &metadata($location,'partorder',undef,undef,undef,
13798:                                                              $depthcount+1);
13799:                                 %metaentry = %currmetaentry;
13800:                                 undef(%currmetaentry);
13801:                                 if ($libpartorder ne '') {
13802:                                     $importedparts = 1;
13803:                                     $importedpartids{$token->[2]->{'id'}}=$libpartorder;
13804:                                 }
13805:                             }
13806:                         }
13807: 			if ($depthcount<20) {
13808: 			    my $metadata = 
13809: 				&metadata($uri,'keys',$toolsymb,$location,$unikey,
13810: 					  $depthcount+1);
13811: 			    foreach my $meta (split(',',$metadata)) {
13812: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
13813: 				$metathesekeys{$meta}=1;
13814: 			    }
13815:                         }
13816: 		    } else {
13817: #
13818: # Not importing, some other kind of non-package, non-library start tag
13819: # 
13820:                         $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
13821:                         if (defined($token->[2]->{'id'})) {
13822:                             $unikey.='_'.$token->[2]->{'id'};
13823:                         }
13824: 			if (defined($token->[2]->{'name'})) { 
13825: 			    $unikey.='_'.$token->[2]->{'name'}; 
13826: 			}
13827: 			$metathesekeys{$unikey}=1;
13828: 			foreach my $param (@{$token->[3]}) {
13829: 			    $metaentry{':'.$unikey.'.'.$param} =
13830: 				$token->[2]->{$param};
13831: 			}
13832: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
13833: 			my $default=$metaentry{':'.$unikey.'.default'};
13834: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
13835: 		 # only ws inside the tag, and not in default, so use default
13836: 		 # as value
13837: 			    $metaentry{':'.$unikey}=$default;
13838: 			} elsif ( $internaltext =~ /\S/ ) {
13839: 		  # something interesting inside the tag
13840: 			    $metaentry{':'.$unikey}=$internaltext;
13841: 			} else {
13842: 		  # no interesting values, don't set a default
13843: 			}
13844: # end of not-a-package not-a-library import
13845: 		    }
13846: # end of not-a-package start tag
13847: 		}
13848: # the next is the end of "start tag"
13849: 	    }
13850: 	}
13851: 	my ($extension) = ($uri =~ /\.(\w+)$/);
13852: 	$extension = lc($extension);
13853: 	if ($extension eq 'htm') { $extension='html'; }
13854: 
13855: 	foreach my $key (keys(%packagetab)) {
13856: 	    #no specific packages #how's our extension
13857: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
13858: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
13859: 					 \%metathesekeys);
13860: 	}
13861: 
13862: 	if (!exists($metaentry{':packages'})
13863: 	    || $packagetab{"import_defaults&extension_$extension"}) {
13864: 	    foreach my $key (keys(%packagetab)) {
13865: 		#no specific packages well let's get default then
13866: 		if ($key!~/^default&/) { next; }
13867: 		&metadata_create_package_def($uri,$key,'default',
13868: 					     \%metathesekeys);
13869: 	    }
13870: 	}
13871: # are there custom rights to evaluate
13872: 	if ($metaentry{':copyright'} eq 'custom') {
13873: 
13874:     #
13875:     # Importing a rights file here
13876:     #
13877: 	    unless ($depthcount) {
13878: 		my $location=$metaentry{':customdistributionfile'};
13879: 		my $dir=$filename;
13880: 		$dir=~s|[^/]*$||;
13881: 		$location=&filelocation($dir,$location);
13882: 		my $rights_metadata =
13883: 		    &metadata($uri,'keys',$toolsymb,$location,'_rights',
13884: 			      $depthcount+1);
13885: 		foreach my $rights (split(',',$rights_metadata)) {
13886: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
13887: 		    $metathesekeys{$rights}=1;
13888: 		}
13889: 	    }
13890: 	}
13891: 	# uniqifiy package listing
13892: 	my %seen;
13893: 	my @uniq_packages =
13894: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
13895: 	$metaentry{':packages'} = join(',',@uniq_packages);
13896: 
13897:         if (($importedresponses) || ($importedparts)) {
13898:             if ($importedparts) {
13899: # We had imported parts and need to rebuild partorder
13900:                 $metaentry{':partorder'}='';
13901:                 $metathesekeys{'partorder'}=1;
13902:             }
13903:             if ($importedresponses) {
13904: # We had imported responses and need to rebuil responseorder
13905:                 $metaentry{':responseorder'}='';
13906:                 $metathesekeys{'responseorder'}=1;
13907:             }
13908:             for (my $index=0;$index<$#origfiletagids;$index+=2) {
13909:                 my $origid = $origfiletagids[$index+1];
13910:                 if ($origfiletagids[$index] eq 'part') {
13911: # Original part, part of the problem
13912:                     if ($importedparts) {
13913:                         $metaentry{':partorder'}.=','.$origid;
13914:                     }
13915:                 } elsif ($origfiletagids[$index] eq 'import') {
13916:                     if ($importedparts) {
13917: # We have imported parts at this position
13918:                         if ($importedpartids{$origid} ne '') {
13919:                             $metaentry{':partorder'}.=','.$importedpartids{$origid};
13920:                         }
13921:                     }
13922:                     if ($importedresponses) {
13923: # We have imported responses at this position
13924:                         if ($importedrespids{$origid} ne '') {
13925:                             $metaentry{':responseorder'}.=','.$importedrespids{$origid};
13926:                         }
13927:                     }
13928:                 } else {
13929: # Original response item, part of the problem
13930:                     if ($importedresponses) {
13931:                         $metaentry{':responseorder'}.=','.$origid;
13932:                     }
13933:                 }
13934:             }
13935:             if ($importedparts) {
13936:                 $metaentry{':partorder'}=~s/^\,//;
13937:             }
13938:             if ($importedresponses) {
13939:                 $metaentry{':responseorder'}=~s/^\,//;
13940:             }
13941:         }
13942: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
13943: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
13944: 	$metaentry{':allpossiblekeys'}=join(',',keys(%metathesekeys));
13945:         unless ($liburi) {
13946: 	    &do_cache_new('meta',$uri,\%metaentry,$cachetime);
13947:         }
13948: # this is the end of "was not already recently cached
13949:     }
13950:     return $metaentry{':'.$what};
13951: }
13952: 
13953: sub metadata_create_package_def {
13954:     my ($uri,$key,$package,$metathesekeys)=@_;
13955:     my ($pack,$name,$subp)=split(/\&/,$key);
13956:     if ($subp eq 'default') { next; }
13957:     
13958:     if (defined($metaentry{':packages'})) {
13959: 	$metaentry{':packages'}.=','.$package;
13960:     } else {
13961: 	$metaentry{':packages'}=$package;
13962:     }
13963:     my $value=$packagetab{$key};
13964:     my $unikey;
13965:     $unikey='parameter_0_'.$name;
13966:     $metaentry{':'.$unikey.'.part'}=0;
13967:     $$metathesekeys{$unikey}=1;
13968:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
13969: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
13970:     }
13971:     if (defined($metaentry{':'.$unikey.'.default'})) {
13972: 	$metaentry{':'.$unikey}=
13973: 	    $metaentry{':'.$unikey.'.default'};
13974:     }
13975: }
13976: 
13977: sub metadata_generate_part0 {
13978:     my ($metadata,$metacache,$uri) = @_;
13979:     my %allnames;
13980:     foreach my $metakey (keys(%$metadata)) {
13981: 	if ($metakey=~/^parameter\_(.*)/) {
13982: 	  my $part=$$metacache{':'.$metakey.'.part'};
13983: 	  my $name=$$metacache{':'.$metakey.'.name'};
13984: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
13985: 	    $allnames{$name}=$part;
13986: 	  }
13987: 	}
13988:     }
13989:     foreach my $name (keys(%allnames)) {
13990:       $$metadata{"parameter_0_$name"}=1;
13991:       my $key=":parameter_0_$name";
13992:       $$metacache{"$key.part"}='0';
13993:       $$metacache{"$key.name"}=$name;
13994:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
13995: 					   $allnames{$name}.'_'.$name.
13996: 					   '.type'};
13997:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
13998: 			     '.display'};
13999:       my $expr='[Part: '.$allnames{$name}.']';
14000:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
14001:       $$metacache{"$key.display"}=$olddis;
14002:     }
14003: }
14004: 
14005: # ------------------------------------------------------ Devalidate title cache
14006: 
14007: sub devalidate_title_cache {
14008:     my ($url)=@_;
14009:     if (!$env{'request.course.id'}) { return; }
14010:     my $symb=&symbread($url);
14011:     if (!$symb) { return; }
14012:     my $key=$env{'request.course.id'}."\0".$symb;
14013:     &devalidate_cache_new('title',$key);
14014: }
14015: 
14016: # ------------------------------------------------- Get the title of a course
14017: 
14018: sub current_course_title {
14019:     return $env{ 'course.' . $env{'request.course.id'} . '.description' };
14020: }
14021: # ------------------------------------------------- Get the title of a resource
14022: 
14023: sub gettitle {
14024:     my $urlsymb=shift;
14025:     my $symb=&symbread($urlsymb);
14026:     if ($symb) {
14027: 	my $key=$env{'request.course.id'}."\0".$symb;
14028: 	my ($result,$cached)=&is_cached_new('title',$key);
14029: 	if (defined($cached)) { 
14030: 	    return $result;
14031: 	}
14032: 	my ($map,$resid,$url)=&decode_symb($symb);
14033: 	my $title='';
14034: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
14035: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
14036: 	} else {
14037: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
14038: 		    &GDBM_READER(),0640)) {
14039: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
14040: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
14041: 		untie(%bighash);
14042: 	    }
14043: 	}
14044: 	$title=~s/\&colon\;/\:/gs;
14045: 	if ($title) {
14046: # Remember both $symb and $title for dynamic metadata
14047:             $accesshash{$symb.'___crstitle'}=$title;
14048:             $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
14049: # Cache this title and then return it
14050: 	    return &do_cache_new('title',$key,$title,600);
14051: 	}
14052: 	$urlsymb=$url;
14053:     }
14054:     my $title=&metadata($urlsymb,'title');
14055:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
14056:     return $title;
14057: }
14058: 
14059: sub get_slot {
14060:     my ($which,$cnum,$cdom)=@_;
14061:     if (!$cnum || !$cdom) {
14062: 	(undef,my $courseid)=&whichuser();
14063: 	$cdom=$env{'course.'.$courseid.'.domain'};
14064: 	$cnum=$env{'course.'.$courseid.'.num'};
14065:     }
14066:     my $key=join("\0",'slots',$cdom,$cnum,$which);
14067:     my %slotinfo;
14068:     if (exists($remembered{$key})) {
14069: 	$slotinfo{$which} = $remembered{$key};
14070:     } else {
14071: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
14072: 	&Apache::lonhomework::showhash(%slotinfo);
14073: 	my ($tmp)=keys(%slotinfo);
14074: 	if ($tmp=~/^error:/) { return (); }
14075: 	$remembered{$key} = $slotinfo{$which};
14076:     }
14077:     if (ref($slotinfo{$which}) eq 'HASH') {
14078: 	return %{$slotinfo{$which}};
14079:     }
14080:     return $slotinfo{$which};
14081: }
14082: 
14083: sub get_reservable_slots {
14084:     my ($cnum,$cdom,$uname,$udom) = @_;
14085:     my $now = time;
14086:     my $reservable_info;
14087:     my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
14088:     if (exists($remembered{$key})) {
14089:         $reservable_info = $remembered{$key};
14090:     } else {
14091:         my %resv;
14092:         ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
14093:         &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
14094:         $reservable_info = \%resv;
14095:         $remembered{$key} = $reservable_info;
14096:     }
14097:     return $reservable_info;
14098: }
14099: 
14100: sub get_course_slots {
14101:     my ($cnum,$cdom) = @_;
14102:     my $hashid=$cnum.':'.$cdom;
14103:     my ($result,$cached) = &is_cached_new('allslots',$hashid);
14104:     if (defined($cached)) {
14105:         if (ref($result) eq 'HASH') {
14106:             return %{$result};
14107:         }
14108:     } else {
14109:         my %slots=&dump('slots',$cdom,$cnum);
14110:         my ($tmp) = keys(%slots);
14111:         if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
14112:             &do_cache_new('allslots',$hashid,\%slots,600);
14113:             return %slots;
14114:         }
14115:     }
14116:     return;
14117: }
14118: 
14119: sub devalidate_slots_cache {
14120:     my ($cnum,$cdom)=@_;
14121:     my $hashid=$cnum.':'.$cdom;
14122:     &devalidate_cache_new('allslots',$hashid);
14123: }
14124: 
14125: sub get_coursechange {
14126:     my ($cdom,$cnum) = @_;
14127:     if ($cdom eq '' || $cnum eq '') {
14128:         return unless ($env{'request.course.id'});
14129:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
14130:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
14131:     }
14132:     my $hashid=$cdom.'_'.$cnum;
14133:     my ($change,$cached)=&is_cached_new('crschange',$hashid);
14134:     if ((defined($cached)) && ($change ne '')) {
14135:         return $change;
14136:     } else {
14137:         my %crshash;
14138:         %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
14139:         if ($crshash{'internal.contentchange'} eq '') {
14140:             $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
14141:             if ($change eq '') {
14142:                 %crshash = &get('environment',['internal.created'],$cdom,$cnum);
14143:                 $change = $crshash{'internal.created'};
14144:             }
14145:         } else {
14146:             $change = $crshash{'internal.contentchange'};
14147:         }
14148:         my $cachetime = 600;
14149:         &do_cache_new('crschange',$hashid,$change,$cachetime);
14150:     }
14151:     return $change;
14152: }
14153: 
14154: sub devalidate_coursechange_cache {
14155:     my ($cdom,$cnum)=@_;
14156:     my $hashid=$cdom.'_'.$cnum;
14157:     &devalidate_cache_new('crschange',$hashid);
14158: }
14159: 
14160: sub get_suppchange {
14161:     my ($cdom,$cnum) = @_;
14162:     if ($cdom eq '' || $cnum eq '') {
14163:         return unless ($env{'request.course.id'});
14164:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
14165:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
14166:     }
14167:     my $hashid=$cdom.'_'.$cnum;
14168:     my ($change,$cached)=&is_cached_new('suppchange',$hashid);
14169:     if ((defined($cached)) && ($change ne '')) {
14170:         return $change;
14171:     } else {
14172:         my %crshash = &get('environment',['internal.supplementalchange'],$cdom,$cnum);
14173:         if ($crshash{'internal.supplementalchange'} eq '') {
14174:             $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
14175:             if ($change eq '') {
14176:                 %crshash = &get('environment',['internal.created'],$cdom,$cnum);
14177:                 $change = $crshash{'internal.created'};
14178:             }
14179:         } else {
14180:             $change = $crshash{'internal.supplementalchange'};
14181:         }
14182:         my $cachetime = 600;
14183:         &do_cache_new('suppchange',$hashid,$change,$cachetime);
14184:     }
14185:     return $change;
14186: }
14187: 
14188: sub devalidate_suppchange_cache {
14189:     my ($cdom,$cnum)=@_;
14190:     my $hashid=$cdom.'_'.$cnum;
14191:     &devalidate_cache_new('suppchange',$hashid);
14192: }
14193: 
14194: sub update_supp_caches {
14195:     my ($cdom,$cnum) = @_;
14196:     my %servers = &internet_dom_servers($cdom);
14197:     my @ids=&current_machine_ids();
14198:     foreach my $server (keys(%servers)) {
14199:         next if (grep(/^\Q$server\E$/,@ids));
14200:         my $hashid=$cnum.':'.$cdom;
14201:         my $cachekey = &escape('showsupp').':'.&escape($hashid);
14202:         &remote_devalidate_cache($server,[$cachekey]);
14203:     }
14204:     &has_unhidden_suppfiles($cnum,$cdom,1,1);
14205:     &count_supptools($cnum,$cdom,1);
14206:     my $now = time;
14207:     if ($env{'request.course.id'} eq $cdom.'_'.$cnum) {
14208:         &Apache::lonnet::appenv({'request.course.suppupdated' => $now});
14209:     }
14210:     &put('environment',{'internal.supplementalchange' => $now},
14211:          $cdom,$cnum);
14212:     &Apache::lonnet::appenv(
14213:         {'course.'.$cdom.'_'.$cnum.'.internal.supplementalchange' => $now});
14214:     &do_cache_new('suppchange',$cdom.'_'.$cnum,$now,600);
14215: }
14216: 
14217: # ------------------------------------------------- Update symbolic store links
14218: 
14219: sub symblist {
14220:     my ($mapname,%newhash)=@_;
14221:     $mapname=&deversion(&declutter($mapname));
14222:     my %hash;
14223:     if (($env{'request.course.fn'}) && (%newhash)) {
14224:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
14225:                       &GDBM_WRCREAT(),0640)) {
14226: 	    foreach my $url (keys(%newhash)) {
14227: 		next if ($url eq 'last_known'
14228: 			 && $env{'form.no_update_last_known'});
14229: 		$hash{declutter($url)}=&encode_symb($mapname,
14230: 						    $newhash{$url}->[1],
14231: 						    $newhash{$url}->[0]);
14232:             }
14233:             if (untie(%hash)) {
14234: 		return 'ok';
14235:             }
14236:         }
14237:     }
14238:     return 'error';
14239: }
14240: 
14241: # --------------------------------------------------------------- Verify a symb
14242: 
14243: sub symbverify {
14244:     my ($symb,$thisurl,$encstate)=@_;
14245:     my $thisfn=$thisurl;
14246:     $thisfn=&declutter($thisfn);
14247: # direct jump to resource in page or to a sequence - will construct own symbs
14248:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
14249: # check URL part
14250:     my ($map,$resid,$url)=&decode_symb($symb);
14251: 
14252:     unless ($url eq $thisfn) { return 0; }
14253: 
14254:     $symb=&symbclean($symb);
14255:     $thisurl=&deversion($thisurl);
14256:     $thisfn=&deversion($thisfn);
14257: 
14258:     my %bighash;
14259:     my $okay=0;
14260: 
14261:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
14262:                             &GDBM_READER(),0640)) {
14263:         if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
14264:             $thisurl =~ s/\?.+$//;
14265:             if ($map =~ m{^uploaded/.+\.page$}) {
14266:                 $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
14267:                 $thisurl =~ s{^\Qhttp://https://\E}{https://};
14268:             }
14269:         }
14270:         my $ids;
14271:         if ($map =~ m{^uploaded/.+\.page$}) {
14272:             $ids=$bighash{'ids_'.&clutter_with_no_wrapper($thisurl)};
14273:         } else {
14274:             $ids=$bighash{'ids_'.&clutter($thisurl)};
14275:         }
14276:         unless ($ids) {
14277:             my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;  
14278:             $ids=$bighash{$idkey};
14279:         }
14280:         if ($ids) {
14281: # ------------------------------------------------------------------- Has ID(s)
14282:             if ($thisfn =~ m{^/adm/wrapper/ext/}) {
14283:                 $symb =~ s/\?.+$//;
14284:             }
14285: 	    foreach my $id (split(/\,/,$ids)) {
14286: 	       my ($mapid,$resid)=split(/\./,$id);
14287:                if (
14288:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
14289:    eq $symb) {
14290:                    if (ref($encstate)) {
14291:                        $$encstate = $bighash{'encrypted_'.$id};
14292:                    }
14293: 		   if (($env{'request.role.adv'}) ||
14294: 		       ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
14295:                        ($thisurl eq '/adm/navmaps')) {
14296: 		       $okay=1;
14297:                        last;
14298: 		   }
14299: 	       }
14300: 	   }
14301:         }
14302: 	untie(%bighash);
14303:     }
14304:     return $okay;
14305: }
14306: 
14307: # --------------------------------------------------------------- Clean-up symb
14308: 
14309: sub symbclean {
14310:     my $symb=shift;
14311:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
14312: # remove version from map
14313:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
14314: 
14315: # remove version from URL
14316:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
14317: 
14318: # remove wrapper
14319: 
14320:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
14321:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
14322:     return $symb;
14323: }
14324: 
14325: # ---------------------------------------------- Split symb to find map and url
14326: 
14327: sub encode_symb {
14328:     my ($map,$resid,$url)=@_;
14329:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
14330: }
14331: 
14332: sub decode_symb {
14333:     my $symb=shift;
14334:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
14335:     my ($map,$resid,$url)=split(/___/,$symb);
14336:     return (&fixversion($map),$resid,&fixversion($url));
14337: }
14338: 
14339: sub fixversion {
14340:     my $fn=shift;
14341:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
14342:     my %bighash;
14343:     my $uri=&clutter($fn);
14344:     my $key=$env{'request.course.id'}.'_'.$uri;
14345: # is this cached?
14346:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
14347:     if (defined($cached)) { return $result; }
14348: # unfortunately not cached, or expired
14349:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
14350: 	    &GDBM_READER(),0640)) {
14351:  	if ($bighash{'version_'.$uri}) {
14352:  	    my $version=$bighash{'version_'.$uri};
14353:  	    unless (($version eq 'mostrecent') || 
14354: 		    ($version==&getversion($uri))) {
14355:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
14356:  	    }
14357:  	}
14358:  	untie %bighash;
14359:     }
14360:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
14361: }
14362: 
14363: sub deversion {
14364:     my $url=shift;
14365:     $url=~s/\.\d+\.(\w+)$/\.$1/;
14366:     return $url;
14367: }
14368: 
14369: # ------------------------------------------------------ Return symb list entry
14370: 
14371: sub symbread {
14372:     my ($thisfn,$donotrecurse,$ignorecachednull,$checkforblock,$possibles,
14373:         $ignoresymbdb,$noenccheck)=@_;
14374:     my $cache_str='request.symbread.cached.'.$thisfn;
14375:     if (defined($env{$cache_str})) {
14376:         unless (ref($possibles) eq 'HASH') {
14377:             if ($ignorecachednull) {
14378:                 return $env{$cache_str} unless ($env{$cache_str} eq '');
14379:             } else {
14380:                 return $env{$cache_str};
14381:             }
14382:         }
14383:     }
14384: # no filename provided? try from environment
14385:     unless ($thisfn) {
14386:         if ($env{'request.symb'}) {
14387:             return $env{$cache_str}=&symbclean($env{'request.symb'});
14388: 	}
14389: 	$thisfn=$env{'request.filename'};
14390:     }
14391:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
14392: # is that filename actually a symb? Verify, clean, and return
14393:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
14394: 	if (&symbverify($thisfn,$1)) {
14395: 	    return $env{$cache_str}=&symbclean($thisfn);
14396: 	}
14397:     }
14398:     $thisfn=declutter($thisfn);
14399:     my %hash;
14400:     my %bighash;
14401:     my $syval='';
14402:     if (($env{'request.course.fn'}) && ($thisfn)) {
14403:         unless ($ignoresymbdb) {
14404:             if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
14405:                           &GDBM_READER(),0640)) {
14406: 	        $syval=$hash{$thisfn};
14407:                 untie(%hash);
14408:             }
14409:             if ($syval && $checkforblock) {
14410:                 my @blockers = &has_comm_blocking('bre',$syval,$thisfn,$ignoresymbdb,$noenccheck);
14411:                 if (@blockers) {
14412:                     $syval='';
14413:                 }
14414:             }
14415:         }
14416: # ---------------------------------------------------------- There was an entry
14417:         if ($syval) {
14418: 	    #unless ($syval=~/\_\d+$/) {
14419: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
14420: 		    #&appenv({'request.ambiguous' => $thisfn});
14421: 		    #return $env{$cache_str}='';
14422: 		#}    
14423: 		#$syval.=$1;
14424: 	    #}
14425:         } else {
14426: # ------------------------------------------------------- Was not in symb table
14427:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
14428:                             &GDBM_READER(),0640)) {
14429: # ---------------------------------------------- Get ID(s) for current resource
14430:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
14431:               unless ($ids) { 
14432:                  $ids=$bighash{'ids_/'.$thisfn};
14433:               }
14434:               unless ($ids) {
14435: # alias?
14436: 		  $ids=$bighash{'mapalias_'.$thisfn};
14437:               }
14438:               if ($ids) {
14439: # ------------------------------------------------------------------- Has ID(s)
14440:                  my @possibilities=split(/\,/,$ids);
14441:                  if ($#possibilities==0) {
14442: # ----------------------------------------------- There is only one possibility
14443: 		     my ($mapid,$resid)=split(/\./,$ids);
14444: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
14445: 						    $resid,$thisfn);
14446:                      if (ref($possibles) eq 'HASH') {
14447:                          unless ($bighash{'randomout_'.$ids} || $env{'request.role.adv'}) {
14448:                              $possibles->{$syval} = 1;
14449:                          }
14450:                      }
14451:                      if ($checkforblock) {
14452:                          unless ($bighash{'randomout_'.$ids} || $env{'request.role.adv'}) {
14453:                              my @blockers = &has_comm_blocking('bre',$syval,$bighash{'src_'.$ids},'',$noenccheck);
14454:                              if (@blockers) {
14455:                                  $syval = '';
14456:                                  untie(%bighash);
14457:                                  return $env{$cache_str}='';
14458:                              }
14459:                          }
14460:                      }
14461:                  } elsif ((!$donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) { 
14462: # ------------------------------------------ There is more than one possibility
14463:                      my $realpossible=0;
14464:                      foreach my $id (@possibilities) {
14465: 			 my $file=$bighash{'src_'.$id};
14466:                          my $canaccess;
14467:                          if (($donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
14468:                              $canaccess = 1;
14469:                          } else { 
14470:                              $canaccess = &allowed('bre',$file);
14471:                          }
14472:                          if ($canaccess) {
14473:          		     my ($mapid,$resid)=split(/\./,$id);
14474:                              if ($bighash{'map_type_'.$mapid} ne 'page') {
14475:                                  my $poss_syval=&encode_symb($bighash{'map_id_'.$mapid},
14476: 						             $resid,$thisfn);
14477:                                  next if ($bighash{'randomout_'.$id} && !$env{'request.role.adv'});
14478:                                  next unless (($noenccheck) || ($bighash{'encrypted_'.$id} eq $env{'request.enc'}));
14479:                                  if ($checkforblock) {
14480:                                      my @blockers = &has_comm_blocking('bre',$poss_syval,$file,'',$noenccheck);
14481:                                      if (@blockers > 0) {
14482:                                          $syval = '';
14483:                                      } else {
14484:                                          $syval = $poss_syval;
14485:                                          $realpossible++;
14486:                                      }
14487:                                  } else {
14488:                                      $syval = $poss_syval;
14489:                                      $realpossible++;
14490:                                  }
14491:                                  if ($syval) {
14492:                                      if (ref($possibles) eq 'HASH') {
14493:                                          $possibles->{$syval} = 1;
14494:                                      }
14495:                                  }
14496:                              }
14497: 			 }
14498:                      }
14499: 		     if ($realpossible!=1) { $syval=''; }
14500:                  } else {
14501:                      $syval='';
14502:                  }
14503: 	      }
14504:               untie(%bighash);
14505:            }
14506:         }
14507:         if ($syval) {
14508: 	    return $env{$cache_str}=$syval;
14509:         }
14510:     }
14511:     &appenv({'request.ambiguous' => $thisfn});
14512:     return $env{$cache_str}='';
14513: }
14514: 
14515: # ---------------------------------------------------------- Return random seed
14516: 
14517: sub numval {
14518:     my $txt=shift;
14519:     $txt=~tr/A-J/0-9/;
14520:     $txt=~tr/a-j/0-9/;
14521:     $txt=~tr/K-T/0-9/;
14522:     $txt=~tr/k-t/0-9/;
14523:     $txt=~tr/U-Z/0-5/;
14524:     $txt=~tr/u-z/0-5/;
14525:     $txt=~s/\D//g;
14526:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
14527:     return int($txt);
14528: }
14529: 
14530: sub numval2 {
14531:     my $txt=shift;
14532:     $txt=~tr/A-J/0-9/;
14533:     $txt=~tr/a-j/0-9/;
14534:     $txt=~tr/K-T/0-9/;
14535:     $txt=~tr/k-t/0-9/;
14536:     $txt=~tr/U-Z/0-5/;
14537:     $txt=~tr/u-z/0-5/;
14538:     $txt=~s/\D//g;
14539:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
14540:     my $total;
14541:     foreach my $val (@txts) { $total+=$val; }
14542:     if ($_64bit) { if ($total > 2**32) { return -1; } }
14543:     return int($total);
14544: }
14545: 
14546: sub numval3 {
14547:     use integer;
14548:     my $txt=shift;
14549:     $txt=~tr/A-J/0-9/;
14550:     $txt=~tr/a-j/0-9/;
14551:     $txt=~tr/K-T/0-9/;
14552:     $txt=~tr/k-t/0-9/;
14553:     $txt=~tr/U-Z/0-5/;
14554:     $txt=~tr/u-z/0-5/;
14555:     $txt=~s/\D//g;
14556:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
14557:     my $total;
14558:     foreach my $val (@txts) { $total+=$val; }
14559:     if ($_64bit) { $total=(($total<<32)>>32); }
14560:     return $total;
14561: }
14562: 
14563: sub digest {
14564:     my ($data)=@_;
14565:     my $digest=&Digest::MD5::md5($data);
14566:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
14567:     my ($e,$f);
14568:     {
14569:         use integer;
14570:         $e=($a+$b);
14571:         $f=($c+$d);
14572:         if ($_64bit) {
14573:             $e=(($e<<32)>>32);
14574:             $f=(($f<<32)>>32);
14575:         }
14576:     }
14577:     if (wantarray) {
14578: 	return ($e,$f);
14579:     } else {
14580: 	my $g;
14581: 	{
14582: 	    use integer;
14583: 	    $g=($e+$f);
14584: 	    if ($_64bit) {
14585: 		$g=(($g<<32)>>32);
14586: 	    }
14587: 	}
14588: 	return $g;
14589:     }
14590: }
14591: 
14592: sub latest_rnd_algorithm_id {
14593:     return '64bit5';
14594: }
14595: 
14596: sub get_rand_alg {
14597:     my ($courseid)=@_;
14598:     if (!$courseid) { $courseid=(&whichuser())[1]; }
14599:     if ($courseid) {
14600: 	return $env{"course.$courseid.rndseed"};
14601:     }
14602:     return &latest_rnd_algorithm_id();
14603: }
14604: 
14605: sub validCODE {
14606:     my ($CODE)=@_;
14607:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
14608:     return 0;
14609: }
14610: 
14611: sub getCODE {
14612:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
14613:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
14614: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
14615: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
14616: 	return $Apache::lonhomework::history{'resource.CODE'};
14617:     }
14618:     return undef;
14619: }
14620: #
14621: #  Determines the random seed for a specific context:
14622: #
14623: # parameters:
14624: #   symb      - in course context the symb for the seed.
14625: #   course_id - The course id of the form domain_coursenum.
14626: #   domain    - Domain for the user.
14627: #   course    - Course for the user.
14628: #   cenv      - environment of the course.
14629: #
14630: # NOTE:
14631: #   All parameters are picked out of the environment if missing
14632: #   or not defined.
14633: #   If a symb cannot be determined the current time is used instead.
14634: #
14635: #  For a given well defined symb, courside, domain, username,
14636: #  and course environment, the seed is reproducible.
14637: #
14638: sub rndseed {
14639:     my ($symb,$courseid,$domain,$username, $cenv)=@_;
14640:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
14641:     if (!defined($symb)) {
14642: 	unless ($symb=$wsymb) { return time; }
14643:     }
14644:     if (!defined $courseid) { 
14645: 	$courseid=$wcourseid; 
14646:     }
14647:     if (!defined $domain) { $domain=$wdomain; }
14648:     if (!defined $username) { $username=$wusername }
14649: 
14650:     my $which;
14651:     if (defined($cenv->{'rndseed'})) {
14652: 	$which = $cenv->{'rndseed'};
14653:     } else {
14654: 	$which =&get_rand_alg($courseid);
14655:     }
14656:     if (defined(&getCODE())) {
14657: 
14658: 	if ($which eq '64bit5') {
14659: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
14660: 	} elsif ($which eq '64bit4') {
14661: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
14662: 	} else {
14663: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
14664: 	}
14665:     } elsif ($which eq '64bit5') {
14666: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
14667:     } elsif ($which eq '64bit4') {
14668: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
14669:     } elsif ($which eq '64bit3') {
14670: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
14671:     } elsif ($which eq '64bit2') {
14672: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
14673:     } elsif ($which eq '64bit') {
14674: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
14675:     }
14676:     return &rndseed_32bit($symb,$courseid,$domain,$username);
14677: }
14678: 
14679: sub rndseed_32bit {
14680:     my ($symb,$courseid,$domain,$username)=@_;
14681:     {
14682: 	use integer;
14683: 	my $symbchck=unpack("%32C*",$symb) << 27;
14684: 	my $symbseed=numval($symb) << 22;
14685: 	my $namechck=unpack("%32C*",$username) << 17;
14686: 	my $nameseed=numval($username) << 12;
14687: 	my $domainseed=unpack("%32C*",$domain) << 7;
14688: 	my $courseseed=unpack("%32C*",$courseid);
14689: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
14690: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
14691: 	#&logthis("rndseed :$num:$symb");
14692: 	if ($_64bit) { $num=(($num<<32)>>32); }
14693: 	return $num;
14694:     }
14695: }
14696: 
14697: sub rndseed_64bit {
14698:     my ($symb,$courseid,$domain,$username)=@_;
14699:     {
14700: 	use integer;
14701: 	my $symbchck=unpack("%32S*",$symb) << 21;
14702: 	my $symbseed=numval($symb) << 10;
14703: 	my $namechck=unpack("%32S*",$username);
14704: 	
14705: 	my $nameseed=numval($username) << 21;
14706: 	my $domainseed=unpack("%32S*",$domain) << 10;
14707: 	my $courseseed=unpack("%32S*",$courseid);
14708: 	
14709: 	my $num1=$symbchck+$symbseed+$namechck;
14710: 	my $num2=$nameseed+$domainseed+$courseseed;
14711: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
14712: 	#&logthis("rndseed :$num:$symb");
14713: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
14714: 	return "$num1,$num2";
14715:     }
14716: }
14717: 
14718: sub rndseed_64bit2 {
14719:     my ($symb,$courseid,$domain,$username)=@_;
14720:     {
14721: 	use integer;
14722: 	# strings need to be an even # of cahracters long, it it is odd the
14723:         # last characters gets thrown away
14724: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
14725: 	my $symbseed=numval($symb) << 10;
14726: 	my $namechck=unpack("%32S*",$username.' ');
14727: 	
14728: 	my $nameseed=numval($username) << 21;
14729: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
14730: 	my $courseseed=unpack("%32S*",$courseid.' ');
14731: 	
14732: 	my $num1=$symbchck+$symbseed+$namechck;
14733: 	my $num2=$nameseed+$domainseed+$courseseed;
14734: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
14735: 	#&logthis("rndseed :$num:$symb");
14736: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
14737: 	return "$num1,$num2";
14738:     }
14739: }
14740: 
14741: sub rndseed_64bit3 {
14742:     my ($symb,$courseid,$domain,$username)=@_;
14743:     {
14744: 	use integer;
14745: 	# strings need to be an even # of cahracters long, it it is odd the
14746:         # last characters gets thrown away
14747: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
14748: 	my $symbseed=numval2($symb) << 10;
14749: 	my $namechck=unpack("%32S*",$username.' ');
14750: 	
14751: 	my $nameseed=numval2($username) << 21;
14752: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
14753: 	my $courseseed=unpack("%32S*",$courseid.' ');
14754: 	
14755: 	my $num1=$symbchck+$symbseed+$namechck;
14756: 	my $num2=$nameseed+$domainseed+$courseseed;
14757: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
14758: 	#&logthis("rndseed :$num1:$num2:$_64bit");
14759: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
14760: 	
14761: 	return "$num1:$num2";
14762:     }
14763: }
14764: 
14765: sub rndseed_64bit4 {
14766:     my ($symb,$courseid,$domain,$username)=@_;
14767:     {
14768: 	use integer;
14769: 	# strings need to be an even # of cahracters long, it it is odd the
14770:         # last characters gets thrown away
14771: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
14772: 	my $symbseed=numval3($symb) << 10;
14773: 	my $namechck=unpack("%32S*",$username.' ');
14774: 	
14775: 	my $nameseed=numval3($username) << 21;
14776: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
14777: 	my $courseseed=unpack("%32S*",$courseid.' ');
14778: 	
14779: 	my $num1=$symbchck+$symbseed+$namechck;
14780: 	my $num2=$nameseed+$domainseed+$courseseed;
14781: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
14782: 	#&logthis("rndseed :$num1:$num2:$_64bit");
14783: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
14784: 	
14785: 	return "$num1:$num2";
14786:     }
14787: }
14788: 
14789: sub rndseed_64bit5 {
14790:     my ($symb,$courseid,$domain,$username)=@_;
14791:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
14792:     return "$num1:$num2";
14793: }
14794: 
14795: sub rndseed_CODE_64bit {
14796:     my ($symb,$courseid,$domain,$username)=@_;
14797:     {
14798: 	use integer;
14799: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
14800: 	my $symbseed=numval2($symb);
14801: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
14802: 	my $CODEseed=numval(&getCODE());
14803: 	my $courseseed=unpack("%32S*",$courseid.' ');
14804: 	my $num1=$symbseed+$CODEchck;
14805: 	my $num2=$CODEseed+$courseseed+$symbchck;
14806: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
14807: 	#&logthis("rndseed :$num1:$num2:$symb");
14808: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
14809: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
14810: 	return "$num1:$num2";
14811:     }
14812: }
14813: 
14814: sub rndseed_CODE_64bit4 {
14815:     my ($symb,$courseid,$domain,$username)=@_;
14816:     {
14817: 	use integer;
14818: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
14819: 	my $symbseed=numval3($symb);
14820: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
14821: 	my $CODEseed=numval3(&getCODE());
14822: 	my $courseseed=unpack("%32S*",$courseid.' ');
14823: 	my $num1=$symbseed+$CODEchck;
14824: 	my $num2=$CODEseed+$courseseed+$symbchck;
14825: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
14826: 	#&logthis("rndseed :$num1:$num2:$symb");
14827: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
14828: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
14829: 	return "$num1:$num2";
14830:     }
14831: }
14832: 
14833: sub rndseed_CODE_64bit5 {
14834:     my ($symb,$courseid,$domain,$username)=@_;
14835:     my $code = &getCODE();
14836:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
14837:     return "$num1:$num2";
14838: }
14839: 
14840: sub setup_random_from_rndseed {
14841:     my ($rndseed)=@_;
14842:     if ($rndseed =~/([,:])/) {
14843:         my ($num1,$num2) = map { abs($_); } (split(/[,:]/,$rndseed));
14844:         if ((!$num1) || (!$num2) || ($num1 > 2147483562) || ($num2 > 2147483398)) {
14845:             &Math::Random::random_set_seed_from_phrase($rndseed);
14846:         } else {
14847:             &Math::Random::random_set_seed($num1,$num2);
14848:         }
14849:     } else {
14850: 	&Math::Random::random_set_seed_from_phrase($rndseed);
14851:     }
14852: }
14853: 
14854: sub latest_receipt_algorithm_id {
14855:     return 'receipt3';
14856: }
14857: 
14858: sub recunique {
14859:     my $fucourseid=shift;
14860:     my $unique;
14861:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
14862: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
14863: 	$unique=$env{"course.$fucourseid.internal.encseed"};
14864:     } else {
14865: 	$unique=$perlvar{'lonReceipt'};
14866:     }
14867:     return unpack("%32C*",$unique);
14868: }
14869: 
14870: sub recprefix {
14871:     my $fucourseid=shift;
14872:     my $prefix;
14873:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
14874: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
14875: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
14876:     } else {
14877: 	$prefix=$perlvar{'lonHostID'};
14878:     }
14879:     return unpack("%32C*",$prefix);
14880: }
14881: 
14882: sub ireceipt {
14883:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
14884: 
14885:     my $return =&recprefix($fucourseid).'-';
14886: 
14887:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
14888: 	$env{'request.state'} eq 'construct') {
14889: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
14890: 	return $return;
14891:     }
14892: 
14893:     my $cuname=unpack("%32C*",$funame);
14894:     my $cudom=unpack("%32C*",$fudom);
14895:     my $cucourseid=unpack("%32C*",$fucourseid);
14896:     my $cusymb=unpack("%32C*",$fusymb);
14897:     my $cunique=&recunique($fucourseid);
14898:     my $cpart=unpack("%32S*",$part);
14899:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
14900: 
14901: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
14902: 			       
14903: 	$return.= ($cunique%$cuname+
14904: 		   $cunique%$cudom+
14905: 		   $cusymb%$cuname+
14906: 		   $cusymb%$cudom+
14907: 		   $cucourseid%$cuname+
14908: 		   $cucourseid%$cudom+
14909: 		   $cpart%$cuname+
14910: 		   $cpart%$cudom);
14911:     } else {
14912: 	$return.= ($cunique%$cuname+
14913: 		   $cunique%$cudom+
14914: 		   $cusymb%$cuname+
14915: 		   $cusymb%$cudom+
14916: 		   $cucourseid%$cuname+
14917: 		   $cucourseid%$cudom);
14918:     }
14919:     return $return;
14920: }
14921: 
14922: sub receipt {
14923:     my ($part)=@_;
14924:     my ($symb,$courseid,$domain,$name) = &whichuser();
14925:     return &ireceipt($name,$domain,$courseid,$symb,$part);
14926: }
14927: 
14928: sub whichuser {
14929:     my ($passedsymb)=@_;
14930:     my ($symb,$courseid,$domain,$name,$publicuser);
14931:     if (defined($env{'form.grade_symb'})) {
14932: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
14933: 	my $allowed=&allowed('vgr',$tmp_courseid);
14934: 	if (!$allowed &&
14935: 	    exists($env{'request.course.sec'}) &&
14936: 	    $env{'request.course.sec'} !~ /^\s*$/) {
14937: 	    $allowed=&allowed('vgr',$tmp_courseid.
14938: 			      '/'.$env{'request.course.sec'});
14939: 	}
14940: 	if ($allowed) {
14941: 	    ($symb)=&get_env_multiple('form.grade_symb');
14942: 	    $courseid=$tmp_courseid;
14943: 	    ($domain)=&get_env_multiple('form.grade_domain');
14944: 	    ($name)=&get_env_multiple('form.grade_username');
14945: 	    return ($symb,$courseid,$domain,$name,$publicuser);
14946: 	}
14947:     }
14948:     if (!$passedsymb) {
14949: 	$symb=&symbread();
14950:     } else {
14951: 	$symb=$passedsymb;
14952:     }
14953:     $courseid=$env{'request.course.id'};
14954:     $domain=$env{'user.domain'};
14955:     $name=$env{'user.name'};
14956:     if ($name eq 'public' && $domain eq 'public') {
14957: 	if (!defined($env{'form.username'})) {
14958: 	    $env{'form.username'}.=time.rand(10000000);
14959: 	}
14960: 	$name.=$env{'form.username'};
14961:     }
14962:     return ($symb,$courseid,$domain,$name,$publicuser);
14963: 
14964: }
14965: 
14966: # ------------------------------------------------------------ Serves up a file
14967: # returns either the contents of the file or 
14968: # -1 if the file doesn't exist
14969: #
14970: # if the target is a file that was uploaded via DOCS, 
14971: # a check will be made to see if a current copy exists on the local server,
14972: # if it does this will be served, otherwise a copy will be retrieved from
14973: # the home server for the course and stored in /home/httpd/html/userfiles on
14974: # the local server.   
14975: 
14976: sub getfile {
14977:     my ($file) = @_;
14978:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
14979:     &repcopy($file);
14980:     return &readfile($file);
14981: }
14982: 
14983: sub repcopy_userfile {
14984:     my ($file)=@_;
14985:     my $londocroot = $perlvar{'lonDocRoot'};
14986:     if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
14987:     if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
14988:     my ($cdom,$cnum,$filename) = 
14989: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
14990:     my $uri="/uploaded/$cdom/$cnum/$filename";
14991:     if (-e "$file") {
14992: # we already have a local copy, check it out
14993: 	my @fileinfo = stat($file);
14994: 	my $rtncode;
14995: 	my $info;
14996: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
14997: 	if ($lwpresp ne 'ok') {
14998: # there is no such file anymore, even though we had a local copy
14999: 	    if ($rtncode eq '404') {
15000: 		unlink($file);
15001: 	    }
15002: 	    return -1;
15003: 	}
15004: 	if ($info < $fileinfo[9]) {
15005: # nice, the file we have is up-to-date, just say okay
15006: 	    return 'ok';
15007: 	} else {
15008: # the file is outdated, get rid of it
15009: 	    unlink($file);
15010: 	}
15011:     }
15012: # one way or the other, at this point, we don't have the file
15013: # construct the correct path for the file
15014:     my @parts = ($cdom,$cnum); 
15015:     if ($filename =~ m|^(.+)/[^/]+$|) {
15016: 	push @parts, split(/\//,$1);
15017:     }
15018:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
15019:     foreach my $part (@parts) {
15020: 	$path .= '/'.$part;
15021: 	if (!-e $path) {
15022: 	    mkdir($path,0770);
15023: 	}
15024:     }
15025: # now the path exists for sure
15026: # get a user agent
15027:     my $transferfile=$file.'.in.transfer';
15028: # FIXME: this should flock
15029:     if (-e $transferfile) { return 'ok'; }
15030:     my $request;
15031:     $uri=~s/^\///;
15032:     my $homeserver = &homeserver($cnum,$cdom);
15033:     my $hostname = &hostname($homeserver);
15034:     my $protocol = $protocol{$homeserver};
15035:     $protocol = 'http' if ($protocol ne 'https');
15036:     $request=new HTTP::Request('GET',$protocol.'://'.$hostname.'/raw/'.$uri);
15037:     my $response = &LONCAPA::LWPReq::makerequest($homeserver,$request,$transferfile,\%perlvar,'',0,1);
15038: # did it work?
15039:     if ($response->is_error()) {
15040: 	unlink($transferfile);
15041: 	&logthis("Userfile repcopy failed for $uri");
15042: 	return -1;
15043:     }
15044: # worked, rename the transfer file
15045:     rename($transferfile,$file);
15046:     return 'ok';
15047: }
15048: 
15049: sub tokenwrapper {
15050:     my $uri=shift;
15051:     $uri=~s|^https?\://([^/]+)||;
15052:     $uri=~s|^/||;
15053:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
15054:     my $token=$1;
15055:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
15056:     if ($udom && $uname && $file) {
15057: 	$file=~s|(\?\.*)*$||;
15058:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
15059:         my $homeserver = &homeserver($uname,$udom);
15060:         my $hostname = &hostname($homeserver);
15061:         my $protocol = $protocol{$homeserver};
15062:         $protocol = 'http' if ($protocol ne 'https');
15063:         return $protocol.'://'.$hostname.'/'.$uri.
15064:                (($uri=~/\?/)?'&':'?').'token='.$token.
15065:                                '&tokenissued='.$perlvar{'lonHostID'};
15066:     } else {
15067:         return '/adm/notfound.html';
15068:     }
15069: }
15070: 
15071: # call with reqtype HEAD: get last modification time
15072: # call with reqtype GET: get the file contents
15073: # Do not call this with reqtype GET for large files! It loads everything into memory
15074: #
15075: sub getuploaded {
15076:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
15077:     $uri=~s/^\///;
15078:     my $homeserver = &homeserver($cnum,$cdom);
15079:     my $hostname = &hostname($homeserver);
15080:     my $protocol = $protocol{$homeserver};
15081:     $protocol = 'http' if ($protocol ne 'https');
15082:     $uri = $protocol.'://'.$hostname.'/raw/'.$uri;
15083:     my $request=new HTTP::Request($reqtype,$uri);
15084:     my $response=&LONCAPA::LWPReq::makerequest($homeserver,$request,'',\%perlvar,'',0,1);
15085:     $$rtncode = $response->code;
15086:     if (! $response->is_success()) {
15087: 	return 'failed';
15088:     }      
15089:     if ($reqtype eq 'HEAD') {
15090: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
15091:     } elsif ($reqtype eq 'GET') {
15092: 	$$info = $response->content;
15093:     }
15094:     return 'ok';
15095: }
15096: 
15097: sub readfile {
15098:     my $file = shift;
15099:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
15100:     my $fh;
15101:     open($fh,"<",$file);
15102:     my $a='';
15103:     while (my $line = <$fh>) { $a .= $line; }
15104:     return $a;
15105: }
15106: 
15107: sub filelocation {
15108:     my ($dir,$file) = @_;
15109:     my $location;
15110:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
15111: 
15112:     if ($file =~ m-^/adm/-) {
15113: 	$file=~s-^/adm/wrapper/-/-;
15114: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
15115:     }
15116: 
15117:     if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
15118:         $location = $file;
15119:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
15120:         my ($udom,$uname,$filename)=
15121:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
15122:         my $home=&homeserver($uname,$udom);
15123:         my $is_me=0;
15124:         my @ids=&current_machine_ids();
15125:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
15126:         if ($is_me) {
15127:   	    $location=propath($udom,$uname).'/userfiles/'.$filename;
15128:         } else {
15129:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
15130:   	      $udom.'/'.$uname.'/'.$filename;
15131:         }
15132:     } elsif ($file =~ m-^/adm/-) {
15133: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
15134:     } else {
15135:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
15136:         $file=~s:^/(res|priv)/:/:;
15137:         my $space=$1;
15138:         if ( !( $file =~ m:^/:) ) {
15139:             $location = $dir. '/'.$file;
15140:         } else {
15141:             $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
15142:         }
15143:     }
15144:     $location=~s://+:/:g; # remove duplicate /
15145:     while ($location=~m{/\.\./}) {
15146: 	if ($location =~ m{/[^/]+/\.\./}) {
15147: 	    $location=~ s{/[^/]+/\.\./}{/}g;
15148: 	} else {
15149: 	    $location=~ s{/\.\./}{/}g;
15150: 	}
15151:     } #remove dir/..
15152:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
15153:     return $location;
15154: }
15155: 
15156: sub hreflocation {
15157:     my ($dir,$file)=@_;
15158:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
15159: 	$file=filelocation($dir,$file);
15160:     } elsif ($file=~m-^/adm/-) {
15161: 	$file=~s-^/adm/wrapper/-/-;
15162: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
15163:     }
15164:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
15165: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
15166:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
15167: 	$file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
15168: 	        {/uploaded/$1/$2/}x;
15169:     }
15170:     if ($file=~ m{^/userfiles/}) {
15171: 	$file =~ s{^/userfiles/}{/uploaded/};
15172:     }
15173:     return $file;
15174: }
15175: 
15176: 
15177: 
15178: 
15179: 
15180: sub current_machine_domains {
15181:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
15182: }
15183: 
15184: sub machine_domains {
15185:     my ($hostname) = @_;
15186:     my @domains;
15187:     my %hostname = &all_hostnames();
15188:     while( my($id, $name) = each(%hostname)) {
15189: #	&logthis("-$id-$name-$hostname-");
15190: 	if ($hostname eq $name) {
15191: 	    push(@domains,&host_domain($id));
15192: 	}
15193:     }
15194:     return @domains;
15195: }
15196: 
15197: sub current_machine_ids {
15198:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
15199: }
15200: 
15201: sub machine_ids {
15202:     my ($hostname) = @_;
15203:     $hostname ||= &hostname($perlvar{'lonHostID'});
15204:     my @ids;
15205:     my %name_to_host = &all_names();
15206:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
15207: 	return @{ $name_to_host{$hostname} };
15208:     }
15209:     return;
15210: }
15211: 
15212: sub additional_machine_domains {
15213:     my @domains;
15214:     if (-e "$perlvar{'lonTabDir'}/expected_domains.tab") {
15215:         if (open(my $fh,"<","$perlvar{'lonTabDir'}/expected_domains.tab")) {
15216:             while (my $line = <$fh>) {
15217:                 chomp($line);           
15218:                 $line =~ s/\s//g;
15219:                 push(@domains,$line);
15220:             }
15221:             close($fh);
15222:         }
15223:     }
15224:     return @domains;
15225: }
15226: 
15227: sub default_login_domain {
15228:     my $domain = $perlvar{'lonDefDomain'};
15229:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
15230:     foreach my $posdom (&current_machine_domains(),
15231:                         &additional_machine_domains()) {
15232:         if (lc($posdom) eq lc($testdomain)) {
15233:             $domain=$posdom;
15234:             last;
15235:         }
15236:     }
15237:     return $domain;
15238: }
15239: 
15240: sub shared_institution {
15241:     my ($dom,$lonhost) = @_;
15242:     if ($lonhost eq '') {
15243:         $lonhost = $perlvar{'lonHostID'};
15244:     }
15245:     my $same_intdom;
15246:     my $hostintdom = &internet_dom($lonhost);
15247:     if ($hostintdom ne '') {
15248:         my %iphost = &get_iphost();
15249:         my $primary_id = &domain($dom,'primary');
15250:         my $primary_ip = &get_host_ip($primary_id);
15251:         if (ref($iphost{$primary_ip}) eq 'ARRAY') {
15252:             foreach my $id (@{$iphost{$primary_ip}}) {
15253:                 my $intdom = &internet_dom($id);
15254:                 if ($intdom eq $hostintdom) {
15255:                     $same_intdom = 1;
15256:                     last;
15257:                 }
15258:             }
15259:         }
15260:     }
15261:     return $same_intdom;
15262: }
15263: 
15264: sub uses_sts {
15265:     my ($ignore_cache) = @_;
15266:     my $lonhost = $perlvar{'lonHostID'};
15267:     my $hostname = &hostname($lonhost);
15268:     my $sts_on;
15269:     if ($protocol{$lonhost} eq 'https') {
15270:         my $cachetime = 12*3600;
15271:         if (!$ignore_cache) {
15272:             ($sts_on,my $cached)=&is_cached_new('stspolicy',$lonhost);
15273:             if (defined($cached)) {
15274:                 return $sts_on;
15275:             }
15276:         }
15277:         my $url = $protocol{$lonhost}.'://'.$hostname.'/index.html';
15278:         my $request=new HTTP::Request('HEAD',$url);
15279:         my $response=&LONCAPA::LWPReq::makerequest($lonhost,$request,'',\%perlvar,'','','',1);
15280:         if ($response->is_success) {
15281:             my $has_sts = $response->header('Strict-Transport-Security');
15282:             if ($has_sts eq '') {
15283:                 $sts_on = 0;
15284:             } else {
15285:                 if ($has_sts =~ /\Qmax-age=\E(\d+)/) {
15286:                     my $maxage = $1;
15287:                     if ($maxage) {
15288:                         $sts_on = 1;
15289:                     } else {
15290:                         $sts_on = 0;
15291:                     }
15292:                 } else {
15293:                     $sts_on = 0;
15294:                 }
15295:             }
15296:             return &do_cache_new('stspolicy',$lonhost,$sts_on,$cachetime);
15297:         }
15298:     }
15299:     return;
15300: }
15301: 
15302: sub waf_allssl {
15303:     my ($host_name) = @_;
15304:     my $alias = &get_proxy_alias();
15305:     if ($host_name eq '') {
15306:         $host_name = $ENV{'SERVER_NAME'};
15307:     }
15308:     if (($host_name ne '') && ($alias eq $host_name)) {
15309:         my $serverhomedom = &host_domain($perlvar{'lonHostID'});
15310:         my %defdomdefaults = &get_domain_defaults($serverhomedom);
15311:         if ($defdomdefaults{'waf_sslopt'}) {
15312:             return $defdomdefaults{'waf_sslopt'};
15313:         }
15314:     }
15315:     return;
15316: }
15317: 
15318: sub get_requestor_ip {
15319:     my ($r,$nolookup,$noproxy) = @_;
15320:     my $from_ip;
15321:     if (ref($r)) {
15322:         if ($r->can('useragent_ip')) {
15323:             if ($noproxy && $r->can('client_ip')) {
15324:                 $from_ip = $r->client_ip();
15325:             } else {
15326:                 $from_ip = $r->useragent_ip();
15327:             }
15328:         } elsif ($r->connection->can('remote_ip')) {
15329:             $from_ip = $r->connection->remote_ip();
15330:         } else {
15331:             $from_ip = $r->get_remote_host($nolookup);
15332:         }
15333:     } else {
15334:         $from_ip = $ENV{'REMOTE_ADDR'};
15335:     }
15336:     return $from_ip if ($noproxy); 
15337:     # Who controls proxy settings for server
15338:     my $dom_in_use = $Apache::lonnet::perlvar{'lonDefDomain'};
15339:     my $proxyinfo = &get_proxy_settings($dom_in_use);
15340:     if ((ref($proxyinfo) eq 'HASH') && ($from_ip)) {
15341:         if ($proxyinfo->{'vpnint'}) {
15342:             if (&ip_match($from_ip,$proxyinfo->{'vpnint'})) {
15343:                 return $from_ip;
15344:             }
15345:         }
15346:         if ($proxyinfo->{'trusted'}) {
15347:             if (&ip_match($from_ip,$proxyinfo->{'trusted'})) {
15348:                 my $ipheader = $proxyinfo->{'ipheader'};
15349:                 my ($ip,$xfor);
15350:                 if (ref($r)) {
15351:                     if ($ipheader) {
15352:                         $ip = $r->headers_in->{$ipheader};
15353:                     }
15354:                     $xfor = $r->headers_in->{'X-Forwarded-For'};
15355:                 } else {
15356:                     if ($ipheader) {
15357:                         $ip = $ENV{'HTTP_'.uc($ipheader)};
15358:                     }
15359:                     $xfor = $ENV{'HTTP_X_FORWARDED_FOR'};
15360:                 }
15361:                 if (($ip eq '') && ($xfor ne '')) {
15362:                     foreach my $poss_ip (reverse(split(/\s*,\s*/,$xfor))) {
15363:                         unless (&ip_match($poss_ip,$proxyinfo->{'trusted'})) {
15364:                             $ip = $poss_ip;
15365:                             last;
15366:                         }
15367:                     }
15368:                 }
15369:                 if ($ip ne '') {
15370:                     return $ip;
15371:                 }
15372:             }
15373:         }
15374:     }
15375:     return $from_ip;
15376: }
15377: 
15378: sub get_proxy_settings {
15379:     my ($dom_in_use) = @_;
15380:     my %domdefaults = &get_domain_defaults($dom_in_use);
15381:     my $proxyinfo = {
15382:                        ipheader => $domdefaults{'waf_ipheader'},
15383:                        trusted  => $domdefaults{'waf_trusted'},
15384:                        vpnint   => $domdefaults{'waf_vpnint'},
15385:                        vpnext   => $domdefaults{'waf_vpnext'},
15386:                        sslopt   => $domdefaults{'waf_sslopt'},
15387:                     };
15388:     return $proxyinfo;
15389: }
15390: 
15391: sub ip_match {
15392:     my ($ip,$pattern_str) = @_;
15393:     $ip=Net::CIDR::cidrvalidate($ip);
15394:     if ($ip) {
15395:         return Net::CIDR::cidrlookup($ip,split(/\s*,\s*/,$pattern_str));
15396:     }
15397:     return;
15398: }
15399: 
15400: sub get_proxy_alias {
15401:     my ($lonid) = @_;
15402:     if ($lonid eq '') {
15403:         $lonid = $perlvar{'lonHostID'};
15404:     }
15405:     if (!defined(&hostname($lonid))) {
15406:         return;
15407:     }
15408:     if ($lonid ne '') {
15409:         my ($alias,$cached) = &is_cached_new('proxyalias',$lonid);
15410:         if ($cached) {
15411:             return $alias;
15412:         }
15413:         my $dom = &host_domain($lonid);
15414:         if ($dom ne '') {
15415:             my $cachetime = 60*60*24;
15416:             my %domconfig =
15417:                 &get_dom('configuration',['wafproxy'],$dom);
15418:             if (ref($domconfig{'wafproxy'}) eq 'HASH') {
15419:                 if (ref($domconfig{'wafproxy'}{'alias'}) eq 'HASH') {
15420:                     $alias = $domconfig{'wafproxy'}{'alias'}{$lonid};
15421:                 }
15422:             }
15423:             return &do_cache_new('proxyalias',$lonid,$alias,$cachetime);
15424:         }
15425:     }
15426:     return;
15427: }
15428: 
15429: sub use_proxy_alias {
15430:     my ($r,$lonid) = @_;
15431:     my $alias = &get_proxy_alias($lonid);
15432:     if ($alias) {
15433:         my $dom = &host_domain($lonid);
15434:         if ($dom ne '') {
15435:             my $proxyinfo = &get_proxy_settings($dom);
15436:             my ($vpnint,$remote_ip);
15437:             if (ref($proxyinfo) eq 'HASH') {
15438:                 $vpnint = $proxyinfo->{'vpnint'};
15439:                 if ($vpnint) {
15440:                     $remote_ip = &get_requestor_ip($r,1,1);
15441:                 }
15442:             }
15443:             unless ($vpnint && &ip_match($remote_ip,$vpnint)) {
15444:                 return $alias;
15445:             }
15446:         }
15447:     }
15448:     return;
15449: }
15450: 
15451: sub alias_sso {
15452:     my ($lonid) = @_;
15453:     if ($lonid eq '') {
15454:         $lonid = $perlvar{'lonHostID'};
15455:     }
15456:     if (!defined(&hostname($lonid))) {
15457:         return;
15458:     }
15459:     if ($lonid ne '') {
15460:         my ($use_alias,$cached) = &is_cached_new('proxysaml',$lonid);
15461:         if ($cached) {
15462:             return $use_alias;
15463:         }
15464:         my $dom = &host_domain($lonid);
15465:         if ($dom ne '') {
15466:             my $cachetime = 60*60*24;
15467:             my %domconfig =
15468:                 &get_dom('configuration',['wafproxy'],$dom);
15469:             if (ref($domconfig{'wafproxy'}) eq 'HASH') {
15470:                 if (ref($domconfig{'wafproxy'}{'saml'}) eq 'HASH') {
15471:                     $use_alias = $domconfig{'wafproxy'}{'saml'}{$lonid};
15472:                 }
15473:             }
15474:             return &do_cache_new('proxysaml',$lonid,$use_alias,$cachetime);
15475:         }
15476:     }
15477:     return;
15478: }
15479: 
15480: sub get_saml_landing {
15481:     my ($lonid) = @_;
15482:     if ($lonid eq '') {
15483:         my $defdom = &default_login_domain();
15484:         my @hosts = &current_machine_ids();
15485:         if (@hosts > 1) {
15486:             foreach my $hostid (@hosts) {
15487:                 if (&host_domain($hostid) eq $defdom) {
15488:                     $lonid = $hostid;
15489:                     last;
15490:                 }
15491:             }
15492:         } else {
15493:             $lonid = $perlvar{'lonHostID'};
15494:         }
15495:         if ($lonid) {
15496:             unless (&host_domain($lonid) eq $defdom) {
15497:                 return;
15498:             }
15499:         } else {
15500:             return;
15501:         }
15502:     } elsif (!defined(&hostname($lonid))) {
15503:         return;
15504:     }
15505:     my ($landing,$cached) = &is_cached_new('samllanding',$lonid);
15506:     if ($cached) {
15507:         return $landing;
15508:     }
15509:     my $dom = &host_domain($lonid);
15510:     if ($dom ne '') {
15511:         my $cachetime = 60*60*24;
15512:         my %domconfig =
15513:             &get_dom('configuration',['login'],$dom);
15514:         if (ref($domconfig{'login'}) eq 'HASH') {
15515:             if (ref($domconfig{'login'}{'saml'}) eq 'HASH') {
15516:                 if (ref($domconfig{'login'}{'saml'}{$lonid}) eq 'HASH') {
15517:                     $landing = 1;
15518:                 }
15519:             }
15520:         }
15521:         return &do_cache_new('samllanding',$lonid,$landing,$cachetime);
15522:     }
15523:     return;
15524: }
15525: 
15526: # ------------------------------------------------------------- Declutters URLs
15527: 
15528: sub declutter {
15529:     my $thisfn=shift;
15530:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
15531:     unless ($thisfn=~m{^/home/httpd/html/priv/}) {
15532:         $thisfn=~s{^/home/httpd/html}{};
15533:     }
15534:     $thisfn=~s/^\///;
15535:     $thisfn=~s|^adm/wrapper/||;
15536:     $thisfn=~s|^adm/coursedocs/showdoc/||;
15537:     $thisfn=~s/^res\///;
15538:     $thisfn=~s/^priv\///;
15539:     unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
15540:         $thisfn=~s/\?.+$//;
15541:     }
15542:     return $thisfn;
15543: }
15544: 
15545: # ------------------------------------------------------------- Clutter up URLs
15546: 
15547: sub clutter {
15548:     my $thisfn='/'.&declutter(shift);
15549:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
15550: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
15551:        $thisfn='/res'.$thisfn; 
15552:     }
15553:     if ($thisfn !~m|^/adm|) {
15554: 	if ($thisfn =~ m|^/ext/|) {
15555: 	    $thisfn='/adm/wrapper'.$thisfn;
15556: 	} else {
15557: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
15558: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
15559: 	    if ($embstyle eq 'ssi'
15560: 		|| ($embstyle eq 'hdn')
15561: 		|| ($embstyle eq 'rat')
15562: 		|| ($embstyle eq 'prv')
15563: 		|| ($embstyle eq 'ign')) {
15564: 		#do nothing with these
15565: 	    } elsif (($embstyle eq 'img') 
15566: 		|| ($embstyle eq 'emb')
15567: 		|| ($embstyle eq 'wrp')) {
15568: 		$thisfn='/adm/wrapper'.$thisfn;
15569: 	    } elsif ($embstyle eq 'unk'
15570: 		     && $thisfn!~/\.(sequence|page)$/) {
15571: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
15572: 	    } else {
15573: #		&logthis("Got a blank emb style");
15574: 	    }
15575: 	}
15576:     } elsif ($thisfn =~ m{^/adm/$match_domain/$match_courseid/\d+/ext\.tool$}) {
15577:         $thisfn='/adm/wrapper'.$thisfn;
15578:     }
15579:     return $thisfn;
15580: }
15581: 
15582: sub clutter_with_no_wrapper {
15583:     my $uri = &clutter(shift);
15584:     if ($uri =~ m-^/adm/-) {
15585: 	$uri =~ s-^/adm/wrapper/-/-;
15586: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
15587:     }
15588:     return $uri;
15589: }
15590: 
15591: sub freeze_escape {
15592:     my ($value)=@_;
15593:     if (ref($value)) {
15594: 	$value=&nfreeze($value);
15595: 	return '__FROZEN__'.&escape($value);
15596:     }
15597:     return &escape($value);
15598: }
15599: 
15600: 
15601: sub thaw_unescape {
15602:     my ($value)=@_;
15603:     if ($value =~ /^__FROZEN__/) {
15604: 	substr($value,0,10,undef);
15605: 	$value=&unescape($value);
15606: 	return &thaw($value);
15607:     }
15608:     return &unescape($value);
15609: }
15610: 
15611: sub correct_line_ends {
15612:     my ($result)=@_;
15613:     $$result =~s/\r\n/\n/mg;
15614:     $$result =~s/\r/\n/mg;
15615: }
15616: # ================================================================ Main Program
15617: 
15618: sub goodbye {
15619:    &logthis("Starting Shut down");
15620: #not converted to using infrastruture and probably shouldn't be
15621:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
15622: #converted
15623: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
15624:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
15625: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
15626: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
15627: #1.1 only
15628: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
15629: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
15630: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
15631: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
15632:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
15633:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
15634:    &logthis(sprintf("%-20s is %s",'hits',$hits));
15635:    &flushcourselogs();
15636:    &logthis("Shutting down");
15637: }
15638: 
15639: sub get_dns {
15640:     my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
15641:     if (!$ignore_cache) {
15642: 	my ($content,$cached)=
15643: 	    &is_cached_new('dns',$url);
15644: 	if ($cached) {
15645: 	    &$func($content,$hashref);
15646: 	    return;
15647: 	}
15648:     }
15649: 
15650:     my %alldns;
15651:     if (open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab")) {
15652:         foreach my $dns (<$config>) {
15653: 	    next if ($dns !~ /^\^(\S*)/x);
15654:             my $line = $1;
15655:             my ($host,$protocol) = split(/:/,$line);
15656:             if ($protocol ne 'https') {
15657:                 $protocol = 'http';
15658:             }
15659: 	    $alldns{$host} = $protocol;
15660:         }
15661:         close($config);
15662:     }
15663:     while (%alldns) {
15664: 	my ($dns) = sort { $b cmp $a } keys(%alldns);
15665:         my ($contents,@content);
15666:         if ($dns eq Sys::Hostname::FQDN::fqdn()) {
15667:             my $command = (split('/',$url))[3];
15668:             my ($dir,$file) = &parse_getdns_url($command,$url);
15669:             delete($alldns{$dns});
15670:             next if (($dir eq '') || ($file eq ''));
15671:             if (open(my $config,'<',"$dir/$file")) {
15672:                 @content = <$config>;
15673:                 close($config);
15674:             }
15675:             if ($url eq '/adm/dns/loncapaCRL') {
15676:                 $contents = join('',@content);
15677:             }
15678:         } else {
15679: 	    my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
15680:             my $response = &LONCAPA::LWPReq::makerequest('',$request,'',\%perlvar,30,0);
15681:             delete($alldns{$dns});
15682: 	    next if ($response->is_error());
15683:             if ($url eq '/adm/dns/loncapaCRL') {
15684:                 $contents = $response->content;
15685:             } else {
15686:                 @content = split("\n",$response->content);
15687:             }
15688:         }
15689:         if ($url eq '/adm/dns/loncapaCRL') {
15690:             return &$func($contents);
15691:         } else {
15692: 	    unless ($nocache) {
15693: 	        &do_cache_new('dns',$url,\@content,30*24*60*60);
15694: 	    }
15695: 	    &$func(\@content,$hashref);
15696:             return;
15697:         }
15698:     }
15699:     my $which = (split('/',$url,4))[3];
15700:     if ($which eq 'loncapaCRL') {
15701:         my $diskfile = "$perlvar{'lonCertificateDirectory'}/$perlvar{'lonnetCertRevocationList'}";
15702:         if (-e $diskfile) {
15703:             &logthis("unable to contact DNS, on disk file $diskfile not updated");
15704:         } else {
15705:             &logthis("unable to contact DNS, no on disk file $diskfile available");
15706:         }
15707:     } else {
15708:         &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
15709:         if (open(my $config,"<","$perlvar{'lonTabDir'}/dns_$which.tab")) {
15710:             my @content = <$config>;
15711:             close($config);
15712:             &$func(\@content,$hashref);
15713:         }
15714:     }
15715:     return;
15716: }
15717: 
15718: # ------------------------------------------------------Get DNS checksums file
15719: sub parse_dns_checksums_tab {
15720:     my ($lines,$hashref) = @_;
15721:     my $lonhost = $perlvar{'lonHostID'};
15722:     my $machine_dom = &host_domain($lonhost);
15723:     my $loncaparev = &get_server_loncaparev($machine_dom);
15724:     my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
15725:     my $webconfdir = '/etc/httpd/conf';
15726:     if ($distro =~ /^(ubuntu|debian)(\d+)$/) {
15727:         $webconfdir = '/etc/apache2';
15728:     } elsif ($distro =~ /^sles(\d+)$/) {
15729:         if ($1 >= 10) {
15730:             $webconfdir = '/etc/apache2';
15731:         }
15732:     } elsif ($distro =~ /^suse(\d+\.\d+)$/) {
15733:         if ($1 >= 10.0) {
15734:             $webconfdir = '/etc/apache2';
15735:         }
15736:     }
15737:     my ($release,$timestamp) = split(/\-/,$loncaparev);
15738:     my (%chksum,%revnum);
15739:     if (ref($lines) eq 'ARRAY') {
15740:         chomp(@{$lines});
15741:         my $version = shift(@{$lines});
15742:         if ($version eq $release) {  
15743:             foreach my $line (@{$lines}) {
15744:                 my ($file,$version,$shasum) = split(/,/,$line);
15745:                 if ($file =~ m{^/etc/httpd/conf}) {
15746:                     if ($webconfdir eq '/etc/apache2') {
15747:                         $file =~ s{^\Q/etc/httpd/conf/\E}{$webconfdir/};
15748:                     }
15749:                 }
15750:                 $chksum{$file} = $shasum;
15751:                 $revnum{$file} = $version;
15752:             }
15753:             if (ref($hashref) eq 'HASH') {
15754:                 %{$hashref} = (
15755:                                 sums     => \%chksum,
15756:                                 versions => \%revnum,
15757:                               );
15758:             }
15759:         }
15760:     }
15761:     return;
15762: }
15763: 
15764: sub fetch_dns_checksums {
15765:     my %checksums;
15766:     my $machine_dom = &host_domain($perlvar{'lonHostID'});
15767:     my $loncaparev = &get_server_loncaparev($machine_dom,$perlvar{'lonHostID'});
15768:     my ($release,$timestamp) = split(/\-/,$loncaparev);
15769:     &get_dns("/adm/dns/checksums/$release",\&parse_dns_checksums_tab,1,1,
15770:              \%checksums);
15771:     return \%checksums;
15772: }
15773: 
15774: sub fetch_crl_pemfile {
15775:     return &get_dns("/adm/dns/loncapaCRL",\&save_crl_pem,1,1);
15776: }
15777: 
15778: sub save_crl_pem {
15779:     my ($content) = @_;
15780:     my ($msg,$hadchanges);
15781:     if ($content ne '') {
15782:         my $now = time;
15783:         my $lonca = $perlvar{'lonCertificateDirectory'}.'/'.$perlvar{'lonnetCertificateAuthority'};
15784:         my $tmpcrl = $tmpdir.'/'.$perlvar{'lonnetCertRevocationList'}.'_'.$now.'.'.$$.'.tmp';
15785:         if (open(my $fh,'>',"$tmpcrl")) {
15786:             print $fh $content;
15787:             close($fh);
15788:             if (-e $lonca) {
15789:                 if (open(PIPE,"openssl crl -in $tmpcrl -inform pem -CAfile $lonca -noout 2>&1 |")) {
15790:                     my $check = <PIPE>;
15791:                     close(PIPE);
15792:                     chomp($check);
15793:                     if ($check eq 'verify OK') {
15794:                         my $dest = "$perlvar{'lonCertificateDirectory'}/$perlvar{'lonnetCertRevocationList'}";
15795:                         my $backup;
15796:                         if (-e $dest) {
15797:                             if (&File::Copy::move($dest,"$dest.bak")) {
15798:                                 $backup = 'ok';
15799:                             }
15800:                         }
15801:                         if (&File::Copy::move($tmpcrl,$dest)) {
15802:                             $msg = 'ok';
15803:                             if ($backup) {
15804:                                 my (%oldnums,%newnums);
15805:                                 if (open(PIPE, "openssl crl -inform PEM -text -noout -in $dest.bak |grep 'Serial Number' |")) {
15806:                                     while (<PIPE>) {
15807:                                         $oldnums{(split(/:/))[1]} = 1;
15808:                                     }
15809:                                     close(PIPE);
15810:                                 }
15811:                                 if (open(PIPE, "openssl crl -inform PEM -text -noout -in $dest |grep 'Serial Number' |")) {
15812:                                     while(<PIPE>) {
15813:                                         $newnums{(split(/:/))[1]} = 1;
15814:                                     }
15815:                                     close(PIPE);
15816:                                 }
15817:                                 foreach my $key (sort {$b <=> $a } (keys(%newnums))) {
15818:                                     unless (exists($oldnums{$key})) {
15819:                                         $hadchanges = 1;
15820:                                         last;
15821:                                     }
15822:                                 }
15823:                                 unless ($hadchanges) {
15824:                                     foreach my $key (sort {$b <=> $a } (keys(%oldnums))) {
15825:                                         unless (exists($newnums{$key})) {
15826:                                             $hadchanges = 1;
15827:                                             last;
15828:                                         }
15829:                                     }
15830:                                 }
15831:                             }
15832:                         }
15833:                     } else {
15834:                         unlink($tmpcrl);
15835:                     }
15836:                 } else {
15837:                     unlink($tmpcrl);
15838:                 }
15839:             } else {
15840:                 unlink($tmpcrl);
15841:             }
15842:         }
15843:     }
15844:     return ($msg,$hadchanges);
15845: }
15846: 
15847: sub parse_getdns_url {
15848:     my ($command,$url) = @_;
15849:     my $dir = $perlvar{'lonTabDir'};
15850:     my $file;
15851:     if ($command eq 'hosts') {
15852:         $file = 'dns_hosts.tab';
15853:     } elsif ($command eq 'domain') {
15854:         $file = 'dns_domain.tab';
15855:     } elsif ($command eq 'checksums') {
15856:         my $version = (split('/',$url))[4];
15857:         $file = "dns_checksums/$version.tab",
15858:     } elsif ($command eq 'loncapaCRL') {
15859:         $dir = $perlvar{'lonCertificateDirectory'};
15860:         $file = $perlvar{'lonnetCertRevocationList'};
15861:     }
15862:     return ($dir,$file);
15863: }
15864: 
15865: # ------------------------------------------------------------ Read domain file
15866: {
15867:     my $loaded;
15868:     my %domain;
15869: 
15870:     sub parse_domain_tab {
15871: 	my ($lines) = @_;
15872: 	foreach my $line (@$lines) {
15873: 	    next if ($line =~ /^(\#|\s*$ )/x);
15874: 
15875: 	    chomp($line);
15876: 	    my ($name,@elements) = split(/:/,$line,9);
15877: 	    my %this_domain;
15878: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
15879: 			       'lang_def', 'city', 'longi', 'lati',
15880: 			       'primary') {
15881: 		$this_domain{$field} = shift(@elements);
15882: 	    }
15883: 	    $domain{$name} = \%this_domain;
15884: 	}
15885:     }
15886: 
15887:     sub reset_domain_info {
15888: 	undef($loaded);
15889: 	undef(%domain);
15890:     }
15891: 
15892:     sub load_domain_tab {
15893: 	my ($ignore_cache,$nocache) = @_;
15894: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache,$nocache);
15895: 	my $fh;
15896: 	if (open($fh,"<",$perlvar{'lonTabDir'}.'/domain.tab')) {
15897: 	    my @lines = <$fh>;
15898: 	    &parse_domain_tab(\@lines);
15899: 	}
15900: 	close($fh);
15901: 	$loaded = 1;
15902:     }
15903: 
15904:     sub domain {
15905: 	&load_domain_tab() if (!$loaded);
15906: 
15907: 	my ($name,$what) = @_;
15908: 	return if ( !exists($domain{$name}) );
15909: 
15910: 	if (!$what) {
15911: 	    return $domain{$name}{'description'};
15912: 	}
15913: 	return $domain{$name}{$what};
15914:     }
15915: 
15916:     sub domain_info {
15917:         &load_domain_tab() if (!$loaded);
15918:         return %domain;
15919:     }
15920: 
15921: }
15922: 
15923: 
15924: # ------------------------------------------------------------- Read hosts file
15925: {
15926:     my %hostname;
15927:     my %hostdom;
15928:     my %libserv;
15929:     my $loaded;
15930:     my %name_to_host;
15931:     my %internetdom;
15932:     my %LC_dns_serv;
15933: 
15934:     sub parse_hosts_tab {
15935: 	my ($file) = @_;
15936: 	foreach my $configline (@$file) {
15937: 	    next if ($configline =~ /^(\#|\s*$ )/x);
15938:             chomp($configline);
15939: 	    if ($configline =~ /^\^/) {
15940:                 if ($configline =~ /^\^([\w.\-]+)/) {
15941:                     $LC_dns_serv{$1} = 1;
15942:                 }
15943:                 next;
15944:             }
15945: 	    my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
15946: 	    $name=~s/\s//g;
15947: 	    if ($id && $domain && $role && $name) {
15948:                 if ((exists($hostname{$id})) && ($hostname{$id} ne '')) {
15949:                     my $curr = $hostname{$id};
15950:                     my $skip;
15951:                     if (ref($name_to_host{$curr}) eq 'ARRAY') {
15952:                         if (($curr eq $name) && (@{$name_to_host{$curr}} == 1)) {
15953:                             $skip = 1;
15954:                         } else {
15955:                             @{$name_to_host{$curr}} = grep { $_ ne $id } @{$name_to_host{$curr}};
15956:                         }
15957:                     }
15958:                     unless ($skip) {
15959:                         push(@{$name_to_host{$name}},$id);
15960:                     }
15961:                 } else {
15962:                     push(@{$name_to_host{$name}},$id);
15963:                 }
15964: 		$hostname{$id}=$name;
15965: 		$hostdom{$id}=$domain;
15966: 		if ($role eq 'library') { $libserv{$id}=$name; }
15967:                 if (defined($protocol)) {
15968:                     if ($protocol eq 'https') {
15969:                         $protocol{$id} = $protocol;
15970:                     } else {
15971:                         $protocol{$id} = 'http'; 
15972:                     }
15973:                 } else {
15974:                     $protocol{$id} = 'http';
15975:                 }
15976:                 if (defined($intdom)) {
15977:                     $internetdom{$id} = $intdom;
15978:                 }
15979: 	    }
15980: 	}
15981:     }
15982:     
15983:     sub reset_hosts_info {
15984: 	&purge_remembered();
15985: 	&reset_domain_info();
15986: 	&reset_hosts_ip_info();
15987:         undef(%internetdom);
15988: 	undef(%name_to_host);
15989: 	undef(%hostname);
15990: 	undef(%hostdom);
15991: 	undef(%libserv);
15992: 	undef($loaded);
15993:     }
15994: 
15995:     sub load_hosts_tab {
15996: 	my ($ignore_cache,$nocache) = @_;
15997: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache,$nocache);
15998: 	open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab");
15999: 	my @config = <$config>;
16000: 	&parse_hosts_tab(\@config);
16001: 	close($config);
16002: 	$loaded=1;
16003:     }
16004: 
16005:     sub hostname {
16006: 	&load_hosts_tab() if (!$loaded);
16007: 
16008: 	my ($lonid) = @_;
16009: 	return $hostname{$lonid};
16010:     }
16011: 
16012:     sub all_hostnames {
16013: 	&load_hosts_tab() if (!$loaded);
16014: 
16015: 	return %hostname;
16016:     }
16017: 
16018:     sub all_names {
16019:         my ($ignore_cache,$nocache) = @_;
16020: 	&load_hosts_tab($ignore_cache,$nocache) if (!$loaded);
16021: 
16022: 	return %name_to_host;
16023:     }
16024: 
16025:     sub all_host_domain {
16026:         &load_hosts_tab() if (!$loaded);
16027:         return %hostdom;
16028:     }
16029: 
16030:     sub all_host_intdom {
16031:         &load_hosts_tab() if (!$loaded);
16032:         return %internetdom;
16033:     }
16034: 
16035:     sub is_library {
16036: 	&load_hosts_tab() if (!$loaded);
16037: 
16038: 	return exists($libserv{$_[0]});
16039:     }
16040: 
16041:     sub all_library {
16042: 	&load_hosts_tab() if (!$loaded);
16043: 
16044: 	return %libserv;
16045:     }
16046: 
16047:     sub unique_library {
16048: 	#2x reverse removes all hostnames that appear more than once
16049:         my %unique = reverse &all_library();
16050:         return reverse %unique;
16051:     }
16052: 
16053:     sub get_servers {
16054: 	&load_hosts_tab() if (!$loaded);
16055: 
16056: 	my ($domain,$type) = @_;
16057: 	my %possible_hosts = ($type eq 'library') ? %libserv
16058: 	                                          : %hostname;
16059: 	my %result;
16060: 	if (ref($domain) eq 'ARRAY') {
16061: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
16062: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
16063: 		    $result{$host} = $hostname;
16064: 		}
16065: 	    }
16066: 	} else {
16067: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
16068: 		if ($hostdom{$host} eq $domain) {
16069: 		    $result{$host} = $hostname;
16070: 		}
16071: 	    }
16072: 	}
16073: 	return %result;
16074:     }
16075: 
16076:     sub get_unique_servers {
16077:         my %unique = reverse &get_servers(@_);
16078: 	return reverse %unique;
16079:     }
16080: 
16081:     sub host_domain {
16082: 	&load_hosts_tab() if (!$loaded);
16083: 
16084: 	my ($lonid) = @_;
16085: 	return $hostdom{$lonid};
16086:     }
16087: 
16088:     sub all_domains {
16089: 	&load_hosts_tab() if (!$loaded);
16090: 
16091: 	my %seen;
16092: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
16093: 	return @uniq;
16094:     }
16095: 
16096:     sub internet_dom {
16097:         &load_hosts_tab() if (!$loaded);
16098: 
16099:         my ($lonid) = @_;
16100:         return $internetdom{$lonid};
16101:     }
16102: 
16103:     sub is_LC_dns {
16104:         &load_hosts_tab() if (!$loaded);
16105: 
16106:         my ($hostname) = @_;
16107:         return exists($LC_dns_serv{$hostname});
16108:     }
16109: 
16110: }
16111: 
16112: { 
16113:     my %iphost;
16114:     my %name_to_ip;
16115:     my %lonid_to_ip;
16116: 
16117:     sub get_hosts_from_ip {
16118: 	my ($ip) = @_;
16119: 	my %iphosts = &get_iphost();
16120: 	if (ref($iphosts{$ip})) {
16121: 	    return @{$iphosts{$ip}};
16122: 	}
16123: 	return;
16124:     }
16125:     
16126:     sub reset_hosts_ip_info {
16127: 	undef(%iphost);
16128: 	undef(%name_to_ip);
16129: 	undef(%lonid_to_ip);
16130:     }
16131: 
16132:     sub get_host_ip {
16133: 	my ($lonid) = @_;
16134: 	if (exists($lonid_to_ip{$lonid})) {
16135: 	    return $lonid_to_ip{$lonid};
16136: 	}
16137: 	my $name=&hostname($lonid);
16138:    	my $ip = gethostbyname($name);
16139: 	return if (!$ip || length($ip) ne 4);
16140: 	$ip=inet_ntoa($ip);
16141: 	$name_to_ip{$name}   = $ip;
16142: 	$lonid_to_ip{$lonid} = $ip;
16143: 	return $ip;
16144:     }
16145:     
16146:     sub get_iphost {
16147: 	my ($ignore_cache,$nocache) = @_;
16148: 
16149: 	if (!$ignore_cache) {
16150: 	    if (%iphost) {
16151: 		return %iphost;
16152: 	    }
16153: 	    my ($ip_info,$cached)=
16154: 		&is_cached_new('iphost','iphost');
16155: 	    if ($cached) {
16156: 		%iphost      = %{$ip_info->[0]};
16157: 		%name_to_ip  = %{$ip_info->[1]};
16158: 		%lonid_to_ip = %{$ip_info->[2]};
16159: 		return %iphost;
16160: 	    }
16161: 	}
16162: 
16163: 	# get yesterday's info for fallback
16164: 	my %old_name_to_ip;
16165: 	my ($ip_info,$cached)=
16166: 	    &is_cached_new('iphost','iphost');
16167: 	if ($cached) {
16168: 	    %old_name_to_ip = %{$ip_info->[1]};
16169: 	}
16170: 
16171: 	my %name_to_host = &all_names($ignore_cache,$nocache);
16172: 	foreach my $name (keys(%name_to_host)) {
16173: 	    my $ip;
16174: 	    if (!exists($name_to_ip{$name})) {
16175: 		$ip = gethostbyname($name);
16176: 		if (!$ip || length($ip) ne 4) {
16177: 		    if (defined($old_name_to_ip{$name})) {
16178: 			$ip = $old_name_to_ip{$name};
16179: 			&logthis("Can't find $name defaulting to old $ip");
16180: 		    } else {
16181: 			&logthis("Name $name no IP found");
16182: 			next;
16183: 		    }
16184: 		} else {
16185: 		    $ip=inet_ntoa($ip);
16186: 		}
16187: 		$name_to_ip{$name} = $ip;
16188: 	    } else {
16189: 		$ip = $name_to_ip{$name};
16190: 	    }
16191: 	    foreach my $id (@{ $name_to_host{$name} }) {
16192: 		$lonid_to_ip{$id} = $ip;
16193: 	    }
16194: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
16195: 	}
16196:         unless ($nocache) {
16197: 	    &do_cache_new('iphost','iphost',
16198: 		          [\%iphost,\%name_to_ip,\%lonid_to_ip],
16199: 		          48*60*60);
16200:         }
16201: 
16202: 	return %iphost;
16203:     }
16204: 
16205:     #
16206:     #  Given a DNS returns the loncapa host name for that DNS 
16207:     # 
16208:     sub host_from_dns {
16209:         my ($dns) = @_;
16210:         my @hosts;
16211:         my $ip;
16212: 
16213:         if (exists($name_to_ip{$dns})) {
16214:             $ip = $name_to_ip{$dns};
16215:         }
16216:         if (!$ip) {
16217:             $ip = gethostbyname($dns); # Initial translation to IP is in net order.
16218:             if (length($ip) == 4) { 
16219: 	        $ip   = &IO::Socket::inet_ntoa($ip);
16220:             }
16221:         }
16222:         if ($ip) {
16223: 	    @hosts = get_hosts_from_ip($ip);
16224: 	    return $hosts[0];
16225:         }
16226:         return undef;
16227:     }
16228: 
16229:     sub get_internet_names {
16230:         my ($lonid) = @_;
16231:         return if ($lonid eq '');
16232:         my ($idnref,$cached)=
16233:             &is_cached_new('internetnames',$lonid);
16234:         if ($cached) {
16235:             return $idnref;
16236:         }
16237:         my $ip = &get_host_ip($lonid);
16238:         my @hosts = &get_hosts_from_ip($ip);
16239:         my %iphost = &get_iphost();
16240:         my (@idns,%seen);
16241:         foreach my $id (@hosts) {
16242:             my $dom = &host_domain($id);
16243:             my $prim_id = &domain($dom,'primary');
16244:             my $prim_ip = &get_host_ip($prim_id);
16245:             next if ($seen{$prim_ip});
16246:             if (ref($iphost{$prim_ip}) eq 'ARRAY') {
16247:                 foreach my $id (@{$iphost{$prim_ip}}) {
16248:                     my $intdom = &internet_dom($id);
16249:                     unless (grep(/^\Q$intdom\E$/,@idns)) {
16250:                         push(@idns,$intdom);
16251:                     }
16252:                 }
16253:             }
16254:             $seen{$prim_ip} = 1;
16255:         }
16256:         return &do_cache_new('internetnames',$lonid,\@idns,12*60*60);
16257:     }
16258: 
16259: }
16260: 
16261: sub all_loncaparevs {
16262:     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);
16263: }
16264: 
16265: # ---------------------------------------------------------- Read loncaparev table
16266: {
16267:     sub load_loncaparevs { 
16268:         if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
16269:             if (open(my $config,"<","$perlvar{'lonTabDir'}/loncaparevs.tab")) {
16270:                 while (my $configline=<$config>) {
16271:                     chomp($configline);
16272:                     my ($hostid,$loncaparev)=split(/:/,$configline);
16273:                     $loncaparevs{$hostid}=$loncaparev;
16274:                 }
16275:                 close($config);
16276:             }
16277:         }
16278:     }
16279: }
16280: 
16281: # ---------------------------------------------------------- Read serverhostID table
16282: {
16283:     sub load_serverhomeIDs {
16284:         if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
16285:             if (open(my $config,"<","$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
16286:                 while (my $configline=<$config>) {
16287:                     chomp($configline);
16288:                     my ($name,$id)=split(/:/,$configline);
16289:                     $serverhomeIDs{$name}=$id;
16290:                 }
16291:                 close($config);
16292:             }
16293:         }
16294:     }
16295: }
16296: 
16297: 
16298: BEGIN {
16299: 
16300: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
16301:     unless ($readit) {
16302: {
16303:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
16304:     %perlvar = (%perlvar,%{$configvars});
16305: }
16306: 
16307: 
16308: # ------------------------------------------------------ Read spare server file
16309: {
16310:     open(my $config,"<","$perlvar{'lonTabDir'}/spare.tab");
16311: 
16312:     while (my $configline=<$config>) {
16313:        chomp($configline);
16314:        if ($configline) {
16315: 	   my ($host,$type) = split(':',$configline,2);
16316: 	   if (!defined($type) || $type eq '') { $type = 'default' };
16317: 	   push(@{ $spareid{$type} }, $host);
16318:        }
16319:     }
16320:     close($config);
16321: }
16322: # ------------------------------------------------------------ Read permissions
16323: {
16324:     open(my $config,"<","$perlvar{'lonTabDir'}/roles.tab");
16325: 
16326:     while (my $configline=<$config>) {
16327: 	chomp($configline);
16328: 	if ($configline) {
16329: 	    my ($role,$perm)=split(/ /,$configline);
16330: 	    if ($perm ne '') { $pr{$role}=$perm; }
16331: 	}
16332:     }
16333:     close($config);
16334: }
16335: 
16336: # -------------------------------------------- Read plain texts for permissions
16337: {
16338:     open(my $config,"<","$perlvar{'lonTabDir'}/rolesplain.tab");
16339: 
16340:     while (my $configline=<$config>) {
16341: 	chomp($configline);
16342: 	if ($configline) {
16343: 	    my ($short,@plain)=split(/:/,$configline);
16344:             %{$prp{$short}} = ();
16345: 	    if (@plain > 0) {
16346:                 $prp{$short}{'std'} = $plain[0];
16347:                 for (my $i=1; $i<@plain; $i++) {
16348:                     $prp{$short}{'alt'.$i} = $plain[$i];  
16349:                 }
16350:             }
16351: 	}
16352:     }
16353:     close($config);
16354: }
16355: 
16356: # ---------------------------------------------------------- Read package table
16357: {
16358:     open(my $config,"<","$perlvar{'lonTabDir'}/packages.tab");
16359: 
16360:     while (my $configline=<$config>) {
16361: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
16362: 	chomp($configline);
16363: 	my ($short,$plain)=split(/:/,$configline);
16364: 	my ($pack,$name)=split(/\&/,$short);
16365: 	if ($plain ne '') {
16366: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
16367: 	    $packagetab{$short}=$plain; 
16368: 	}
16369:     }
16370:     close($config);
16371: }
16372: 
16373: # ---------------------------------------------------------- Read loncaparev table
16374: 
16375: &load_loncaparevs();
16376: 
16377: # ---------------------------------------------------------- Read serverhostID table
16378: 
16379: &load_serverhomeIDs();
16380: 
16381: # ---------------------------------------------------------- Read releaseslist XML
16382: {
16383:     my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
16384:     if (-e $file) {
16385:         my $parser = HTML::LCParser->new($file);
16386:         while (my $token = $parser->get_token()) {
16387:             if ($token->[0] eq 'S') {
16388:                 my $item = $token->[1];
16389:                 my $name = $token->[2]{'name'};
16390:                 my $value = $token->[2]{'value'};
16391:                 my $valuematch = $token->[2]{'valuematch'};
16392:                 my $namematch = $token->[2]{'namematch'};
16393:                 if ($item eq 'parameter') {
16394:                     if (($namematch ne '') || (($name ne '') && ($value ne '' || $valuematch ne ''))) {
16395:                         my $release = $parser->get_text();
16396:                         $release =~ s/(^\s*|\s*$ )//gx;
16397:                         $needsrelease{$item.':'.$name.':'.$value.':'.$valuematch.':'.$namematch} = $release;
16398:                     }
16399:                 } elsif ($item ne '' && $name ne '') {
16400:                     my $release = $parser->get_text();
16401:                     $release =~ s/(^\s*|\s*$ )//gx;
16402:                     $needsrelease{$item.':'.$name.':'.$value} = $release;
16403:                 }
16404:             }
16405:         }
16406:     }
16407: }
16408: 
16409: # ---------------------------------------------------------- Read managers table
16410: {
16411:     if (-e "$perlvar{'lonTabDir'}/managers.tab") {
16412:         if (open(my $config,"<","$perlvar{'lonTabDir'}/managers.tab")) {
16413:             while (my $configline=<$config>) {
16414:                 chomp($configline);
16415:                 next if ($configline =~ /^\#/);
16416:                 if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
16417:                     $managerstab{$configline} = 1;
16418:                 }
16419:             }
16420:             close($config);
16421:         }
16422:     }
16423: }
16424: 
16425: # ------------- set up temporary directory
16426: {
16427:     $tmpdir = LONCAPA::tempdir();
16428: 
16429: }
16430: 
16431: # ------------- set default texengine (domain default overrides this)
16432: {
16433:     $deftex = LONCAPA::texengine();
16434: }
16435: 
16436: # ------------- set default minimum length for passwords for internal auth users
16437: {
16438:     $passwdmin = LONCAPA::passwd_min();
16439: }
16440: 
16441: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
16442: 				'compress_threshold'=> 20_000,
16443:  			        });
16444: 
16445: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
16446: $dumpcount=0;
16447: $locknum=0;
16448: 
16449: &logtouch();
16450: &logthis('<font color="yellow">INFO: Read configuration</font>');
16451: $readit=1;
16452:     {
16453: 	use integer;
16454: 	my $test=(2**32)+1;
16455: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
16456: 	&logthis(" Detected 64bit platform ($_64bit)");
16457:     }
16458: }
16459: }
16460: 
16461: 1;
16462: __END__
16463: 
16464: =pod
16465: 
16466: =head1 NAME
16467: 
16468: Apache::lonnet - Subroutines to ask questions about things in the network.
16469: 
16470: =head1 SYNOPSIS
16471: 
16472: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
16473: 
16474:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
16475: 
16476: Common parameters:
16477: 
16478: =over 4
16479: 
16480: =item *
16481: 
16482: $uname : an internal username (if $cname expecting a course Id specifically)
16483: 
16484: =item *
16485: 
16486: $udom : a domain (if $cdom expecting a course's domain specifically)
16487: 
16488: =item *
16489: 
16490: $symb : a resource instance identifier
16491: 
16492: =item *
16493: 
16494: $namespace : the name of a .db file that contains the data needed or
16495: being set.
16496: 
16497: =back
16498: 
16499: =head1 OVERVIEW
16500: 
16501: lonnet provides subroutines which interact with the
16502: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
16503: about classes, users, and resources.
16504: 
16505: For many of these objects you can also use this to store data about
16506: them or modify them in various ways.
16507: 
16508: =head2 Symbs
16509: 
16510: To identify a specific instance of a resource, LON-CAPA uses symbols
16511: or "symbs"X<symb>. These identifiers are built from the URL of the
16512: map, the resource number of the resource in the map, and the URL of
16513: the resource itself. The latter is somewhat redundant, but might help
16514: if maps change.
16515: 
16516: An example is
16517: 
16518:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
16519: 
16520: The respective map entry is
16521: 
16522:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
16523:   title="Problem 2">
16524:  </resource>
16525: 
16526: Symbs are used by the random number generator, as well as to store and
16527: restore data specific to a certain instance of for example a problem.
16528: 
16529: =head2 Storing And Retrieving Data
16530: 
16531: X<store()>X<cstore()>X<restore()>Three of the most important functions
16532: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
16533: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
16534: is is the non-critical message twin of cstore. These functions are for
16535: handlers to store a perl hash to a user's permanent data space in an
16536: easy manner, and to retrieve it again on another call. It is expected
16537: that a handler would use this once at the beginning to retrieve data,
16538: and then again once at the end to send only the new data back.
16539: 
16540: The data is stored in the user's data directory on the user's
16541: homeserver under the ID of the course.
16542: 
16543: The hash that is returned by restore will have all of the previous
16544: value for all of the elements of the hash.
16545: 
16546: Example:
16547: 
16548:  #creating a hash
16549:  my %hash;
16550:  $hash{'foo'}='bar';
16551: 
16552:  #storing it
16553:  &Apache::lonnet::cstore(\%hash);
16554: 
16555:  #changing a value
16556:  $hash{'foo'}='notbar';
16557: 
16558:  #adding a new value
16559:  $hash{'bar'}='foo';
16560:  &Apache::lonnet::cstore(\%hash);
16561: 
16562:  #retrieving the hash
16563:  my %history=&Apache::lonnet::restore();
16564: 
16565:  #print the hash
16566:  foreach my $key (sort(keys(%history))) {
16567:    print("\%history{$key} = $history{$key}");
16568:  }
16569: 
16570: Will print out:
16571: 
16572:  %history{1:foo} = bar
16573:  %history{1:keys} = foo:timestamp
16574:  %history{1:timestamp} = 990455579
16575:  %history{2:bar} = foo
16576:  %history{2:foo} = notbar
16577:  %history{2:keys} = foo:bar:timestamp
16578:  %history{2:timestamp} = 990455580
16579:  %history{bar} = foo
16580:  %history{foo} = notbar
16581:  %history{timestamp} = 990455580
16582:  %history{version} = 2
16583: 
16584: Note that the special hash entries C<keys>, C<version> and
16585: C<timestamp> were added to the hash. C<version> will be equal to the
16586: total number of versions of the data that have been stored. The
16587: C<timestamp> attribute will be the UNIX time the hash was
16588: stored. C<keys> is available in every historical section to list which
16589: keys were added or changed at a specific historical revision of a
16590: hash.
16591: 
16592: B<Warning>: do not store the hash that restore returns directly. This
16593: will cause a mess since it will restore the historical keys as if the
16594: were new keys. I.E. 1:foo will become 1:1:foo etc.
16595: 
16596: Calling convention:
16597: 
16598:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname);
16599:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$laststore);
16600: 
16601: For more detailed information, see lonnet specific documentation.
16602: 
16603: =head1 RETURN MESSAGES
16604: 
16605: =over 4
16606: 
16607: =item * B<con_lost>: unable to contact remote host
16608: 
16609: =item * B<con_delayed>: unable to contact remote host, message will be delivered
16610: when the connection is brought back up
16611: 
16612: =item * B<con_failed>: unable to contact remote host and unable to save message
16613: for later delivery
16614: 
16615: =item * B<error:>: an error a occurred, a description of the error follows the :
16616: 
16617: =item * B<no_such_host>: unable to fund a host associated with the user/domain
16618: that was requested
16619: 
16620: =back
16621: 
16622: =head1 PUBLIC SUBROUTINES
16623: 
16624: =head2 Session Environment Functions
16625: 
16626: =over 4
16627: 
16628: =item * 
16629: X<appenv()>
16630: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
16631: the user envirnoment file, and will be restored for each access this
16632: user makes during this session, also modifies the %env for the current
16633: process. Optional rolesarrayref - if defined contains a reference to an array
16634: of roles which are exempt from the restriction on modifying user.role entries 
16635: in the user's environment.db and in %env.    
16636: 
16637: =item *
16638: X<delenv()>
16639: B<delenv($delthis,$regexp)>: removes all items from the session
16640: environment file that begin with $delthis. If the 
16641: optional second arg - $regexp - is true, $delthis is treated as a 
16642: regular expression, otherwise \Q$delthis\E is used. 
16643: The values are also deleted from the current processes %env.
16644: 
16645: =item * get_env_multiple($name) 
16646: 
16647: gets $name from the %env hash, it seemlessly handles the cases where multiple
16648: values may be defined and end up as an array ref.
16649: 
16650: returns an array of values
16651: 
16652: =back
16653: 
16654: =head2 User Information
16655: 
16656: =over 4
16657: 
16658: =item *
16659: X<queryauthenticate()>
16660: B<queryauthenticate($uname,$udom)>: try to determine user's current 
16661: authentication scheme
16662: 
16663: =item *
16664: X<authenticate()>
16665: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
16666: authenticate user from domain's lib servers (first use the current
16667: one). C<$upass> should be the users password.
16668: $checkdefauth is optional (value is 1 if a check should be made to
16669:    authenticate user using default authentication method, and allow
16670:    account creation if username does not have account in the domain).
16671: $clientcancheckhost is optional (value is 1 if checking whether the
16672:    server can host will occur on the client side in lonauth.pm).   
16673: 
16674: =item *
16675: X<homeserver()>
16676: B<homeserver($uname,$udom)>: find the server which has
16677: the user's directory and files (there must be only one), this caches
16678: the answer, and also caches if there is a borken connection.
16679: 
16680: =item *
16681: X<idget()>
16682: B<idget($udom,$idsref,$namespace)>: find the usernames behind either 
16683: a list of student/employee IDs or clicker IDs
16684: (student/employee IDs are a unique resource in a domain, there must be 
16685: only 1 ID per username, and only 1 username per ID in a specific domain).
16686: clickerIDs are not necessarily unique, as students might share clickers.
16687: (returns hash: id=>name,id=>name)
16688: 
16689: =item *
16690: X<idrget()>
16691: B<idrget($udom,@unames)>: find the IDs behind a list of
16692: usernames (returns hash: name=>id,name=>id)
16693: 
16694: =item *
16695: X<idput()>
16696: B<idput($udom,$idsref,$uhome,$namespace)>: store away a list of 
16697: names and associated student/employee IDs or clicker IDs.
16698: 
16699: =item *
16700: X<iddel()>
16701: B<iddel($udom,$idshashref,$uhome,$namespace)>: delete unwanted 
16702: student/employee ID or clicker ID username look-ups from domain.
16703: The homeserver ($uhome) and namespace ($namespace) are optional.
16704: If no $uhome is provided, it will be determined usig &homeserver()
16705: for each user.  If no $namespace is provided, the default is ids.
16706: 
16707: =item *
16708: X<updateclickers()>
16709: B<updateclickers($udom,$action,$idshashref,$uhome,$critical)>: update 
16710: clicker ID-to-username look-ups in clickers.db on library server.
16711: Permitted actions are add or del (i.e., add or delete). The 
16712: clickers.db contains clickerID as keys (escaped), and each corresponding
16713: value is an escaped comma-separated list of usernames (for whom the
16714: library server is the homeserver), who registered that particular ID.
16715: If $critical is true, the update will be sent via &critical, otherwise
16716: &reply() will be used.
16717: 
16718: =item *
16719: X<rolesinit()>
16720: B<rolesinit($udom,$username)>: get user privileges.
16721: returns user role, first access and timer interval hashes
16722: 
16723: =item *
16724: X<privileged()>
16725: B<privileged($username,$domain)>: returns a true if user has a
16726: privileged and active role (i.e. su or dc), false otherwise.
16727: 
16728: =item *
16729: X<getsection()>
16730: B<getsection($udom,$uname,$cname)>: finds the section of student in the
16731: course $cname, return section name/number or '' for "not in course"
16732: and '-1' for "no section"
16733: 
16734: =item *
16735: X<userenvironment()>
16736: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
16737: passed in @what from the requested user's environment, returns a hash
16738: 
16739: =item * 
16740: X<userlog_query()>
16741: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
16742: activity.log file. %filters defines filters applied when parsing the
16743: log file. These can be start or end timestamps, or the type of action
16744: - log to look for Login or Logout events, check for Checkin or
16745: Checkout, role for role selection. The response is in the form
16746: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
16747: escaped strings of the action recorded in the activity.log file.
16748: 
16749: =back
16750: 
16751: =head2 User Roles
16752: 
16753: =over 4
16754: 
16755: =item *
16756: 
16757: allowed($priv,$uri,$symb,$role,$clientip,$noblockcheck) : check for a user privilege; 
16758: returns codes for allowed actions.
16759: 
16760: The first argument is required, all others are optional.
16761: 
16762: $priv is the privilege being checked.
16763: $uri contains additional information about what is being checked for access (e.g.,
16764: URL, course ID etc.). 
16765: $symb is the unique resource instance identifier in a course; if needed,
16766: but not provided, it will be retrieved via a call to &symbread(). 
16767: $role is the role for which a priv is being checked (only used if priv is evb). 
16768: $clientip is the user's IP address (only used when checking for access to portfolio 
16769: files).
16770: $noblockcheck, if true, skips calls to &has_comm_blocking() for the bre priv. This 
16771: prevents recursive calls to &allowed.
16772: 
16773:  F: full access
16774:  U,I,K: authentication modes (cxx only)
16775:  '': forbidden
16776:  1: user needs to choose course
16777:  2: browse allowed
16778:  A: passphrase authentication needed
16779:  B: access temporarily blocked because of a blocking event in a course.
16780:  D: access blocked because access is required via session initiated via deep-link 
16781: 
16782: =item *
16783: 
16784: constructaccess($url,$setpriv) : check for access to construction space URL
16785: 
16786: See if the owner domain and name in the URL match those in the
16787: expected environment.  If so, return three element list
16788: ($ownername,$ownerdomain,$ownerhome).
16789: 
16790: Otherwise return the null string.
16791: 
16792: If second argument 'setpriv' is true, it assigns the privileges,
16793: and returns the same three element list, unless the owner has
16794: blocked "ad hoc" Domain Coordinator access to the Author Space,
16795: in which case the null string is returned.
16796: 
16797: =item *
16798: 
16799: definerole($rolename,$sysrole,$domrole,$courole,$uname,$udom) : define role;
16800: define a custom role rolename set privileges in format of lonTabs/roles.tab
16801: for system, domain, and course level. $uname and $udom are optional (current
16802: user's username and domain will be used when either of $uname or $udom are absent.
16803: 
16804: =item *
16805: 
16806: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
16807: (rolesplain.tab); plain text explanation of a user role term.
16808: $type is Course (default) or Community.
16809: If $forcedefault evaluates to true, text returned will be default 
16810: text for $type. Otherwise, if this is a course, the text returned 
16811: will be a custom name for the role (if defined in the course's 
16812: environment).  If no custom name is defined the default is returned.
16813:    
16814: =item *
16815: 
16816: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv) :
16817: All arguments are optional. Returns a hash of a roles, either for
16818: co-author/assistant author roles for a user's Construction Space
16819: (default), or if $context is 'userroles', roles for the user himself,
16820: In the hash, keys are set to colon-separated $uname,$udom,$role, and
16821: (optionally) if $withsec is true, a fourth colon-separated item - $section.
16822: For each key, value is set to colon-separated start and end times for
16823: the role.  If no username and domain are specified, will default to
16824: current user/domain. Types, roles, and roledoms are references to arrays
16825: of role statuses (active, future or previous), roles 
16826: (e.g., cc,in, st etc.) and domains of the roles which can be used
16827: to restrict the list of roles reported. If no array ref is 
16828: provided for types, will default to return only active roles.
16829: 
16830: =item *
16831: 
16832: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
16833: user: $uname:$udom has a role in the course: $cdom_$cnum. 
16834: 
16835: Additional optional arguments are: $type (if role checking is to be restricted 
16836: to certain user status types -- previous (expired roles), active (currently
16837: available roles) or future (roles available in the future), and
16838: $hideprivileged -- if true will not report course roles for users who
16839: have active Domain Coordinator role in course's domain or in additional
16840: domains (specified in 'Domains to check for privileged users' in course
16841: environment -- set via:  Course Settings -> Classlists and staff listing).
16842: 
16843: =item *
16844: 
16845: privileged($username,$domain,$possdomains,$possroles) : returns 1 if user
16846: $username:$domain is a privileged user (e.g., Domain Coordinator or Super User)
16847: $possdomains and $possroles are optional array refs -- to domains to check and
16848: roles to check.  If $possdomains is not specified, a dump will be done of the
16849: users' roles.db to check for a dc or su role in any domain. This can be
16850: time consuming if &privileged is called repeatedly (e.g., when displaying a
16851: classlist), so in such cases, supplying a $possdomains array is preferred, as
16852: this then allows &privileged_by_domain() to be used, which caches the identity
16853: of privileged users, eliminating the need for repeated calls to &dump().
16854: 
16855: =item *
16856: 
16857: privileged_by_domain($possdomains,$roles) : returns a hash of a hash of a hash,
16858: where the outer hash keys are domains specified in the $possdomains array ref,
16859: next inner hash keys are privileged roles specified in the $roles array ref,
16860: and the innermost hash contains key = value pairs for username:domain = end:start
16861: for active or future "privileged" users with that role in that domain. To avoid
16862: repeated dumps of domain roles -- via &get_domain_roles() -- contents of the
16863: innerhash are cached using priv_$role and $dom as the identifiers.
16864: 
16865: =back
16866: 
16867: =head2 User Modification
16868: 
16869: =over 4
16870: 
16871: =item *
16872: 
16873: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
16874: user for the level given by URL.  Optional start and end dates (leave empty
16875: string or zero for "no date")
16876: 
16877: =item *
16878: 
16879: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
16880: change a users, password, possible return values are: ok,
16881: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
16882: refused
16883: 
16884: =item *
16885: 
16886: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
16887: 
16888: =item *
16889: 
16890: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
16891:            $forceid,$desiredhome,$email,$inststatus,$candelete) :
16892: 
16893: will update user information (firstname,middlename,lastname,generation,
16894: permanentemail), and if forceid is true, student/employee ID also.
16895: A user's institutional affiliation(s) can also be updated.
16896: User information fields will not be overwritten with empty entries 
16897: unless the field is included in the $candelete array reference.
16898: This array is included when a single user is modified via "Manage Users",
16899: or when Autoupdate.pl is run by cron in a domain.
16900: 
16901: =item *
16902: 
16903: modifystudent
16904: 
16905: modify a student's enrollment and identification information.
16906: The course id is resolved based on the current user's environment.  
16907: This means the invoking user must be a course coordinator or otherwise
16908: associated with a course.
16909: 
16910: This call is essentially a wrapper for lonnet::modifyuser and
16911: lonnet::modify_student_enrollment
16912: 
16913: Inputs: 
16914: 
16915: =over 4
16916: 
16917: =item B<$udom> Student's loncapa domain
16918: 
16919: =item B<$uname> Student's loncapa login name
16920: 
16921: =item B<$uid> Student/Employee ID
16922: 
16923: =item B<$umode> Student's authentication mode
16924: 
16925: =item B<$upass> Student's password
16926: 
16927: =item B<$first> Student's first name
16928: 
16929: =item B<$middle> Student's middle name
16930: 
16931: =item B<$last> Student's last name
16932: 
16933: =item B<$gene> Student's generation
16934: 
16935: =item B<$usec> Student's section in course
16936: 
16937: =item B<$end> Unix time of the roles expiration
16938: 
16939: =item B<$start> Unix time of the roles start date
16940: 
16941: =item B<$forceid> If defined, allow $uid to be changed
16942: 
16943: =item B<$desiredhome> server to use as home server for student
16944: 
16945: =item B<$email> Student's permanent e-mail address
16946: 
16947: =item B<$type> Type of enrollment (auto or manual)
16948: 
16949: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
16950: 
16951: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
16952: 
16953: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
16954: 
16955: =item B<$context> role change context (shown in User Management Logs display in a course)
16956: 
16957: =item B<$inststatus> institutional status of user - : separated string of escaped status types
16958: 
16959: =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.
16960: 
16961: =back
16962: 
16963: =item *
16964: 
16965: modify_student_enrollment
16966: 
16967: Change a student's enrollment status in a class.  The environment variable
16968: 'role.request.course' must be defined for this function to proceed.
16969: 
16970: Inputs:
16971: 
16972: =over 4
16973: 
16974: =item $udom, student's domain
16975: 
16976: =item $uname, student's name
16977: 
16978: =item $uid, student's user id
16979: 
16980: =item $first, student's first name
16981: 
16982: =item $middle
16983: 
16984: =item $last
16985: 
16986: =item $gene
16987: 
16988: =item $usec
16989: 
16990: =item $end
16991: 
16992: =item $start
16993: 
16994: =item $type
16995: 
16996: =item $locktype
16997: 
16998: =item $cid
16999: 
17000: =item $selfenroll
17001: 
17002: =item $context
17003: 
17004: =item $credits, number of credits student will earn from this class
17005: 
17006: =item $instsec, institutional course section code for student
17007: 
17008: =back
17009: 
17010: 
17011: =item *
17012: 
17013: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
17014: custom role; give a custom role to a user for the level given by URL.  Specify
17015: name and domain of role author, and role name
17016: 
17017: =item *
17018: 
17019: revokerole($udom,$uname,$url,$role) : revoke a role for url
17020: 
17021: =item *
17022: 
17023: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
17024: 
17025: =back
17026: 
17027: =head2 Course Infomation
17028: 
17029: =over 4
17030: 
17031: =item *
17032: 
17033: coursedescription($courseid,$options) : returns a hash of information about the
17034: specified course id, including all environment settings for the
17035: course, the description of the course will be in the hash under the
17036: key 'description'
17037: 
17038: $options is an optional parameter that if supplied is a hash reference that controls
17039: what how this function works.  It has the following key/values:
17040: 
17041: =over 4
17042: 
17043: =item freshen_cache
17044: 
17045: If defined, and the environment cache for the course is valid, it is 
17046: returned in the returned hash.
17047: 
17048: =item one_time
17049: 
17050: If defined, the last cache time is set to _now_
17051: 
17052: =item user
17053: 
17054: If defined, the supplied username is used instead of the current user.
17055: 
17056: 
17057: =back
17058: 
17059: =item *
17060: 
17061: resdata($name,$domain,$type,@which) : request for current parameter
17062: setting for a specific $type, where $type is either 'course' or 'user',
17063: @what should be a list of parameters to ask about. This routine caches
17064: answers for 10 minutes.
17065: 
17066: =item *
17067: 
17068: get_courseresdata($courseid, $domain) : dump the entire course resource
17069: data base, returning a hash that is keyed by the resource name and has
17070: values that are the resource value.  I believe that the timestamps and
17071: versions are also returned.
17072: 
17073: =back
17074: 
17075: =head2 Course Modification
17076: 
17077: =over 4
17078: 
17079: =item *
17080: 
17081: writecoursepref($courseid,%prefs) : write preferences (environment
17082: database) for a course
17083: 
17084: =item *
17085: 
17086: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
17087: 
17088: =item *
17089: 
17090: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
17091: 
17092: =item *
17093: 
17094: is_course($courseid), is_course($cdom, $cnum)
17095: 
17096: Accepts either a combined $courseid (in the form of domain_courseid) or the
17097: two component version $cdom, $cnum. It checks if the specified course exists.
17098: 
17099: Returns:
17100:     undef if the course doesn't exist, otherwise
17101:     in scalar context the combined courseid.
17102:     in list context the two components of the course identifier, domain and 
17103:     courseid.    
17104: 
17105: =back
17106: 
17107: =head2 Bubblesheet Configuration
17108: 
17109: =over 4
17110: 
17111: =item *
17112: 
17113: get_scantron_config($which)
17114: 
17115: $which - the name of the configuration to parse from the file.
17116: 
17117: Parses and returns the bubblesheet configuration line selected as a
17118: hash of configuration file fields.
17119: 
17120: 
17121: Returns:
17122:     If the named configuration is not in the file, an empty
17123:     hash is returned.
17124: 
17125:     a hash with the fields
17126:       name         - internal name for the this configuration setup
17127:       description  - text to display to operator that describes this config
17128:       CODElocation - if 0 or the string 'none'
17129:                           - no CODE exists for this config
17130:                      if -1 || the string 'letter'
17131:                           - a CODE exists for this config and is
17132:                             a string of letters
17133:                      Unsupported value (but planned for future support)
17134:                           if a positive integer
17135:                                - The CODE exists as the first n items from
17136:                                  the question section of the form
17137:                           if the string 'number'
17138:                                - The CODE exists for this config and is
17139:                                  a string of numbers
17140:       CODEstart   - (only matter if a CODE exists) column in the line where
17141:                      the CODE starts
17142:       CODElength  - length of the CODE
17143:       IDstart     - column where the student/employee ID starts
17144:       IDlength    - length of the student/employee ID info
17145:       Qstart      - column where the information from the bubbled
17146:                     'questions' start
17147:       Qlength     - number of columns comprising a single bubble line from
17148:                     the sheet. (usually either 1 or 10)
17149:       Qon         - either a single character representing the character used
17150:                     to signal a bubble was chosen in the positional setup, or
17151:                     the string 'letter' if the letter of the chosen bubble is
17152:                     in the final, or 'number' if a number representing the
17153:                     chosen bubble is in the file (1->A 0->J)
17154:       Qoff        - the character used to represent that a bubble was
17155:                     left blank
17156:       PaperID     - if the scanning process generates a unique number for each
17157:                     sheet scanned the column that this ID number starts in
17158:       PaperIDlength - number of columns that comprise the unique ID number
17159:                       for the sheet of paper
17160:       FirstName   - column that the first name starts in
17161:       FirstNameLength - number of columns that the first name spans
17162:       LastName    - column that the last name starts in
17163:       LastNameLength - number of columns that the last name spans
17164:       BubblesPerRow - number of bubbles available in each row used to
17165:                       bubble an answer. (If not specified, 10 assumed).
17166: 
17167: 
17168: =item *
17169: 
17170: get_scantronformat_file($cdom)
17171: 
17172: $cdom - the course's domain (optional); if not supplied, uses
17173: domain for current $env{'request.course.id'}.
17174: 
17175: Returns an array containing lines from the scantron format file for
17176: the domain of the course.
17177: 
17178: If a url for a custom.tab file is listed in domain's configuration.db,
17179: lines are from this file.
17180: 
17181: Otherwise, if a default.tab has been published in RES space by the
17182: domainconfig user, lines are from this file.
17183: 
17184: Otherwise, fall back to getting lines from the legacy file on the
17185: local server:  /home/httpd/lonTabs/default_scantronformat.tab
17186: 
17187: =back
17188: 
17189: =head2 Resource Subroutines
17190: 
17191: =over 4
17192: 
17193: =item *
17194: 
17195: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
17196: 
17197: =item *
17198: 
17199: repcopy($filename) : subscribes to the requested file, and attempts to
17200: replicate from the owning library server, Might return
17201: 'unavailable', 'not_found', 'forbidden', 'ok', or
17202: 'bad_request', also attempts to grab the metadata for the
17203: resource. Expects the local filesystem pathname
17204: (/home/httpd/html/res/....)
17205: 
17206: =back
17207: 
17208: =head2 Resource Information
17209: 
17210: =over 4
17211: 
17212: =item *
17213: 
17214: EXT($varname,$symb,$udom,$uname,$usection,$recurse,$cid) : evaluates 
17215: and returns the value of a variety of different possible values,
17216: $varname should be a request string, and the other parameters can be
17217: used to specify who and what one is asking about. Ordinarily, $cid 
17218: does not need to be specified, as it is retrived from 
17219: $env{'request.course.id'}, but &Apache::lonnet::EXT() is called
17220: within lonuserstate::loadmap() when initializing a course, before
17221: $env{'request.course.id'} has been set, so it needs to be provided
17222: in that one case.
17223: 
17224: Possible values for $varname are environment.lastname (or other item
17225: from the envirnment hash), user.name (or someother aspect about the
17226: user), resource.0.maxtries (or some other part and parameter of a
17227: resource)
17228: 
17229: =item *
17230: 
17231: directcondval($number) : get current value of a condition; reads from a state
17232: string
17233: 
17234: =item *
17235: 
17236: condval($condidx) : value of condition index based on state
17237: 
17238: =item *
17239: 
17240: metadata($uri,$what,$toolsymb,$liburi,$prefix,$depthcount) : request a
17241: resource's metadata, $what should be either a specific key, or either
17242: 'keys' (to get a list of possible keys) or 'packages' to get a list of
17243: packages that this resource currently uses, the last 3 arguments are 
17244: only used internally for recursive metadata.
17245: 
17246: the toolsymb is only used where the uri is for an external tool (for which
17247: the uri as well as the symb are guaranteed to be unique).
17248: 
17249: this function automatically caches all requests except any made recursively
17250: to retrieve a list of metadata keys for an imported library file ($liburi is 
17251: defined).
17252: 
17253: =item *
17254: 
17255: metadata_query($query,$custom,$customshow) : make a metadata query against the
17256: network of library servers; returns file handle of where SQL and regex results
17257: will be stored for query
17258: 
17259: =item *
17260: 
17261: symbread($filename,$donotrecurse,$ignorecachednull,$checkforblock,$possibles) : 
17262: return symbolic list entry (all arguments optional). 
17263: 
17264: Args: filename is the filename (including path) for the file for which a symb 
17265: is required; donotrecurse, if true will prevent calls to allowed() being made 
17266: to check access status if more than one resource was found in the bighash 
17267: (see rev. 1.249) to avoid an infinite loop if an ambiguous resource is part of 
17268: a randompick); ignorecachednull, if true will prevent a symb of '' being 
17269: returned if $env{$cache_str} is defined as ''; checkforblock if true will
17270: cause possible symbs to be checked to determine if they are subject to content
17271: blocking, if so they will not be included as possible symbs; possibles is a
17272: ref to a hash, which, as a side effect, will be populated with all possible 
17273: symbs (content blocking not tested).
17274:  
17275: returns the data handle
17276: 
17277: =item *
17278: 
17279: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
17280: and is a possible symb for the URL in $thisfn, and if is an encrypted
17281: resource that the user accessed using /enc/ returns a 1 on success, 0
17282: on failure, user must be in a course, as it assumes the existence of
17283: the course initial hash, and uses $env('request.course.id'}.  The third
17284: arg is an optional reference to a scalar.  If this arg is passed in the 
17285: call to symbverify, it will be set to 1 if the symb has been set to be 
17286: encrypted; otherwise it will be null.  
17287: 
17288: =item *
17289: 
17290: symbclean($symb) : removes versions numbers from a symb, returns the
17291: cleaned symb
17292: 
17293: =item *
17294: 
17295: is_on_map($uri) : checks if the $uri is somewhere on the current
17296: course map, user must be in a course for it to work.
17297: 
17298: =item *
17299: 
17300: numval($salt) : return random seed value (addend for rndseed)
17301: 
17302: =item *
17303: 
17304: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
17305: a random seed, all arguments are optional, if they aren't sent it uses the
17306: environment to derive them. Note: if symb isn't sent and it can't get one
17307: from &symbread it will use the current time as its return value
17308: 
17309: =item *
17310: 
17311: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
17312: unfakeable, receipt
17313: 
17314: =item *
17315: 
17316: receipt() : API to ireceipt working off of env values; given out to users
17317: 
17318: =item *
17319: 
17320: countacc($url) : count the number of accesses to a given URL
17321: 
17322: =item *
17323: 
17324: 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
17325: 
17326: =item *
17327: 
17328: 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)
17329: 
17330: =item *
17331: 
17332: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
17333: 
17334: =item *
17335: 
17336: devalidate($symb) : devalidate temporary spreadsheet calculations,
17337: forcing spreadsheet to reevaluate the resource scores next time.
17338: 
17339: =item * 
17340: 
17341: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
17342: when viewing in course context.
17343: 
17344:  input: six args -- filename (decluttered), course number, course domain,
17345:                     url, symb (if registered) and group (if this is a 
17346:                     group item -- e.g., bulletin board, group page etc.).
17347: 
17348:  output: array of five scalars --
17349:          $cfile -- url for file editing if editable on current server
17350:          $home -- homeserver of resource (i.e., for author if published,
17351:                                           or course if uploaded.).
17352:          $switchserver --  1 if server switch will be needed.
17353:          $forceedit -- 1 if icon/link should be to go to edit mode 
17354:          $forceview -- 1 if icon/link should be to go to view mode
17355: 
17356: =item *
17357: 
17358: is_course_upload($file,$cnum,$cdom)
17359: 
17360: Used in course context to determine if current file was uploaded to 
17361: the course (i.e., would be found in /userfiles/docs on the course's 
17362: homeserver.
17363: 
17364:   input: 3 args -- filename (decluttered), course number and course domain.
17365:   output: boolean -- 1 if file was uploaded.
17366: 
17367: =back
17368: 
17369: =head2 Storing/Retreiving Data
17370: 
17371: =over 4
17372: 
17373: =item *
17374: 
17375: store($storehash,$symb,$namespace,$udom,$uname,$laststore) : stores hash
17376: permanently for this url; hashref needs to be given and should be a \%hashname;
17377: the remaining args aren't required and if they aren't passed or are '' they will
17378: be derived from the env (with the exception of $laststore, which is an 
17379: optional arg used when a user's submission is stored in grading).
17380: $laststore is $version=$timestamp, where $version is the most recent version
17381: number retrieved for the corresponding $symb in the $namespace db file, and
17382: $timestamp is the timestamp for that transaction (UNIX time).
17383: $laststore is currently only passed when cstore() is called by 
17384: structuretags::finalize_storage().
17385: 
17386: =item *
17387: 
17388: cstore($storehash,$symb,$namespace,$udom,$uname,$laststore) : same as store
17389: but uses critical subroutine
17390: 
17391: =item *
17392: 
17393: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
17394: all args are optional
17395: 
17396: =item *
17397: 
17398: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
17399: dumps the complete (or key matching regexp) namespace into a hash
17400: ($udom, $uname, $regexp, $range are optional) for a namespace that is
17401: normally &store()ed into
17402: 
17403: $range should be either an integer '100' (give me the first 100
17404:                                            matching records)
17405:               or be  two integers sperated by a - with no spaces
17406:                  '30-50' (give me the 30th through the 50th matching
17407:                           records)
17408: 
17409: 
17410: =item *
17411: 
17412: putstore($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog) :
17413: replaces a &store() version of data with a replacement set of data
17414: for a particular resource in a namespace passed in the $storehash hash 
17415: reference. If $tolog is true, the transaction is logged in the courselog
17416: with an action=PUTSTORE.
17417: 
17418: =item *
17419: 
17420: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
17421: works very similar to store/cstore, but all data is stored in a
17422: temporary location and can be reset using tmpreset, $storehash should
17423: be a hash reference, returns nothing on success
17424: 
17425: =item *
17426: 
17427: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
17428: similar to restore, but all data is stored in a temporary location and
17429: can be reset using tmpreset. Returns a hash of values on success,
17430: error string otherwise.
17431: 
17432: =item *
17433: 
17434: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
17435: deltes all keys for $symb form the temporary storage hash.
17436: 
17437: =item *
17438: 
17439: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
17440: reference filled in from namesp ($udom and $uname are optional)
17441: 
17442: =item *
17443: 
17444: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
17445: namesp ($udom and $uname are optional)
17446: 
17447: =item *
17448: 
17449: dump($namespace,$udom,$uname,$regexp,$range) : 
17450: dumps the complete (or key matching regexp) namespace into a hash
17451: ($udom, $uname, $regexp, $range are optional)
17452: 
17453: $range should be either an integer '100' (give me the first 100
17454:                                            matching records)
17455:               or be  two integers sperated by a - with no spaces
17456:                  '30-50' (give me the 30th through the 50th matching
17457:                           records)
17458: =item *
17459: 
17460: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
17461: $store can be a scalar, an array reference, or if the amount to be 
17462: incremented is > 1, a hash reference.
17463: 
17464: ($udom and $uname are optional)
17465: 
17466: =item *
17467: 
17468: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
17469: ($udom and $uname are optional)
17470: 
17471: =item *
17472: 
17473: cput($namespace,$storehash,$udom,$uname) : critical put
17474: ($udom and $uname are optional)
17475: 
17476: =item *
17477: 
17478: newput($namespace,$storehash,$udom,$uname) :
17479: 
17480: Attempts to store the items in the $storehash, but only if they don't
17481: currently exist, if this succeeds you can be certain that you have 
17482: successfully created a new key value pair in the $namespace db.
17483: 
17484: 
17485: Args:
17486:  $namespace: name of database to store values to
17487:  $storehash: hashref to store to the db
17488:  $udom: (optional) domain of user containing the db
17489:  $uname: (optional) name of user caontaining the db
17490: 
17491: Returns:
17492:  'ok' -> succeeded in storing all keys of $storehash
17493:  'key_exists: <key>' -> failed to anything out of $storehash, as at
17494:                         least <key> already existed in the db (other
17495:                         requested keys may also already exist)
17496:  'error: <msg>' -> unable to tie the DB or other error occurred
17497:  'con_lost' -> unable to contact request server
17498:  'refused' -> action was not allowed by remote machine
17499: 
17500: 
17501: =item *
17502: 
17503: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
17504: reference filled in from namesp (encrypts the return communication)
17505: ($udom and $uname are optional)
17506: 
17507: =item *
17508: 
17509: log($udom,$name,$home,$message) : write to permanent log for user; use
17510: critical subroutine
17511: 
17512: =item *
17513: 
17514: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
17515: array reference filled in from namespace found in domain level on either
17516: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
17517: 
17518: =item *
17519: 
17520: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
17521: domain level either on specified domain server ($uhome) or primary domain 
17522: server ($udom and $uhome are optional)
17523: 
17524: =item * 
17525: 
17526: get_domain_defaults($target_domain,$ignore_cache) : returns hash with defaults 
17527: for: authentication, language, quotas, timezone, date locale, and portal URL in
17528: the target domain.
17529: 
17530: May also include additional key => value pairs for the following groups:
17531: 
17532: =over
17533: 
17534: =item
17535: disk quotas (MB allocated by default to portfolios and authoring spaces).
17536: 
17537: =over
17538: 
17539: =item defaultquota, authorquota
17540: 
17541: =back
17542: 
17543: =item
17544: tools (availability of aboutme page, blog, webDAV access for authoring spaces,
17545: portfolio for users).
17546: 
17547: =over
17548: 
17549: =item
17550: aboutme, blog, webdav, portfolio
17551: 
17552: =back
17553: 
17554: =item
17555: requestcourses: ability to request courses, and how requests are processed.
17556: 
17557: =over
17558: 
17559: =item
17560: official, unofficial, community, textbook, placement
17561: 
17562: =back
17563: 
17564: =item
17565: inststatus: types of institutional affiliation, and order in which they are displayed.
17566: 
17567: =over
17568: 
17569: =item
17570: inststatustypes, inststatusorder, inststatusguest
17571: 
17572: =back
17573: 
17574: =item
17575: coursedefaults: can PDF forms can be created, default credits for courses, default quotas (MB)
17576: for course's uploaded content.
17577: 
17578: =over
17579: 
17580: =item
17581: canuse_pdfforms, officialcredits, unofficialcredits, textbookcredits, officialquota, unofficialquota, 
17582: communityquota, textbookquota, placementquota
17583: 
17584: =back
17585: 
17586: =item
17587: usersessions: set options for hosting of your users in other domains, and hosting of users from other domains
17588: on your servers.
17589: 
17590: =over
17591: 
17592: =item 
17593: remotesessions, hostedsessions
17594: 
17595: =back
17596: 
17597: =back
17598: 
17599: In cases where a domain coordinator has never used the "Set Domain Configuration"
17600: utility to create a configuration.db file on a domain's primary library server 
17601: only the following domain defaults: auth_def, auth_arg_def, lang_def
17602: -- corresponding values are authentication type (internal, krb4, krb5,
17603: or localauth), initial password or a kerberos realm, language (e.g., en-us) -- 
17604: will be available. Values are retrieved from cache (if current), unless the
17605: optional $ignore_cache arg is true, or from domain's configuration.db (if available),
17606: or lastly from values in lonTabs/dns_domain,tab, or lonTabs/domain.tab.
17607: 
17608: Typical usage:
17609: 
17610: %domdefaults = &get_domain_defaults($target_domain);
17611: 
17612: =back
17613: 
17614: =head2 Network Status Functions
17615: 
17616: =over 4
17617: 
17618: =item *
17619: 
17620: dirlist() : return directory list based on URI (first arg).
17621: 
17622: Inputs: 1 required, 5 optional.
17623: 
17624: =over
17625: 
17626: =item 
17627: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
17628: 
17629: =item
17630: $userdomain - domain of user/course to be listed. Extracted from $uri if absent. 
17631: 
17632: =item
17633: $username -  username of user/course to be listed. Extracted from $uri if absent. 
17634: 
17635: =item
17636: $getpropath - boolean: 1 if prepend path using &propath(). 
17637: 
17638: =item
17639: $getuserdir - boolean: 1 if prepend path for "userfiles".
17640: 
17641: =item 
17642: $alternateRoot - path to prepend in place of path from $uri.
17643: 
17644: =back
17645: 
17646: Returns: Array of up to two items.
17647: 
17648: =over
17649: 
17650: a reference to an array of files/subdirectories
17651: 
17652: =over
17653: 
17654: Each element in the array of files/subdirectories is a & separated list of
17655: item name and the result of running stat on the item.  If dirlist was requested
17656: for a file instead of a directory, the item name will be ''. For a directory 
17657: listing, if the item is a metadata file, the element will end &N&M 
17658: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
17659: default copyright set (1).  
17660: 
17661: =back
17662: 
17663: a scalar containing error condition (if encountered).
17664: 
17665: =over
17666: 
17667: =item 
17668: no_host (no homeserver identified for $username:$domain).
17669: 
17670: =item 
17671: no_such_host (server contacted for listing not identified as valid host).
17672: 
17673: =item 
17674: con_lost (connection to remote server failed).
17675: 
17676: =item 
17677: refused (invalid $username:$domain received on lond side).
17678: 
17679: =item 
17680: no_such_dir (directory at specified path on lond side does not exist). 
17681: 
17682: =item 
17683: empty (directory at specified path on lond side is empty).
17684: 
17685: =over
17686: 
17687: This is currently not encountered because the &ls3, &ls2, 
17688: &ls (_handler) routines on the lond side do not filter out
17689: . and .. from a directory listing. 
17690: 
17691: =back
17692: 
17693: =back
17694: 
17695: =back
17696: 
17697: =item *
17698: 
17699: spareserver() : find server with least workload from spare.tab
17700: 
17701: 
17702: =item *
17703: 
17704: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
17705: if there is no corresponding loncapa host.
17706: 
17707: =back
17708: 
17709: 
17710: =head2 Apache Request
17711: 
17712: =over 4
17713: 
17714: =item *
17715: 
17716: ssi($url,%hash) : server side include, does a complete request cycle on url to
17717: localhost, posts hash
17718: 
17719: =back
17720: 
17721: =head2 Data to String to Data
17722: 
17723: =over 4
17724: 
17725: =item *
17726: 
17727: hash2str(%hash) : convert a hash into a string complete with escaping and '='
17728: and '&' separators, supports elements that are arrayrefs and hashrefs
17729: 
17730: =item *
17731: 
17732: hashref2str($hashref) : convert a hashref into a string complete with
17733: escaping and '=' and '&' separators, supports elements that are
17734: arrayrefs and hashrefs
17735: 
17736: =item *
17737: 
17738: arrayref2str($arrayref) : convert an arrayref into a string complete
17739: with escaping and '&' separators, supports elements that are arrayrefs
17740: and hashrefs
17741: 
17742: =item *
17743: 
17744: str2hash($string) : convert string to hash using unescaping and
17745: splitting on '=' and '&', supports elements that are arrayrefs and
17746: hashrefs
17747: 
17748: =item *
17749: 
17750: str2array($string) : convert string to hash using unescaping and
17751: splitting on '&', supports elements that are arrayrefs and hashrefs
17752: 
17753: =back
17754: 
17755: =head2 Logging Routines
17756: 
17757: 
17758: These routines allow one to make log messages in the lonnet.log and
17759: lonnet.perm logfiles.
17760: 
17761: =over 4
17762: 
17763: =item *
17764: 
17765: logtouch() : make sure the logfile, lonnet.log, exists
17766: 
17767: =item *
17768: 
17769: logthis() : append message to the normal lonnet.log file, it gets
17770: preiodically rolled over and deleted.
17771: 
17772: =item *
17773: 
17774: logperm() : append a permanent message to lonnet.perm.log, this log
17775: file never gets deleted by any automated portion of the system, only
17776: messages of critical importance should go in here.
17777: 
17778: 
17779: =back
17780: 
17781: =head2 General File Helper Routines
17782: 
17783: =over 4
17784: 
17785: =item *
17786: 
17787: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
17788: (a) files in /uploaded
17789:   (i) If a local copy of the file exists - 
17790:       compares modification date of local copy with last-modified date for 
17791:       definitive version stored on home server for course. If local copy is 
17792:       stale, requests a new version from the home server and stores it. 
17793:       If the original has been removed from the home server, then local copy 
17794:       is unlinked.
17795:   (ii) If local copy does not exist -
17796:       requests the file from the home server and stores it. 
17797:   
17798:   If $caller is 'uploadrep':  
17799:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
17800:     for request for files originally uploaded via DOCS. 
17801:      - returns 'ok' if fresh local copy now available, -1 otherwise.
17802:   
17803:   Otherwise:
17804:      This indicates a call from the content generation phase of the request.
17805:      -  returns the entire contents of the file or -1.
17806:      
17807: (b) files in /res
17808:    - returns the entire contents of a file or -1; 
17809:    it properly subscribes to and replicates the file if neccessary.
17810: 
17811: 
17812: =item *
17813: 
17814: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
17815:                   reference
17816: 
17817: returns either a stat() list of data about the file or an empty list
17818: if the file doesn't exist or couldn't find out about it (connection
17819: problems or user unknown)
17820: 
17821: =item *
17822: 
17823: filelocation($dir,$file) : returns file system location of a file
17824: based on URI; meant to be "fairly clean" absolute reference, $dir is a
17825: directory that relative $file lookups are to looked in ($dir of /a/dir
17826: and a file of ../bob will become /a/bob)
17827: 
17828: =item *
17829: 
17830: hreflocation($dir,$file) : returns file system location or a URL; same as
17831: filelocation except for hrefs
17832: 
17833: =item *
17834: 
17835: declutter() : declutters URLs -- remove beginning slashes, 'res' etc.
17836: also removes beginning /home/httpd/html unless /priv/ follows it.
17837: 
17838: =back
17839: 
17840: =head2 Usererfile file routines (/uploaded*)
17841: 
17842: =over 4
17843: 
17844: =item *
17845: 
17846: userfileupload(): main rotine for putting a file in a user or course's
17847:                   filespace, arguments are,
17848: 
17849:  formname - required - this is the name of the element in $env where the
17850:            filename, and the contents of the file to create/modifed exist
17851:            the filename is in $env{'form.'.$formname.'.filename'} and the
17852:            contents of the file is located in $env{'form.'.$formname}
17853:  context - if coursedoc, store the file in the course of the active role
17854:              of the current user; 
17855:            if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
17856:            if 'canceloverwrite': delete file in tmp/overwrites directory
17857:  subdir - required - subdirectory to put the file in under ../userfiles/
17858:          if undefined, it will be placed in "unknown"
17859: 
17860:  (This routine calls clean_filename() to remove any dangerous
17861:  characters from the filename, and then calls finuserfileupload() to
17862:  complete the transaction)
17863: 
17864:  returns either the url of the uploaded file (/uploaded/....) if successful
17865:  and /adm/notfound.html if unsuccessful
17866: 
17867: =item *
17868: 
17869: clean_filename(): routine for cleaing a filename up for storage in
17870:                  userfile space, argument is:
17871: 
17872:  filename - proposed filename
17873: 
17874: returns: the new clean filename
17875: 
17876: =item *
17877: 
17878: finishuserfileupload(): routine that creates and sends the file to
17879: userspace, probably shouldn't be called directly
17880: 
17881:   docuname: username or courseid of destination for the file
17882:   docudom: domain of user/course of destination for the file
17883:   formname: same as for userfileupload()
17884:   fname: filename (including subdirectories) for the file
17885:   parser: if 'parse', will parse (html) file to extract references to objects, links etc.
17886:           if hashref, and context is scantron, will convert csv format to standard format
17887:   allfiles: reference to hash used to store objects found by parser
17888:   codebase: reference to hash used for codebases of java objects found by parser
17889:   thumbwidth: width (pixels) of thumbnail to be created for uploaded image
17890:   thumbheight: height (pixels) of thumbnail to be created for uploaded image
17891:   resizewidth: width to be used to resize image using resizeImage from ImageMagick
17892:   resizeheight: height to be used to resize image using resizeImage from ImageMagick
17893:   context: if 'overwrite', will move the uploaded file from its temporary location to
17894:             userfiles to facilitate overwriting a previously uploaded file with same name.
17895:   mimetype: reference to scalar to accommodate mime type determined
17896:             from File::MMagic if $parser = parse.
17897: 
17898:  returns either the url of the uploaded file (/uploaded/....) if successful
17899:  and /adm/notfound.html if unsuccessful (or an error message if context 
17900:  was 'overwrite').
17901:  
17902: 
17903: =item *
17904: 
17905: renameuserfile(): renames an existing userfile to a new name
17906: 
17907:   Args:
17908:    docuname: username or courseid of destination for the file
17909:    docudom: domain of user/course of destination for the file
17910:    old: current file name (including any subdirs under userfiles)
17911:    new: desired file name (including any subdirs under userfiles)
17912: 
17913: =item *
17914: 
17915: mkdiruserfile(): creates a directory is a userfiles dir
17916: 
17917:   Args:
17918:    docuname: username or courseid of destination for the file
17919:    docudom: domain of user/course of destination for the file
17920:    dir: dir to create (including any subdirs under userfiles)
17921: 
17922: =item *
17923: 
17924: removeuserfile(): removes a file that exists in userfiles
17925: 
17926:   Args:
17927:    docuname: username or courseid of destination for the file
17928:    docudom: domain of user/course of destination for the file
17929:    fname: filname to delete (including any subdirs under userfiles)
17930: 
17931: =item *
17932: 
17933: removeuploadedurl(): convience function for removeuserfile()
17934: 
17935:   Args:
17936:    url:  a full /uploaded/... url to delete
17937: 
17938: =item * 
17939: 
17940: get_portfile_permissions():
17941:   Args:
17942:     domain: domain of user or course contain the portfolio files
17943:     user: name of user or num of course contain the portfolio files
17944:   Returns:
17945:     hashref of a dump of the proper file_permissions.db
17946:    
17947: 
17948: =item * 
17949: 
17950: get_access_controls():
17951: 
17952: Args:
17953:   current_permissions: the hash ref returned from get_portfile_permissions()
17954:   group: (optional) the group you want the files associated with
17955:   file: (optional) the file you want access info on
17956: 
17957: Returns:
17958:     a hash (keys are file names) of hashes containing
17959:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
17960:         values are XML containing access control settings (see below) 
17961: 
17962: Internal notes:
17963: 
17964:  access controls are stored in file_permissions.db as key=value pairs.
17965:     key -> path to file/file_name\0uniqueID:scope_end_start
17966:         where scope -> public,guest,course,group,domains or users.
17967:               end -> UNIX time for end of access (0 -> no end date)
17968:               start -> UNIX time for start of access
17969: 
17970:     value -> XML description of access control
17971:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
17972:             <start></start>
17973:             <end></end>
17974: 
17975:             <password></password>  for scope type = guest
17976: 
17977:             <domain></domain>     for scope type = course or group
17978:             <number></number>
17979:             <roles id="">
17980:              <role></role>
17981:              <access></access>
17982:              <section></section>
17983:              <group></group>
17984:             </roles>
17985: 
17986:             <dom></dom>         for scope type = domains
17987: 
17988:             <users>             for scope type = users
17989:              <user>
17990:               <uname></uname>
17991:               <udom></udom>
17992:              </user>
17993:             </users>
17994:            </scope> 
17995:               
17996:  Access data is also aggregated for each file in an additional key=value pair:
17997:  key -> path to file/file_name\0accesscontrol 
17998:  value -> reference to hash
17999:           hash contains key = value pairs
18000:           where key = uniqueID:scope_end_start
18001:                 value = UNIX time record was last updated
18002: 
18003:           Used to improve speed of look-ups of access controls for each file.  
18004:  
18005:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
18006: 
18007: =item *
18008: 
18009: modify_access_controls():
18010: 
18011: Modifies access controls for a portfolio file
18012: Args
18013: 1. file name
18014: 2. reference to hash of required changes,
18015: 3. domain
18016: 4. username
18017:   where domain,username are the domain of the portfolio owner 
18018:   (either a user or a course) 
18019: 
18020: Returns:
18021: 1. result of additions or updates ('ok' or 'error', with error message). 
18022: 2. result of deletions ('ok' or 'error', with error message).
18023: 3. reference to hash of any new or updated access controls.
18024: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
18025:    key = integer (inbound ID)
18026:    value = uniqueID
18027: 
18028: =item *
18029: 
18030: get_timebased_id():
18031: 
18032: Attempts to get a unique timestamp-based suffix for use with items added to a 
18033: course via the Course Editor (e.g., folders, composite pages, 
18034: group bulletin boards).
18035: 
18036: Args: (first three required; six others optional)
18037: 
18038: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
18039:    docssequence, or name of group
18040: 
18041: 2. keyid (alphanumeric): name of temporary locking key in hash,
18042:    e.g., num, boardids
18043: 
18044: 3. namespace: name of gdbm file used to store suffixes already assigned;  
18045:    file will be named nohist_namespace.db
18046: 
18047: 4. cdom: domain of course; default is current course domain from %env
18048: 
18049: 5. cnum: course number; default is current course number from %env
18050: 
18051: 6. idtype: set to concat if an additional digit is to be appended to the 
18052:    unix timestamp to form the suffix, if the plain timestamp is already
18053:    in use.  Default is to not do this, but simply increment the unix 
18054:    timestamp by 1 until a unique key is obtained.
18055: 
18056: 7. who: holder of locking key; defaults to user:domain for user.
18057: 
18058: 8. locktries: number of attempts to obtain a lock (sleep of 1s before 
18059:    retrying); default is 3.
18060: 
18061: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.  
18062: 
18063: Returns:
18064: 
18065: 1. suffix obtained (numeric)
18066: 
18067: 2. result of deleting locking key (ok if deleted, or lock never obtained)
18068: 
18069: 3. error: contains (localized) error message if an error occurred.
18070: 
18071: 
18072: =back
18073: 
18074: =head2 HTTP Helper Routines
18075: 
18076: =over 4
18077: 
18078: =item *
18079: 
18080: escape() : unpack non-word characters into CGI-compatible hex codes
18081: 
18082: =item *
18083: 
18084: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
18085: 
18086: =back
18087: 
18088: =head1 PRIVATE SUBROUTINES
18089: 
18090: =head2 Underlying communication routines (Shouldn't call)
18091: 
18092: =over 4
18093: 
18094: =item *
18095: 
18096: subreply() : tries to pass a message to lonc, returns con_lost if incapable
18097: 
18098: =item *
18099: 
18100: reply() : uses subreply to send a message to remote machine, logs all failures
18101: 
18102: =item *
18103: 
18104: critical() : passes a critical message to another server; if cannot
18105: get through then place message in connection buffer directory and
18106: returns con_delayed, if incapable of saving message, returns
18107: con_failed
18108: 
18109: =item *
18110: 
18111: reconlonc() : tries to reconnect lonc client processes.
18112: 
18113: =back
18114: 
18115: =head2 Resource Access Logging
18116: 
18117: =over 4
18118: 
18119: =item *
18120: 
18121: flushcourselogs() : flush (save) buffer logs and access logs
18122: 
18123: =item *
18124: 
18125: courselog($what) : save message for course in hash
18126: 
18127: =item *
18128: 
18129: courseacclog($what) : save message for course using &courselog().  Perform
18130: special processing for specific resource types (problems, exams, quizzes, etc).
18131: 
18132: =item *
18133: 
18134: goodbye() : flush course logs and log shutting down; it is called in srm.conf
18135: as a PerlChildExitHandler
18136: 
18137: =back
18138: 
18139: =head2 Other
18140: 
18141: =over 4
18142: 
18143: =item *
18144: 
18145: symblist($mapname,%newhash) : update symbolic storage links
18146: 
18147: =back
18148: 
18149: =cut
18150: 

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