File:  [LON-CAPA] / loncom / lonnet / perl / lonnet.pm
Revision 1.1411: download - view: text, annotated - select for diffs
Thu Jul 18 18:28:58 2019 UTC (5 years ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Bug 6754. LON-CAPA as LTI Provider.
  Domain configuration to support session expiration in LON-CAPA,
  after user logs out of LTI Consumer which originally launched session,
  (if Consumer supports logoutServiceUrl; e.g. custom_logout_url in Canvas).

    1: # The LearningOnline Network
    2: # TCP networking package
    3: #
    4: # $Id: lonnet.pm,v 1.1411 2019/07/18 18:28:58 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);
   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 LONCAPA qw(:DEFAULT :match);
  100: use LONCAPA::Configuration;
  101: use LONCAPA::lonmetadata;
  102: use LONCAPA::Lond;
  103: use LONCAPA::LWPReq;
  104: use LONCAPA::transliterate;
  105: 
  106: use File::Copy;
  107: 
  108: my $readit;
  109: my $max_connection_retries = 20;     # Or some such value.
  110: 
  111: require Exporter;
  112: 
  113: our @ISA = qw (Exporter);
  114: our @EXPORT = qw(%env);
  115: 
  116: 
  117: # ------------------------------------ Logging (parameters, docs, slots, roles)
  118: {
  119:     my $logid;
  120:     sub write_log {
  121: 	my ($context,$hash_name,$storehash,$delflag,$uname,$udom,$cnum,$cdom)=@_;
  122:         if ($context eq 'course') {
  123:             if (($cnum eq '') || ($cdom eq '')) {
  124:                 $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
  125:                 $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
  126:             }
  127:         }
  128: 	$logid ++;
  129:         my $now = time();
  130: 	my $id=$now.'00000'.$$.'00000'.$logid;
  131:         my $logentry = { 
  132:                           $id => {
  133:                                    'exe_uname' => $env{'user.name'},
  134:                                    'exe_udom'  => $env{'user.domain'},
  135:                                    'exe_time'  => $now,
  136:                                    'exe_ip'    => $ENV{'REMOTE_ADDR'},
  137:                                    'delflag'   => $delflag,
  138:                                    'logentry'  => $storehash,
  139:                                    'uname'     => $uname,
  140:                                    'udom'      => $udom,
  141:                                   }
  142:                        };
  143: 	return &put('nohist_'.$hash_name,$logentry,$cdom,$cnum);
  144:     }
  145: }
  146: 
  147: sub logtouch {
  148:     my $execdir=$perlvar{'lonDaemons'};
  149:     unless (-e "$execdir/logs/lonnet.log") {	
  150: 	open(my $fh,">>","$execdir/logs/lonnet.log");
  151: 	close $fh;
  152:     }
  153:     my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
  154:     chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
  155: }
  156: 
  157: sub logthis {
  158:     my $message=shift;
  159:     my $execdir=$perlvar{'lonDaemons'};
  160:     my $now=time;
  161:     my $local=localtime($now);
  162:     if (open(my $fh,">>","$execdir/logs/lonnet.log")) {
  163: 	my $logstring = $local. " ($$): ".$message."\n"; # Keep any \'s in string.
  164: 	print $fh $logstring;
  165: 	close($fh);
  166:     }
  167:     return 1;
  168: }
  169: 
  170: sub logperm {
  171:     my $message=shift;
  172:     my $execdir=$perlvar{'lonDaemons'};
  173:     my $now=time;
  174:     my $local=localtime($now);
  175:     if (open(my $fh,">>","$execdir/logs/lonnet.perm.log")) {
  176: 	print $fh "$now:$message:$local\n";
  177: 	close($fh);
  178:     }
  179:     return 1;
  180: }
  181: 
  182: sub create_connection {
  183:     my ($hostname,$lonid) = @_;
  184:     my $client=IO::Socket::UNIX->new(Peer    => $perlvar{'lonSockCreate'},
  185: 				     Type    => SOCK_STREAM,
  186: 				     Timeout => 10);
  187:     return 0 if (!$client);
  188:     print $client (join(':',$hostname,$lonid,&machine_ids($hostname),$loncaparevs{$lonid})."\n");
  189:     my $result = <$client>;
  190:     chomp($result);
  191:     return 1 if ($result eq 'done');
  192:     return 0;
  193: }
  194: 
  195: sub get_server_timezone {
  196:     my ($cnum,$cdom) = @_;
  197:     my $home=&homeserver($cnum,$cdom);
  198:     if ($home ne 'no_host') {
  199:         my $cachetime = 24*3600;
  200:         my ($timezone,$cached)=&is_cached_new('servertimezone',$home);
  201:         if (defined($cached)) {
  202:             return $timezone;
  203:         } else {
  204:             my $timezone = &reply('servertimezone',$home);
  205:             return &do_cache_new('servertimezone',$home,$timezone,$cachetime);
  206:         }
  207:     }
  208: }
  209: 
  210: sub get_server_distarch {
  211:     my ($lonhost,$ignore_cache) = @_;
  212:     if (defined($lonhost)) {
  213:         if (!defined(&hostname($lonhost))) {
  214:             return;
  215:         }
  216:         my $cachetime = 12*3600;
  217:         if (!$ignore_cache) {
  218:             my ($distarch,$cached)=&is_cached_new('serverdistarch',$lonhost);
  219:             if (defined($cached)) {
  220:                 return $distarch;
  221:             }
  222:         }
  223:         my $rep = &reply('serverdistarch',$lonhost);
  224:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
  225:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
  226:                 $rep eq '') {
  227:             return &do_cache_new('serverdistarch',$lonhost,$rep,$cachetime);
  228:         }
  229:     }
  230:     return;
  231: }
  232: 
  233: sub get_servercerts_info {
  234:     my ($lonhost,$hostname,$context) = @_;
  235:     return if ($lonhost eq '');
  236:     if ($hostname eq '') {
  237:         $hostname = &hostname($lonhost);
  238:     }
  239:     return if ($hostname eq '');
  240:     my ($rep,$uselocal);
  241:     if ($context eq 'install') {
  242:         $uselocal = 1;
  243:     } elsif (grep { $_ eq $lonhost } &current_machine_ids()) {
  244:         $uselocal = 1;
  245:     }
  246:     if (($context ne 'cgi') && ($context ne 'install') && ($uselocal)) {
  247:         my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
  248:         if ($distro eq '') {
  249:             $uselocal = 0;
  250:         } elsif ($distro =~ /^(?:centos|redhat|scientific)(\d+)$/) {
  251:             if ($1 < 6) {
  252:                 $uselocal = 0;
  253:             }
  254:         }  elsif ($distro =~ /^(?:sles)(\d+)$/) {
  255:             if ($1 < 12) {
  256:                 $uselocal = 0;
  257:             }
  258:         }
  259:     }
  260:     if ($uselocal) {
  261:         $rep = LONCAPA::Lond::server_certs(\%perlvar,$lonhost,$hostname);
  262:     } else {
  263:         $rep=&reply('servercerts',$lonhost);
  264:     }
  265:     my ($result,%returnhash);
  266:     if (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
  267:         ($rep eq 'unknown_cmd')) {
  268:         $result = $rep;
  269:     } else {
  270:         $result = 'ok';
  271:         my @pairs=split(/\&/,$rep);
  272:         foreach my $item (@pairs) {
  273:             my ($key,$value)=split(/=/,$item,2);
  274:             my $what = &unescape($key);
  275:             $returnhash{$what}=&thaw_unescape($value);
  276:         }
  277:     }
  278:     return ($result,\%returnhash);
  279: }
  280: 
  281: sub get_server_loncaparev {
  282:     my ($dom,$lonhost,$ignore_cache,$caller) = @_;
  283:     if (defined($lonhost)) {
  284:         if (!defined(&hostname($lonhost))) {
  285:             undef($lonhost);
  286:         }
  287:     }
  288:     if (!defined($lonhost)) {
  289:         if (defined(&domain($dom,'primary'))) {
  290:             $lonhost=&domain($dom,'primary');
  291:             if ($lonhost eq 'no_host') {
  292:                 undef($lonhost);
  293:             }
  294:         }
  295:     }
  296:     if (defined($lonhost)) {
  297:         my $cachetime = 12*3600;
  298:         if (!$ignore_cache) {
  299:             my ($loncaparev,$cached)=&is_cached_new('serverloncaparev',$lonhost);
  300:             if (defined($cached)) {
  301:                 return $loncaparev;
  302:             }
  303:         }
  304:         my ($answer,$loncaparev);
  305:         my @ids=&current_machine_ids();
  306:         if (grep(/^\Q$lonhost\E$/,@ids)) {
  307:             $answer = $perlvar{'lonVersion'};
  308:             if ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
  309:                 $loncaparev = $1;
  310:             }
  311:         } else {
  312:             $answer = &reply('serverloncaparev',$lonhost);
  313:             if (($answer eq 'unknown_cmd') || ($answer eq 'con_lost')) {
  314:                 if ($caller eq 'loncron') {
  315:                     my $hostname = &hostname($lonhost);
  316:                     my $protocol = $protocol{$lonhost};
  317:                     $protocol = 'http' if ($protocol ne 'https');
  318:                     my $url = $protocol.'://'.$hostname.'/adm/about.html';
  319:                     my $request=new HTTP::Request('GET',$url);
  320:                     my $response=&LONCAPA::LWPReq::makerequest($lonhost,$request,'',\%perlvar,4,1);
  321:                     unless ($response->is_error()) {
  322:                         my $content = $response->content;
  323:                         if ($content =~ /<p>VERSION\:\s*([\w.\-]+)<\/p>/) {
  324:                             $loncaparev = $1;
  325:                         }
  326:                     }
  327:                 } else {
  328:                     $loncaparev = $loncaparevs{$lonhost};
  329:                 }
  330:             } elsif ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
  331:                 $loncaparev = $1;
  332:             }
  333:         }
  334:         return &do_cache_new('serverloncaparev',$lonhost,$loncaparev,$cachetime);
  335:     }
  336: }
  337: 
  338: sub get_server_homeID {
  339:     my ($hostname,$ignore_cache,$caller) = @_;
  340:     unless ($ignore_cache) {
  341:         my ($serverhomeID,$cached)=&is_cached_new('serverhomeID',$hostname);
  342:         if (defined($cached)) {
  343:             return $serverhomeID;
  344:         }
  345:     }
  346:     my $cachetime = 12*3600;
  347:     my $serverhomeID;
  348:     if ($caller eq 'loncron') { 
  349:         my @machine_ids = &machine_ids($hostname);
  350:         foreach my $id (@machine_ids) {
  351:             my $response = &reply('serverhomeID',$id);
  352:             unless (($response eq 'unknown_cmd') || ($response eq 'con_lost')) {
  353:                 $serverhomeID = $response;
  354:                 last;
  355:             }
  356:         }
  357:         if ($serverhomeID eq '') {
  358:             $serverhomeID = $machine_ids[-1];
  359:         }
  360:     } else {
  361:         $serverhomeID = $serverhomeIDs{$hostname};
  362:     }
  363:     return &do_cache_new('serverhomeID',$hostname,$serverhomeID,$cachetime);
  364: }
  365: 
  366: sub get_remote_globals {
  367:     my ($lonhost,$whathash,$ignore_cache) = @_;
  368:     my ($result,%returnhash,%whatneeded);
  369:     if (ref($whathash) eq 'HASH') {
  370:         foreach my $what (sort(keys(%{$whathash}))) {
  371:             my $hashid = $lonhost.'-'.$what;
  372:             my ($response,$cached);
  373:             unless ($ignore_cache) {
  374:                 ($response,$cached)=&is_cached_new('lonnetglobal',$hashid);
  375:             }
  376:             if (defined($cached)) {
  377:                 $returnhash{$what} = $response;
  378:             } else {
  379:                 $whatneeded{$what} = 1;
  380:             }
  381:         }
  382:         if (keys(%whatneeded) == 0) {
  383:             $result = 'ok';
  384:         } else {
  385:             my $requested = &freeze_escape(\%whatneeded);
  386:             my $rep=&reply('readlonnetglobal:'.$requested,$lonhost);
  387:             if (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
  388:                 ($rep eq 'unknown_cmd')) {
  389:                 $result = $rep;
  390:             } else {
  391:                 $result = 'ok';
  392:                 my @pairs=split(/\&/,$rep);
  393:                 foreach my $item (@pairs) {
  394:                     my ($key,$value)=split(/=/,$item,2);
  395:                     my $what = &unescape($key);
  396:                     my $hashid = $lonhost.'-'.$what;
  397:                     $returnhash{$what}=&thaw_unescape($value);
  398:                     &do_cache_new('lonnetglobal',$hashid,$returnhash{$what},600);
  399:                 }
  400:             }
  401:         }
  402:     }
  403:     return ($result,\%returnhash);
  404: }
  405: 
  406: sub remote_devalidate_cache {
  407:     my ($lonhost,$cachekeys) = @_;
  408:     my $items;
  409:     return unless (ref($cachekeys) eq 'ARRAY');
  410:     my $cachestr = join('&',@{$cachekeys});
  411:     my $response = &reply('devalidatecache:'.&escape($cachestr),$lonhost);
  412:     return $response;
  413: }
  414: 
  415: # -------------------------------------------------- Non-critical communication
  416: sub subreply {
  417:     my ($cmd,$server)=@_;
  418:     my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
  419:     #
  420:     #  With loncnew process trimming, there's a timing hole between lonc server
  421:     #  process exit and the master server picking up the listen on the AF_UNIX
  422:     #  socket.  In that time interval, a lock file will exist:
  423: 
  424:     my $lockfile=$peerfile.".lock";
  425:     while (-e $lockfile) {	# Need to wait for the lockfile to disappear.
  426: 	sleep(0.1);
  427:     }
  428:     # At this point, either a loncnew parent is listening or an old lonc
  429:     # or loncnew child is listening so we can connect or everything's dead.
  430:     #
  431:     #   We'll give the connection a few tries before abandoning it.  If
  432:     #   connection is not possible, we'll con_lost back to the client.
  433:     #   
  434:     my $client;
  435:     for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
  436: 	$client=IO::Socket::UNIX->new(Peer    =>"$peerfile",
  437: 				      Type    => SOCK_STREAM,
  438: 				      Timeout => 10);
  439: 	if ($client) {
  440: 	    last;		# Connected!
  441: 	} else {
  442: 	    &create_connection(&hostname($server),$server);
  443: 	}
  444:         sleep(0.1);	# Try again later if failed connection.
  445:     }
  446:     my $answer;
  447:     if ($client) {
  448: 	print $client "sethost:$server:$cmd\n";
  449: 	$answer=<$client>;
  450: 	if (!$answer) { $answer="con_lost"; }
  451: 	chomp($answer);
  452:     } else {
  453: 	$answer = 'con_lost';	# Failed connection.
  454:     }
  455:     return $answer;
  456: }
  457: 
  458: sub reply {
  459:     my ($cmd,$server)=@_;
  460:     unless (defined(&hostname($server))) { return 'no_such_host'; }
  461:     my $answer=subreply($cmd,$server);
  462:     if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
  463:         my $logged = $cmd;
  464:         if ($cmd =~ /^encrypt:([^:]+):/) {
  465:             my $subcmd = $1;
  466:             if (($subcmd eq 'auth') || ($subcmd eq 'passwd') ||
  467:                 ($subcmd eq 'changeuserauth') || ($subcmd eq 'makeuser') ||
  468:                 ($subcmd eq 'putdom') || ($subcmd eq 'autoexportgrades')) {
  469:                 (undef,undef,my @rest) = split(/:/,$cmd);
  470:                 if (($subcmd eq 'auth') || ($subcmd eq 'putdom')) {
  471:                     splice(@rest,2,1,'Hidden');
  472:                 } elsif ($subcmd eq 'passwd') {
  473:                     splice(@rest,2,2,('Hidden','Hidden'));
  474:                 } elsif (($subcmd eq 'changeuserauth') || ($subcmd eq 'makeuser') ||
  475:                          ($subcmd eq 'autoexportgrades')) {
  476:                     splice(@rest,3,1,'Hidden');
  477:                 }
  478:                 $logged = join(':',('encrypt:'.$subcmd,@rest));
  479:             }
  480:         }
  481:         &logthis("<font color=\"blue\">WARNING:".
  482:                  " $logged to $server returned $answer</font>");
  483:     }
  484:     return $answer;
  485: }
  486: 
  487: # ----------------------------------------------------------- Send USR1 to lonc
  488: 
  489: sub reconlonc {
  490:     my ($lonid) = @_;
  491:     if ($lonid) {
  492:         my $hostname = &hostname($lonid);
  493: 	my $peerfile="$perlvar{'lonSockDir'}/$hostname";
  494: 	if ($hostname && -e $peerfile) {
  495: 	    &logthis("Trying to reconnect lonc for $lonid ($hostname)");
  496: 	    my $client=IO::Socket::UNIX->new(Peer    => $peerfile,
  497: 					     Type    => SOCK_STREAM,
  498: 					     Timeout => 10);
  499: 	    if ($client) {
  500: 		print $client ("reset_retries\n");
  501: 		my $answer=<$client>;
  502: 		#reset just this one.
  503: 	    }
  504: 	}
  505: 	return;
  506:     }
  507: 
  508:     &logthis("Trying to reconnect lonc");
  509:     my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
  510:     if (open(my $fh,"<",$loncfile)) {
  511: 	my $loncpid=<$fh>;
  512:         chomp($loncpid);
  513:         if (kill 0 => $loncpid) {
  514: 	    &logthis("lonc at pid $loncpid responding, sending USR1");
  515:             kill USR1 => $loncpid;
  516:             sleep 1;
  517:         } else {
  518: 	    &logthis(
  519:                "<font color=\"blue\">WARNING:".
  520:                " lonc at pid $loncpid not responding, giving up</font>");
  521:         }
  522:     } else {
  523: 	&logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
  524:     }
  525: }
  526: 
  527: # ------------------------------------------------------ Critical communication
  528: 
  529: sub critical {
  530:     my ($cmd,$server)=@_;
  531:     unless (&hostname($server)) {
  532:         &logthis("<font color=\"blue\">WARNING:".
  533:                " Critical message to unknown server ($server)</font>");
  534:         return 'no_such_host';
  535:     }
  536:     my $answer=reply($cmd,$server);
  537:     if ($answer eq 'con_lost') {
  538: 	&reconlonc($server);
  539: 	my $answer=reply($cmd,$server);
  540:         if ($answer eq 'con_lost') {
  541:             my $now=time;
  542:             my $middlename=$cmd;
  543:             $middlename=substr($middlename,0,16);
  544:             $middlename=~s/\W//g;
  545:             my $dfilename=
  546:       "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
  547:             $dumpcount++;
  548:             {
  549: 		my $dfh;
  550: 		if (open($dfh,">",$dfilename)) {
  551: 		    print $dfh "$cmd\n"; 
  552: 		    close($dfh);
  553: 		}
  554:             }
  555:             sleep 1;
  556:             my $wcmd='';
  557:             {
  558: 		my $dfh;
  559: 		if (open($dfh,"<",$dfilename)) {
  560: 		    $wcmd=<$dfh>; 
  561: 		    close($dfh);
  562: 		}
  563:             }
  564:             chomp($wcmd);
  565:             if ($wcmd eq $cmd) {
  566: 		&logthis("<font color=\"blue\">WARNING: ".
  567:                          "Connection buffer $dfilename: $cmd</font>");
  568:                 &logperm("D:$server:$cmd");
  569: 	        return 'con_delayed';
  570:             } else {
  571:                 &logthis("<font color=\"red\">CRITICAL:"
  572:                         ." Critical connection failed: $server $cmd</font>");
  573:                 &logperm("F:$server:$cmd");
  574:                 return 'con_failed';
  575:             }
  576:         }
  577:     }
  578:     return $answer;
  579: }
  580: 
  581: # ------------------------------------------- check if return value is an error
  582: 
  583: sub error {
  584:     my ($result) = @_;
  585:     if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
  586: 	if ($2 == 2) { return undef; }
  587: 	return $1;
  588:     }
  589:     return undef;
  590: }
  591: 
  592: sub convert_and_load_session_env {
  593:     my ($lonidsdir,$handle)=@_;
  594:     my @profile;
  595:     {
  596: 	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
  597: 	if (!$opened) {
  598: 	    return 0;
  599: 	}
  600: 	flock($idf,LOCK_SH);
  601: 	@profile=<$idf>;
  602: 	close($idf);
  603:     }
  604:     my %temp_env;
  605:     foreach my $line (@profile) {
  606: 	if ($line !~ m/=/) {
  607: 	    return 0;
  608: 	}
  609: 	chomp($line);
  610: 	my ($envname,$envvalue)=split(/=/,$line,2);
  611: 	$temp_env{&unescape($envname)} = &unescape($envvalue);
  612:     }
  613:     unlink("$lonidsdir/$handle.id");
  614:     if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
  615: 	    0640)) {
  616: 	%disk_env = %temp_env;
  617: 	@env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
  618: 	untie(%disk_env);
  619:     }
  620:     return 1;
  621: }
  622: 
  623: # ------------------------------------------- Transfer profile into environment
  624: my $env_loaded;
  625: sub transfer_profile_to_env {
  626:     my ($lonidsdir,$handle,$force_transfer) = @_;
  627:     if (!$force_transfer && $env_loaded) { return; } 
  628: 
  629:     if (!defined($lonidsdir)) {
  630: 	$lonidsdir = $perlvar{'lonIDsDir'};
  631:     }
  632:     if (!defined($handle)) {
  633:         ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
  634:     }
  635: 
  636:     my $convert;
  637:     {
  638:     	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
  639: 	if (!$opened) {
  640: 	    return;
  641: 	}
  642: 	flock($idf,LOCK_SH);
  643: 	if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
  644: 		&GDBM_READER(),0640)) {
  645: 	    @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
  646: 	    untie(%disk_env);
  647: 	} else {
  648: 	    $convert = 1;
  649: 	}
  650:     }
  651:     if ($convert) {
  652: 	if (!&convert_and_load_session_env($lonidsdir,$handle)) {
  653: 	    &logthis("Failed to load session, or convert session.");
  654: 	}
  655:     }
  656: 
  657:     my %remove;
  658:     while ( my $envname = each(%env) ) {
  659:         if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
  660:             if ($time < time-300) {
  661:                 $remove{$key}++;
  662:             }
  663:         }
  664:     }
  665: 
  666:     $env{'user.environment'} = "$lonidsdir/$handle.id";
  667:     $env_loaded=1;
  668:     foreach my $expired_key (keys(%remove)) {
  669:         &delenv($expired_key);
  670:     }
  671: }
  672: 
  673: # ---------------------------------------------------- Check for valid session 
  674: sub check_for_valid_session {
  675:     my ($r,$name,$userhashref,$domref) = @_;
  676:     my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
  677:     my ($lonidsdir,$linkname,$pubname,$secure,$lonid);
  678:     if ($name eq 'lonDAV') {
  679:         $lonidsdir=$r->dir_config('lonDAVsessDir');
  680:     } else {
  681:         $lonidsdir=$r->dir_config('lonIDsDir');
  682:         if ($name eq '') {
  683:             $name = 'lonID';
  684:         }
  685:     }
  686:     if ($name eq 'lonID') {
  687:         $secure = 'lonSID';
  688:         $linkname = 'lonLinkID';
  689:         $pubname = 'lonPubID';
  690:         if (exists($cookies{$secure})) {
  691:             $lonid=$cookies{$secure};
  692:         } elsif (exists($cookies{$name})) {
  693:             $lonid=$cookies{$name};
  694:         } elsif ((exists($cookies{$linkname})) && ($ENV{'SERVER_PORT'} != 443)) {
  695:             $lonid=$cookies{$linkname};
  696:         } elsif (exists($cookies{$pubname})) {
  697:             $lonid=$cookies{$pubname};
  698:         }
  699:     } else {
  700:         $lonid=$cookies{$name};
  701:     }
  702:     return undef if (!$lonid);
  703: 
  704:     my $handle=&LONCAPA::clean_handle($lonid->value);
  705:     if (-l "$lonidsdir/$handle.id") {
  706:         my $link = readlink("$lonidsdir/$handle.id");
  707:         if ((-e $link) && ($link =~ m{^\Q$lonidsdir\E/(.+)\.id$})) {
  708:             $handle = $1;
  709:         }
  710:     }
  711:     if (!-e "$lonidsdir/$handle.id") {
  712:         if ((ref($domref)) && ($name eq 'lonID') && 
  713:             ($handle =~ /^($match_username)\_\d+\_($match_domain)\_(.+)$/)) {
  714:             my ($possuname,$possudom,$possuhome) = ($1,$2,$3);
  715:             if ((&domain($possudom) ne '') && (&homeserver($possuname,$possudom) eq $possuhome)) {
  716:                 $$domref = $possudom;
  717:             }
  718:         }
  719:         return undef;
  720:     }
  721: 
  722:     my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
  723:     return undef if (!$opened);
  724: 
  725:     flock($idf,LOCK_SH);
  726:     my %disk_env;
  727:     if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
  728: 	    &GDBM_READER(),0640)) {
  729: 	return undef;	
  730:     }
  731: 
  732:     if (!defined($disk_env{'user.name'})
  733: 	|| !defined($disk_env{'user.domain'})) {
  734:         untie(%disk_env);
  735: 	return undef;
  736:     }
  737: 
  738:     if (ref($userhashref) eq 'HASH') {
  739:         $userhashref->{'name'} = $disk_env{'user.name'};
  740:         $userhashref->{'domain'} = $disk_env{'user.domain'};
  741:         $userhashref->{'lti'} = $disk_env{'request.lti.login'};
  742:         if ($userhashref->{'lti'}) {
  743:             $userhashref->{'ltitarget'} = $disk_env{'request.lti.target'};
  744:             $userhashref->{'ltiuri'} = $disk_env{'request.lti.uri'};
  745:         }
  746:     }
  747:     untie(%disk_env);
  748: 
  749:     return $handle;
  750: }
  751: 
  752: sub timed_flock {
  753:     my ($file,$lock_type) = @_;
  754:     my $failed=0;
  755:     eval {
  756: 	local $SIG{__DIE__}='DEFAULT';
  757: 	local $SIG{ALRM}=sub {
  758: 	    $failed=1;
  759: 	    die("failed lock");
  760: 	};
  761: 	alarm(13);
  762: 	flock($file,$lock_type);
  763: 	alarm(0);
  764:     };
  765:     if ($failed) {
  766: 	return undef;
  767:     } else {
  768: 	return 1;
  769:     }
  770: }
  771: 
  772: sub get_sessionfile_vars {
  773:     my ($handle,$lonidsdir,$storearr) = @_;
  774:     my %returnhash;
  775:     unless (ref($storearr) eq 'ARRAY') {
  776:         return %returnhash;
  777:     }
  778:     if (-l "$lonidsdir/$handle.id") {
  779:         my $link = readlink("$lonidsdir/$handle.id");
  780:         if ((-e $link) && ($link =~ m{^\Q$lonidsdir\E/(.+)\.id$})) {
  781:             $handle = $1;
  782:         }
  783:     }
  784:     if ((-e "$lonidsdir/$handle.id") &&
  785:         ($handle =~ /^($match_username)\_\d+\_($match_domain)\_(.+)$/)) {
  786:         my ($possuname,$possudom,$possuhome) = ($1,$2,$3);
  787:         if ((&domain($possudom) ne '') && (&homeserver($possuname,$possudom) eq $possuhome)) {
  788:             if (open(my $idf,'+<',"$lonidsdir/$handle.id")) {
  789:                 flock($idf,LOCK_SH);
  790:                 if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
  791:                         &GDBM_READER(),0640)) {
  792:                     foreach my $item (@{$storearr}) {
  793:                         $returnhash{$item} = $disk_env{$item};
  794:                     }
  795:                     untie(%disk_env);
  796:                 }
  797:             }
  798:         }
  799:     }
  800:     return %returnhash;
  801: }
  802: 
  803: # ---------------------------------------------------------- Append Environment
  804: 
  805: sub appenv {
  806:     my ($newenv,$roles) = @_;
  807:     if (ref($newenv) eq 'HASH') {
  808:         foreach my $key (keys(%{$newenv})) {
  809:             my $refused = 0;
  810: 	    if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
  811:                 $refused = 1;
  812:                 if (ref($roles) eq 'ARRAY') {
  813:                     my ($type,$role) = ($key =~ m{^user\.(role|priv)\.(.+?)\./});
  814:                     if (grep(/^\Q$role\E$/,@{$roles})) {
  815:                         $refused = 0;
  816:                     }
  817:                 }
  818:             }
  819:             if ($refused) {
  820:                 &logthis("<font color=\"blue\">WARNING: ".
  821:                          "Attempt to modify environment ".$key." to ".$newenv->{$key}
  822:                          .'</font>');
  823: 	        delete($newenv->{$key});
  824:             } else {
  825:                 $env{$key}=$newenv->{$key};
  826:             }
  827:         }
  828:         my $lonids = $perlvar{'lonIDsDir'};
  829:         if ($env{'user.environment'} =~ m{^\Q$lonids/\E$match_username\_\d+\_$match_domain\_[\w\-.]+\.id$}) {
  830:             my $opened = open(my $env_file,'+<',$env{'user.environment'});
  831:             if ($opened
  832: 	        && &timed_flock($env_file,LOCK_EX)
  833: 	        &&
  834: 	        tie(my %disk_env,'GDBM_File',$env{'user.environment'},
  835: 	            (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
  836: 	        while (my ($key,$value) = each(%{$newenv})) {
  837: 	            $disk_env{$key} = $value;
  838: 	        }
  839: 	        untie(%disk_env);
  840:             }
  841:         }
  842:     }
  843:     return 'ok';
  844: }
  845: # ----------------------------------------------------- Delete from Environment
  846: 
  847: sub delenv {
  848:     my ($delthis,$regexp,$roles) = @_;
  849:     if (($delthis=~/^user\.role/) || ($delthis=~/^user\.priv/)) {
  850:         my $refused = 1;
  851:         if (ref($roles) eq 'ARRAY') {
  852:             my ($type,$role) = ($delthis =~ /^user\.(role|priv)\.([^.]+)\./);
  853:             if (grep(/^\Q$role\E$/,@{$roles})) {
  854:                 $refused = 0;
  855:             }
  856:         }
  857:         if ($refused) {
  858:             &logthis("<font color=\"blue\">WARNING: ".
  859:                      "Attempt to delete from environment ".$delthis);
  860:             return 'error';
  861:         }
  862:     }
  863:     my $opened = open(my $env_file,'+<',$env{'user.environment'});
  864:     if ($opened
  865: 	&& &timed_flock($env_file,LOCK_EX)
  866: 	&&
  867: 	tie(my %disk_env,'GDBM_File',$env{'user.environment'},
  868: 	    (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
  869: 	foreach my $key (keys(%disk_env)) {
  870: 	    if ($regexp) {
  871:                 if ($key=~/^$delthis/) {
  872:                     delete($env{$key});
  873:                     delete($disk_env{$key});
  874:                 } 
  875:             } else {
  876:                 if ($key=~/^\Q$delthis\E/) {
  877: 		    delete($env{$key});
  878: 		    delete($disk_env{$key});
  879: 	        }
  880:             }
  881: 	}
  882: 	untie(%disk_env);
  883:     }
  884:     return 'ok';
  885: }
  886: 
  887: sub get_env_multiple {
  888:     my ($name) = @_;
  889:     my @values;
  890:     if (defined($env{$name})) {
  891:         # exists is it an array
  892:         if (ref($env{$name})) {
  893:             @values=@{ $env{$name} };
  894:         } else {
  895:             $values[0]=$env{$name};
  896:         }
  897:     }
  898:     return(@values);
  899: }
  900: 
  901: # ------------------------------------------------------------------- Locking
  902: 
  903: sub set_lock {
  904:     my ($text)=@_;
  905:     $locknum++;
  906:     my $id=$$.'-'.$locknum;
  907:     &appenv({'session.locks' => $env{'session.locks'}.','.$id,
  908:              'session.lock.'.$id => $text});
  909:     return $id;
  910: }
  911: 
  912: sub get_locks {
  913:     my $num=0;
  914:     my %texts=();
  915:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
  916:        if ($lock=~/\w/) {
  917:           $num++;
  918:           $texts{$lock}=$env{'session.lock.'.$lock};
  919:        }
  920:    }
  921:    return ($num,%texts);
  922: }
  923: 
  924: sub remove_lock {
  925:     my ($id)=@_;
  926:     my $newlocks='';
  927:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
  928:        if (($lock=~/\w/) && ($lock ne $id)) {
  929:           $newlocks.=','.$lock;
  930:        }
  931:     }
  932:     &appenv({'session.locks' => $newlocks});
  933:     &delenv('session.lock.'.$id);
  934: }
  935: 
  936: sub remove_all_locks {
  937:     my $activelocks=$env{'session.locks'};
  938:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
  939:        if ($lock=~/\w/) {
  940:           &remove_lock($lock);
  941:        }
  942:     }
  943: }
  944: 
  945: 
  946: # ------------------------------------------ Find out current server userload
  947: sub userload {
  948:     my $numusers=0;
  949:     {
  950: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
  951: 	my $filename;
  952: 	my $curtime=time;
  953: 	while ($filename=readdir(LONIDS)) {
  954: 	    next if ($filename eq '.' || $filename eq '..');
  955: 	    next if ($filename =~ /publicuser_\d+\.id/);
  956:             next if ($filename =~ /^[a-f0-9]+_linked\.id$/);
  957: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
  958: 	    if ($curtime-$mtime < 1800) { $numusers++; }
  959: 	}
  960: 	closedir(LONIDS);
  961:     }
  962:     my $userloadpercent=0;
  963:     my $maxuserload=$perlvar{'lonUserLoadLim'};
  964:     if ($maxuserload) {
  965: 	$userloadpercent=100*$numusers/$maxuserload;
  966:     }
  967:     $userloadpercent=sprintf("%.2f",$userloadpercent);
  968:     return $userloadpercent;
  969: }
  970: 
  971: # ------------------------------ Find server with least workload from spare.tab
  972: 
  973: sub spareserver {
  974:     my ($loadpercent,$userloadpercent,$want_server_name,$udom) = @_;
  975:     my $spare_server;
  976:     if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
  977:     my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent 
  978:                                                      :  $userloadpercent;
  979:     my ($uint_dom,$remotesessions);
  980:     if (($udom ne '') && (&domain($udom) ne '')) {
  981:         my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
  982:         $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
  983:         my %udomdefaults = &Apache::lonnet::get_domain_defaults($udom);
  984:         $remotesessions = $udomdefaults{'remotesessions'};
  985:     }
  986:     my $spareshash = &this_host_spares($udom);
  987:     if (ref($spareshash) eq 'HASH') {
  988:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
  989:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
  990:                 next unless (&spare_can_host($udom,$uint_dom,$remotesessions,
  991:                                              $try_server));
  992: 	        ($spare_server, $lowest_load) =
  993: 	            &compare_server_load($try_server, $spare_server, $lowest_load);
  994:             }
  995:         }
  996: 
  997:         my $found_server = ($spare_server ne '' && $lowest_load < 100);
  998: 
  999:         if (!$found_server) {
 1000:             if (ref($spareshash->{'default'}) eq 'ARRAY') { 
 1001: 	        foreach my $try_server (@{ $spareshash->{'default'} }) {
 1002:                     next unless (&spare_can_host($udom,$uint_dom,
 1003:                                                  $remotesessions,$try_server));
 1004: 	            ($spare_server, $lowest_load) =
 1005: 		        &compare_server_load($try_server, $spare_server, $lowest_load);
 1006:                 }
 1007: 	    }
 1008:         }
 1009:     }
 1010: 
 1011:     if (!$want_server_name) {
 1012:         if (defined($spare_server)) {
 1013:             my $hostname = &hostname($spare_server);
 1014:             if (defined($hostname)) {
 1015:                 my $protocol = 'http';
 1016:                 if ($protocol{$spare_server} eq 'https') {
 1017:                     $protocol = $protocol{$spare_server};
 1018:                 }
 1019: 	        $spare_server = $protocol.'://'.$hostname;
 1020:             }
 1021:         }
 1022:     }
 1023:     return $spare_server;
 1024: }
 1025: 
 1026: sub compare_server_load {
 1027:     my ($try_server, $spare_server, $lowest_load, $required) = @_;
 1028: 
 1029:     if ($required) {
 1030:         my ($reqdmajor,$reqdminor) = ($required =~ /^(\d+)\.(\d+)$/);
 1031:         my $remoterev = &get_server_loncaparev(undef,$try_server);
 1032:         my ($major,$minor) = ($remoterev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
 1033:         if (($major eq '' && $minor eq '') ||
 1034:             (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)))) {
 1035:             return ($spare_server,$lowest_load);
 1036:         }
 1037:     }
 1038: 
 1039:     my $loadans     = &reply('load',    $try_server);
 1040:     my $userloadans = &reply('userload',$try_server);
 1041: 
 1042:     if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
 1043: 	return ($spare_server, $lowest_load); #didn't get a number from the server
 1044:     }
 1045: 
 1046:     my $load;
 1047:     if ($loadans =~ /\d/) {
 1048: 	if ($userloadans =~ /\d/) {
 1049: 	    #both are numbers, pick the bigger one
 1050: 	    $load = ($loadans > $userloadans) ? $loadans 
 1051: 		                              : $userloadans;
 1052: 	} else {
 1053: 	    $load = $loadans;
 1054: 	}
 1055:     } else {
 1056: 	$load = $userloadans;
 1057:     }
 1058: 
 1059:     if (($load =~ /\d/) && ($load < $lowest_load)) {
 1060: 	$spare_server = $try_server;
 1061: 	$lowest_load  = $load;
 1062:     }
 1063:     return ($spare_server,$lowest_load);
 1064: }
 1065: 
 1066: # --------------------------- ask offload servers if user already has a session
 1067: sub find_existing_session {
 1068:     my ($udom,$uname) = @_;
 1069:     my $spareshash = &this_host_spares($udom);
 1070:     if (ref($spareshash) eq 'HASH') {
 1071:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
 1072:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
 1073:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
 1074:             }
 1075:         }
 1076:         if (ref($spareshash->{'default'}) eq 'ARRAY') {
 1077:             foreach my $try_server (@{ $spareshash->{'default'} }) {
 1078:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
 1079:             }
 1080:         }
 1081:     }
 1082:     return;
 1083: }
 1084: 
 1085: sub delusersession {
 1086:     my ($lonid,$udom,$uname) = @_;
 1087:     my $uprimary_id = &domain($udom,'primary');
 1088:     my $uintdom = &internet_dom($uprimary_id);
 1089:     my $intdom = &internet_dom($lonid);
 1090:     my $serverhomedom = &host_domain($lonid);
 1091:     if (($uintdom ne '') && ($uintdom eq $intdom)) {
 1092:         return &reply(join(':','delusersession',
 1093:                             map {&escape($_)} ($udom,$uname)),$lonid);
 1094:     }
 1095:     return;
 1096: }
 1097: 
 1098: # check if user's browser sent load balancer cookie and server still has session
 1099: # and is not overloaded.
 1100: sub check_for_balancer_cookie {
 1101:     my ($r,$update_mtime) = @_;
 1102:     my ($otherserver,$cookie);
 1103:     my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
 1104:     if (exists($cookies{'balanceID'})) {
 1105:         my $balid = $cookies{'balanceID'};
 1106:         $cookie=&LONCAPA::clean_handle($balid->value);
 1107:         my $balancedir=$r->dir_config('lonBalanceDir');
 1108:         if ((-d $balancedir) && (-e "$balancedir/$cookie.id")) {
 1109:             if ($cookie =~ /^($match_domain)_($match_username)_[a-f0-9]+$/) {
 1110:                 my ($possudom,$possuname) = ($1,$2);
 1111:                 my $has_session = 0;
 1112:                 if ((&domain($possudom) ne '') &&
 1113:                     (&homeserver($possuname,$possudom) ne 'no_host')) {
 1114:                     my $try_server;
 1115:                     my $opened = open(my $idf,'+<',"$balancedir/$cookie.id");
 1116:                     if ($opened) {
 1117:                         flock($idf,LOCK_SH);
 1118:                         while (my $line = <$idf>) {
 1119:                             chomp($line);
 1120:                             if (&hostname($line) ne '') {
 1121:                                 $try_server = $line;
 1122:                                 last;
 1123:                             }
 1124:                         }
 1125:                         close($idf);
 1126:                         if (($try_server) &&
 1127:                             (&has_user_session($try_server,$possudom,$possuname))) {
 1128:                             my $lowest_load = 30000;
 1129:                             ($otherserver,$lowest_load) =
 1130:                                 &compare_server_load($try_server,undef,$lowest_load);
 1131:                             if ($otherserver ne '' && $lowest_load < 100) {
 1132:                                 $has_session = 1;
 1133:                             } else {
 1134:                                 undef($otherserver);
 1135:                             }
 1136:                         }
 1137:                     }
 1138:                 }
 1139:                 if ($has_session) {
 1140:                     if ($update_mtime) {
 1141:                         my $atime = my $mtime = time;
 1142:                         utime($atime,$mtime,"$balancedir/$cookie.id");
 1143:                     }
 1144:                 } else {
 1145:                     unlink("$balancedir/$cookie.id");
 1146:                 }
 1147:             }
 1148:         }
 1149:     }
 1150:     return ($otherserver,$cookie);
 1151: }
 1152: 
 1153: sub delbalcookie {
 1154:     my ($cookie,$balancer) =@_;
 1155:     if ($cookie =~ /^($match_domain)\_($match_username)\_[a-f0-9]{32}$/) {
 1156:         my ($udom,$uname) = ($1,$2);
 1157:         my $uprimary_id = &domain($udom,'primary');
 1158:         my $uintdom = &internet_dom($uprimary_id);
 1159:         my $intdom = &internet_dom($balancer);
 1160:         my $serverhomedom = &host_domain($balancer);
 1161:         if (($uintdom ne '') && ($uintdom eq $intdom)) {
 1162:             return &reply("delbalcookie:$cookie",$balancer);
 1163:         }
 1164:     }
 1165: }
 1166: 
 1167: # -------------------------------- ask if server already has a session for user
 1168: sub has_user_session {
 1169:     my ($lonid,$udom,$uname) = @_;
 1170:     my $result = &reply(join(':','userhassession',
 1171: 			     map {&escape($_)} ($udom,$uname)),$lonid);
 1172:     return 1 if ($result eq 'ok');
 1173: 
 1174:     return 0;
 1175: }
 1176: 
 1177: # --------- determine least loaded server in a user's domain which allows login
 1178: 
 1179: sub choose_server {
 1180:     my ($udom,$checkloginvia,$required,$skiploadbal) = @_;
 1181:     my %domconfhash = &Apache::loncommon::get_domainconf($udom);
 1182:     my %servers = &get_servers($udom);
 1183:     my $lowest_load = 30000;
 1184:     my ($login_host,$hostname,$portal_path,$isredirect,$balancers);
 1185:     if ($skiploadbal) {
 1186:         ($balancers,my $cached)=&is_cached_new('loadbalancing',$udom);
 1187:         unless (defined($cached)) {
 1188:             my $cachetime = 60*60*24;
 1189:             my %domconfig =
 1190:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
 1191:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
 1192:                 $balancers = &do_cache_new('loadbalancing',$udom,$domconfig{'loadbalancing'},
 1193:                                            $cachetime);
 1194:             }
 1195:         }
 1196:     }
 1197:     foreach my $lonhost (keys(%servers)) {
 1198:         if ($skiploadbal) {
 1199:             if (ref($balancers) eq 'HASH') {
 1200:                 next if (exists($balancers->{$lonhost}));
 1201:             }
 1202:         }
 1203:         my $loginvia;
 1204:         if ($checkloginvia) {
 1205:             $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
 1206:             if ($loginvia) {
 1207:                 my ($server,$path) = split(/:/,$loginvia);
 1208:                 ($login_host, $lowest_load) =
 1209:                     &compare_server_load($server, $login_host, $lowest_load, $required);
 1210:                 if ($login_host eq $server) {
 1211:                     $portal_path = $path;
 1212:                     $isredirect = 1;
 1213:                 }
 1214:             } else {
 1215:                 ($login_host, $lowest_load) =
 1216:                     &compare_server_load($lonhost, $login_host, $lowest_load, $required);
 1217:                 if ($login_host eq $lonhost) {
 1218:                     $portal_path = '';
 1219:                     $isredirect = ''; 
 1220:                 }
 1221:             }
 1222:         } else {
 1223:             ($login_host, $lowest_load) =
 1224:                 &compare_server_load($lonhost, $login_host, $lowest_load, $required);
 1225:         }
 1226:     }
 1227:     if ($login_host ne '') {
 1228:         $hostname = &hostname($login_host);
 1229:     }
 1230:     return ($login_host,$hostname,$portal_path,$isredirect,$lowest_load);
 1231: }
 1232: 
 1233: # --------------------------------------------- Try to change a user's password
 1234: 
 1235: sub changepass {
 1236:     my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
 1237:     $currentpass = &escape($currentpass);
 1238:     $newpass     = &escape($newpass);
 1239:     my $lonhost = $perlvar{'lonHostID'};
 1240:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
 1241: 		       $server);
 1242:     if (! $answer) {
 1243: 	&logthis("No reply on password change request to $server ".
 1244: 		 "by $uname in domain $udom.");
 1245:     } elsif ($answer =~ "^ok") {
 1246:         &logthis("$uname in $udom successfully changed their password ".
 1247: 		 "on $server.");
 1248:     } elsif ($answer =~ "^pwchange_failure") {
 1249: 	&logthis("$uname in $udom was unable to change their password ".
 1250: 		 "on $server.  The action was blocked by either lcpasswd ".
 1251: 		 "or pwchange");
 1252:     } elsif ($answer =~ "^non_authorized") {
 1253:         &logthis("$uname in $udom did not get their password correct when ".
 1254: 		 "attempting to change it on $server.");
 1255:     } elsif ($answer =~ "^auth_mode_error") {
 1256:         &logthis("$uname in $udom attempted to change their password despite ".
 1257: 		 "not being locally or internally authenticated on $server.");
 1258:     } elsif ($answer =~ "^unknown_user") {
 1259:         &logthis("$uname in $udom attempted to change their password ".
 1260: 		 "on $server but were unable to because $server is not ".
 1261: 		 "their home server.");
 1262:     } elsif ($answer =~ "^refused") {
 1263: 	&logthis("$server refused to change $uname in $udom password because ".
 1264: 		 "it was sent an unencrypted request to change the password.");
 1265:     } elsif ($answer =~ "invalid_client") {
 1266:         &logthis("$server refused to change $uname in $udom password because ".
 1267:                  "it was a reset by e-mail originating from an invalid server.");
 1268:     } elsif ($answer =~ "^prioruse") {
 1269:        &logthis("$server refused to change $uname in $udom password because ".
 1270:                 "the password had been used before");
 1271:     }
 1272:     return $answer;
 1273: }
 1274: 
 1275: # ----------------------- Try to determine user's current authentication scheme
 1276: 
 1277: sub queryauthenticate {
 1278:     my ($uname,$udom)=@_;
 1279:     my $uhome=&homeserver($uname,$udom);
 1280:     if (!$uhome) {
 1281: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
 1282: 	return 'no_host';
 1283:     }
 1284:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
 1285:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
 1286: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
 1287:     }
 1288:     return $answer;
 1289: }
 1290: 
 1291: # --------- Try to authenticate user from domain's lib servers (first this one)
 1292: 
 1293: sub authenticate {
 1294:     my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
 1295:     $upass=&escape($upass);
 1296:     $uname= &LONCAPA::clean_username($uname);
 1297:     my $uhome=&homeserver($uname,$udom,1);
 1298:     my $newhome;
 1299:     if ((!$uhome) || ($uhome eq 'no_host')) {
 1300: # Maybe the machine was offline and only re-appeared again recently?
 1301:         &reconlonc();
 1302: # One more
 1303: 	$uhome=&homeserver($uname,$udom,1);
 1304:         if (($uhome eq 'no_host') && $checkdefauth) {
 1305:             if (defined(&domain($udom,'primary'))) {
 1306:                 $newhome=&domain($udom,'primary');
 1307:             }
 1308:             if ($newhome ne '') {
 1309:                 $uhome = $newhome;
 1310:             }
 1311:         }
 1312: 	if ((!$uhome) || ($uhome eq 'no_host')) {
 1313: 	    &logthis("User $uname at $udom is unknown in authenticate");
 1314: 	    return 'no_host';
 1315:         }
 1316:     }
 1317:     my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
 1318:     if ($answer eq 'authorized') {
 1319:         if ($newhome) {
 1320:             &logthis("User $uname at $udom authorized by $uhome, but needs account");
 1321:             return 'no_account_on_host'; 
 1322:         } else {
 1323:             &logthis("User $uname at $udom authorized by $uhome");
 1324:             return $uhome;
 1325:         }
 1326:     }
 1327:     if ($answer eq 'non_authorized') {
 1328: 	&logthis("User $uname at $udom rejected by $uhome");
 1329: 	return 'no_host'; 
 1330:     }
 1331:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
 1332:     return 'no_host';
 1333: }
 1334: 
 1335: sub can_host_session {
 1336:     my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
 1337:     my $canhost = 1;
 1338:     my $host_idn = &Apache::lonnet::internet_dom($lonhost);
 1339:     if (ref($remotesessions) eq 'HASH') {
 1340:         if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
 1341:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
 1342:                 $canhost = 0;
 1343:             } else {
 1344:                 $canhost = 1;
 1345:             }
 1346:         }
 1347:         if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
 1348:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
 1349:                 $canhost = 1;
 1350:             } else {
 1351:                 $canhost = 0;
 1352:             }
 1353:         }
 1354:         if ($canhost) {
 1355:             if ($remotesessions->{'version'} ne '') {
 1356:                 my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
 1357:                 if ($reqmajor ne '' && $reqminor ne '') {
 1358:                     if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
 1359:                         my $major = $1;
 1360:                         my $minor = $2;
 1361:                         if (($major < $reqmajor ) ||
 1362:                             (($major == $reqmajor) && ($minor < $reqminor))) {
 1363:                             $canhost = 0;
 1364:                         }
 1365:                     } else {
 1366:                         $canhost = 0;
 1367:                     }
 1368:                 }
 1369:             }
 1370:         }
 1371:     }
 1372:     if ($canhost) {
 1373:         if (ref($hostedsessions) eq 'HASH') {
 1374:             my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
 1375:             my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
 1376:             if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
 1377:                 if (($uint_dom ne '') && 
 1378:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'excludedomain'}}))) {
 1379:                     $canhost = 0;
 1380:                 } else {
 1381:                     $canhost = 1;
 1382:                 }
 1383:             }
 1384:             if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
 1385:                 if (($uint_dom ne '') && 
 1386:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'includedomain'}}))) {
 1387:                     $canhost = 1;
 1388:                 } else {
 1389:                     $canhost = 0;
 1390:                 }
 1391:             }
 1392:         }
 1393:     }
 1394:     return $canhost;
 1395: }
 1396: 
 1397: sub spare_can_host {
 1398:     my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
 1399:     my $canhost=1;
 1400:     my $try_server_hostname = &hostname($try_server);
 1401:     my $serverhomeID = &get_server_homeID($try_server_hostname);
 1402:     my $serverhomedom = &host_domain($serverhomeID);
 1403:     my %defdomdefaults = &get_domain_defaults($serverhomedom);
 1404:     if (ref($defdomdefaults{'offloadnow'}) eq 'HASH') {
 1405:         if ($defdomdefaults{'offloadnow'}{$try_server}) {
 1406:             $canhost = 0;
 1407:         }
 1408:     }
 1409:     if (($canhost) && ($uint_dom)) {
 1410:         my @intdoms;
 1411:         my $internet_names = &get_internet_names($try_server);
 1412:         if (ref($internet_names) eq 'ARRAY') {
 1413:             @intdoms = @{$internet_names};
 1414:         }
 1415:         unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
 1416:             my $remoterev = &get_server_loncaparev(undef,$try_server);
 1417:             $canhost = &can_host_session($udom,$try_server,$remoterev,
 1418:                                          $remotesessions,
 1419:                                          $defdomdefaults{'hostedsessions'});
 1420:         }
 1421:     }
 1422:     return $canhost;
 1423: }
 1424: 
 1425: sub this_host_spares {
 1426:     my ($dom) = @_;
 1427:     my ($dom_in_use,$lonhost_in_use,$result);
 1428:     my @hosts = &current_machine_ids();
 1429:     foreach my $lonhost (@hosts) {
 1430:         if (&host_domain($lonhost) eq $dom) {
 1431:             $dom_in_use = $dom;
 1432:             $lonhost_in_use = $lonhost;
 1433:             last;
 1434:         }
 1435:     }
 1436:     if ($dom_in_use ne '') {
 1437:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
 1438:     }
 1439:     if (ref($result) ne 'HASH') {
 1440:         $lonhost_in_use = $perlvar{'lonHostID'};
 1441:         $dom_in_use = &host_domain($lonhost_in_use);
 1442:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
 1443:         if (ref($result) ne 'HASH') {
 1444:             $result = \%spareid;
 1445:         }
 1446:     }
 1447:     return $result;
 1448: }
 1449: 
 1450: sub spares_for_offload  {
 1451:     my ($dom_in_use,$lonhost_in_use) = @_;
 1452:     my ($result,$cached)=&is_cached_new('spares',$dom_in_use);
 1453:     if (defined($cached)) {
 1454:         return $result;
 1455:     } else {
 1456:         my $cachetime = 60*60*24;
 1457:         my %domconfig =
 1458:             &Apache::lonnet::get_dom('configuration',['usersessions'],$dom_in_use);
 1459:         if (ref($domconfig{'usersessions'}) eq 'HASH') {
 1460:             if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
 1461:                 if (ref($domconfig{'usersessions'}{'spares'}{$lonhost_in_use}) eq 'HASH') {
 1462:                     return &do_cache_new('spares',$dom_in_use,$domconfig{'usersessions'}{'spares'}{$lonhost_in_use},$cachetime);
 1463:                 }
 1464:             }
 1465:         }
 1466:     }
 1467:     return;
 1468: }
 1469: 
 1470: sub get_lonbalancer_config {
 1471:     my ($servers) = @_;
 1472:     my ($currbalancer,$currtargets);
 1473:     if (ref($servers) eq 'HASH') {
 1474:         foreach my $server (keys(%{$servers})) {
 1475:             my %what = (
 1476:                          spareid => 1,
 1477:                          perlvar => 1,
 1478:                        );
 1479:             my ($result,$returnhash) = &get_remote_globals($server,\%what);
 1480:             if ($result eq 'ok') {
 1481:                 if (ref($returnhash) eq 'HASH') {
 1482:                     if (ref($returnhash->{'perlvar'}) eq 'HASH') {
 1483:                         if ($returnhash->{'perlvar'}->{'lonBalancer'} eq 'yes') {
 1484:                             $currbalancer = $server;
 1485:                             $currtargets = {};
 1486:                             if (ref($returnhash->{'spareid'}) eq 'HASH') {
 1487:                                 if (ref($returnhash->{'spareid'}->{'primary'}) eq 'ARRAY') {
 1488:                                     $currtargets->{'primary'} = $returnhash->{'spareid'}->{'primary'};
 1489:                                 }
 1490:                                 if (ref($returnhash->{'spareid'}->{'default'}) eq 'ARRAY') {
 1491:                                     $currtargets->{'default'} = $returnhash->{'spareid'}->{'default'};
 1492:                                 }
 1493:                             }
 1494:                             last;
 1495:                         }
 1496:                     }
 1497:                 }
 1498:             }
 1499:         }
 1500:     }
 1501:     return ($currbalancer,$currtargets);
 1502: }
 1503: 
 1504: sub check_loadbalancing {
 1505:     my ($uname,$udom,$caller) = @_;
 1506:     my ($is_balancer,$currtargets,$currrules,$dom_in_use,$homeintdom,
 1507:         $rule_in_effect,$offloadto,$otherserver,$setcookie,$dom_balancers);
 1508:     my $lonhost = $perlvar{'lonHostID'};
 1509:     my @hosts = &current_machine_ids();
 1510:     my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
 1511:     my $uintdom = &Apache::lonnet::internet_dom($uprimary_id);
 1512:     my $intdom = &Apache::lonnet::internet_dom($lonhost);
 1513:     my $serverhomedom = &host_domain($lonhost);
 1514:     my $domneedscache;
 1515:     my $cachetime = 60*60*24;
 1516: 
 1517:     if (($uintdom ne '') && ($uintdom eq $intdom)) {
 1518:         $dom_in_use = $udom;
 1519:         $homeintdom = 1;
 1520:     } else {
 1521:         $dom_in_use = $serverhomedom;
 1522:     }
 1523:     my ($result,$cached)=&is_cached_new('loadbalancing',$dom_in_use);
 1524:     unless (defined($cached)) {
 1525:         my %domconfig =
 1526:             &Apache::lonnet::get_dom('configuration',['loadbalancing'],$dom_in_use);
 1527:         if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
 1528:             $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
 1529:         } else {
 1530:             $domneedscache = $dom_in_use;
 1531:         }
 1532:     }
 1533:     if (ref($result) eq 'HASH') {
 1534:         ($is_balancer,$currtargets,$currrules,$setcookie,$dom_balancers) =
 1535:             &check_balancer_result($result,@hosts);
 1536:         if ($is_balancer) {
 1537:             if (ref($currrules) eq 'HASH') {
 1538:                 if ($homeintdom) {
 1539:                     if ($uname ne '') {
 1540:                         if (($currrules->{'_LC_adv'} ne '') || ($currrules->{'_LC_author'} ne '')) {
 1541:                             my ($is_adv,$is_author) = &is_advanced_user($udom,$uname);
 1542:                             if (($currrules->{'_LC_author'} ne '') && ($is_author)) {
 1543:                                 $rule_in_effect = $currrules->{'_LC_author'};
 1544:                             } elsif (($currrules->{'_LC_adv'} ne '') && ($is_adv)) {
 1545:                                 $rule_in_effect = $currrules->{'_LC_adv'}
 1546:                             }
 1547:                         }
 1548:                         if ($rule_in_effect eq '') {
 1549:                             my %userenv = &userenvironment($udom,$uname,'inststatus');
 1550:                             if ($userenv{'inststatus'} ne '') {
 1551:                                 my @statuses = map { &unescape($_); } split(/:/,$userenv{'inststatus'});
 1552:                                 my ($othertitle,$usertypes,$types) =
 1553:                                     &Apache::loncommon::sorted_inst_types($udom);
 1554:                                 if (ref($types) eq 'ARRAY') {
 1555:                                     foreach my $type (@{$types}) {
 1556:                                         if (grep(/^\Q$type\E$/,@statuses)) {
 1557:                                             if (exists($currrules->{$type})) {
 1558:                                                 $rule_in_effect = $currrules->{$type};
 1559:                                             }
 1560:                                         }
 1561:                                     }
 1562:                                 }
 1563:                             } else {
 1564:                                 if (exists($currrules->{'default'})) {
 1565:                                     $rule_in_effect = $currrules->{'default'};
 1566:                                 }
 1567:                             }
 1568:                         }
 1569:                     } else {
 1570:                         if (exists($currrules->{'default'})) {
 1571:                             $rule_in_effect = $currrules->{'default'};
 1572:                         }
 1573:                     }
 1574:                 } else {
 1575:                     if ($currrules->{'_LC_external'} ne '') {
 1576:                         $rule_in_effect = $currrules->{'_LC_external'};
 1577:                     }
 1578:                 }
 1579:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
 1580:                                                        $uname,$udom);
 1581:             }
 1582:         }
 1583:     } elsif (($homeintdom) && ($udom ne $serverhomedom)) {
 1584:         ($result,$cached)=&is_cached_new('loadbalancing',$serverhomedom);
 1585:         unless (defined($cached)) {
 1586:             my %domconfig =
 1587:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$serverhomedom);
 1588:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
 1589:                 $result = &do_cache_new('loadbalancing',$serverhomedom,$domconfig{'loadbalancing'},$cachetime);
 1590:             } else {
 1591:                 $domneedscache = $serverhomedom;
 1592:             }
 1593:         }
 1594:         if (ref($result) eq 'HASH') {
 1595:             ($is_balancer,$currtargets,$currrules,$setcookie,$dom_balancers) =
 1596:                 &check_balancer_result($result,@hosts);
 1597:             if ($is_balancer) {
 1598:                 if (ref($currrules) eq 'HASH') {
 1599:                     if ($currrules->{'_LC_internetdom'} ne '') {
 1600:                         $rule_in_effect = $currrules->{'_LC_internetdom'};
 1601:                     }
 1602:                 }
 1603:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
 1604:                                                        $uname,$udom);
 1605:             }
 1606:         } else {
 1607:             if ($perlvar{'lonBalancer'} eq 'yes') {
 1608:                 $is_balancer = 1;
 1609:                 $offloadto = &this_host_spares($dom_in_use);
 1610:             }
 1611:             unless (defined($cached)) {
 1612:                 $domneedscache = $serverhomedom;
 1613:             }
 1614:         }
 1615:     } else {
 1616:         if ($perlvar{'lonBalancer'} eq 'yes') {
 1617:             $is_balancer = 1;
 1618:             $offloadto = &this_host_spares($dom_in_use);
 1619:         }
 1620:         unless (defined($cached)) {
 1621:             $domneedscache = $serverhomedom;
 1622:         }
 1623:     }
 1624:     if ($domneedscache) {
 1625:         &do_cache_new('loadbalancing',$domneedscache,$is_balancer,$cachetime);
 1626:     }
 1627:     if ($is_balancer) {
 1628:         my $lowest_load = 30000;
 1629:         if (ref($offloadto) eq 'HASH') {
 1630:             if (ref($offloadto->{'primary'}) eq 'ARRAY') {
 1631:                 foreach my $try_server (@{$offloadto->{'primary'}}) {
 1632:                     ($otherserver,$lowest_load) =
 1633:                         &compare_server_load($try_server,$otherserver,$lowest_load);
 1634:                 }
 1635:             }
 1636:             my $found_server = ($otherserver ne '' && $lowest_load < 100);
 1637: 
 1638:             if (!$found_server) {
 1639:                 if (ref($offloadto->{'default'}) eq 'ARRAY') {
 1640:                     foreach my $try_server (@{$offloadto->{'default'}}) {
 1641:                         ($otherserver,$lowest_load) =
 1642:                             &compare_server_load($try_server,$otherserver,$lowest_load);
 1643:                     }
 1644:                 }
 1645:             }
 1646:         } elsif (ref($offloadto) eq 'ARRAY') {
 1647:             if (@{$offloadto} == 1) {
 1648:                 $otherserver = $offloadto->[0];
 1649:             } elsif (@{$offloadto} > 1) {
 1650:                 foreach my $try_server (@{$offloadto}) {
 1651:                     ($otherserver,$lowest_load) =
 1652:                         &compare_server_load($try_server,$otherserver,$lowest_load);
 1653:                 }
 1654:             }
 1655:         }
 1656:         unless ($caller eq 'login') {
 1657:             if (($otherserver ne '') && (grep(/^\Q$otherserver\E$/,@hosts))) {
 1658:                 $is_balancer = 0;
 1659:                 if ($uname ne '' && $udom ne '') {
 1660:                     if (($env{'user.name'} eq $uname) && ($env{'user.domain'} eq $udom)) {
 1661:                         &appenv({'user.loadbalexempt'     => $lonhost,
 1662:                                  'user.loadbalcheck.time' => time});
 1663:                     }
 1664:                 }
 1665:             }
 1666:         }
 1667:         unless ($homeintdom) {
 1668:             undef($setcookie);
 1669:         }
 1670:     }
 1671:     return ($is_balancer,$otherserver,$setcookie,$offloadto,$dom_balancers);
 1672: }
 1673: 
 1674: sub check_balancer_result {
 1675:     my ($result,@hosts) = @_;
 1676:     my ($is_balancer,$currtargets,$currrules,$setcookie,$dom_balancers);
 1677:     if (ref($result) eq 'HASH') {
 1678:         if ($result->{'lonhost'} ne '') {
 1679:             my $currbalancer = $result->{'lonhost'};
 1680:             if (grep(/^\Q$currbalancer\E$/,@hosts)) {
 1681:                 $is_balancer = 1;
 1682:                 $currtargets = $result->{'targets'};
 1683:                 $currrules = $result->{'rules'};
 1684:             }
 1685:             $dom_balancers = $currbalancer;
 1686:         } else {
 1687:             if (keys(%{$result})) {
 1688:                 foreach my $key (keys(%{$result})) {
 1689:                     if (($key ne '') && (grep(/^\Q$key\E$/,@hosts)) &&
 1690:                         (ref($result->{$key}) eq 'HASH')) {
 1691:                         $is_balancer = 1;
 1692:                         $currrules = $result->{$key}{'rules'};
 1693:                         $currtargets = $result->{$key}{'targets'};
 1694:                         $setcookie = $result->{$key}{'cookie'};
 1695:                         last;
 1696:                     }
 1697:                 }
 1698:                 $dom_balancers = join(',',sort(keys(%{$result})));
 1699:             }
 1700:         }
 1701:     }
 1702:     return ($is_balancer,$currtargets,$currrules,$setcookie,$dom_balancers);
 1703: }
 1704: 
 1705: sub get_loadbalancer_targets {
 1706:     my ($rule_in_effect,$currtargets,$uname,$udom) = @_;
 1707:     my $offloadto;
 1708:     if ($rule_in_effect eq 'none') {
 1709:         return [$perlvar{'lonHostID'}];
 1710:     } elsif ($rule_in_effect eq '') {
 1711:         $offloadto = $currtargets;
 1712:     } else {
 1713:         if ($rule_in_effect eq 'homeserver') {
 1714:             my $homeserver = &homeserver($uname,$udom);
 1715:             if ($homeserver ne 'no_host') {
 1716:                 $offloadto = [$homeserver];
 1717:             }
 1718:         } elsif ($rule_in_effect eq 'externalbalancer') {
 1719:             my %domconfig =
 1720:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
 1721:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
 1722:                 if ($domconfig{'loadbalancing'}{'lonhost'} ne '') {
 1723:                     if (&hostname($domconfig{'loadbalancing'}{'lonhost'}) ne '') {
 1724:                         $offloadto = [$domconfig{'loadbalancing'}{'lonhost'}];
 1725:                     }
 1726:                 }
 1727:             } else {
 1728:                 my %servers = &internet_dom_servers($udom);
 1729:                 my ($remotebalancer,$remotetargets) = &get_lonbalancer_config(\%servers);
 1730:                 if (&hostname($remotebalancer) ne '') {
 1731:                     $offloadto = [$remotebalancer];
 1732:                 }
 1733:             }
 1734:         } elsif (&hostname($rule_in_effect) ne '') {
 1735:             $offloadto = [$rule_in_effect];
 1736:         }
 1737:     }
 1738:     return $offloadto;
 1739: }
 1740: 
 1741: sub internet_dom_servers {
 1742:     my ($dom) = @_;
 1743:     my (%uniqservers,%servers);
 1744:     my $primaryserver = &hostname(&domain($dom,'primary'));
 1745:     my @machinedoms = &machine_domains($primaryserver);
 1746:     foreach my $mdom (@machinedoms) {
 1747:         my %currservers = %servers;
 1748:         my %server = &get_servers($mdom);
 1749:         %servers = (%currservers,%server);
 1750:     }
 1751:     my %by_hostname;
 1752:     foreach my $id (keys(%servers)) {
 1753:         push(@{$by_hostname{$servers{$id}}},$id);
 1754:     }
 1755:     foreach my $hostname (sort(keys(%by_hostname))) {
 1756:         if (@{$by_hostname{$hostname}} > 1) {
 1757:             my $match = 0;
 1758:             foreach my $id (@{$by_hostname{$hostname}}) {
 1759:                 if (&host_domain($id) eq $dom) {
 1760:                     $uniqservers{$id} = $hostname;
 1761:                     $match = 1;
 1762:                 }
 1763:             }
 1764:             unless ($match) {
 1765:                 $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
 1766:             }
 1767:         } else {
 1768:             $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
 1769:         }
 1770:     }
 1771:     return %uniqservers;
 1772: }
 1773: 
 1774: sub trusted_domains {
 1775:     my ($cmdtype,$calldom) = @_;
 1776:     my ($trusted,$untrusted);
 1777:     if (&domain($calldom) eq '') {
 1778:         return ($trusted,$untrusted);
 1779:     }
 1780:     unless ($cmdtype =~ /^(content|shared|enroll|coaurem|othcoau|domroles|catalog|reqcrs|msg)$/) {
 1781:         return ($trusted,$untrusted);
 1782:     }
 1783:     my $callprimary = &domain($calldom,'primary');
 1784:     my $intcalldom = &Apache::lonnet::internet_dom($callprimary);
 1785:     if ($intcalldom eq '') {
 1786:         return ($trusted,$untrusted);
 1787:     }
 1788: 
 1789:     my ($trustconfig,$cached)=&Apache::lonnet::is_cached_new('trust',$calldom);
 1790:     unless (defined($cached)) {
 1791:         my %domconfig = &Apache::lonnet::get_dom('configuration',['trust'],$calldom);
 1792:         &Apache::lonnet::do_cache_new('trust',$calldom,$domconfig{'trust'},3600);
 1793:         $trustconfig = $domconfig{'trust'};
 1794:     }
 1795:     if (ref($trustconfig)) {
 1796:         my (%possexc,%possinc,@allexc,@allinc); 
 1797:         if (ref($trustconfig->{$cmdtype}) eq 'HASH') {
 1798:             if (ref($trustconfig->{$cmdtype}->{'exc'}) eq 'ARRAY') {
 1799:                 map { $possexc{$_} = 1; } @{$trustconfig->{$cmdtype}->{'exc'}}; 
 1800:             }
 1801:             if (ref($trustconfig->{$cmdtype}->{'inc'}) eq 'ARRAY') {
 1802:                 $possinc{$intcalldom} = 1;
 1803:                 map { $possinc{$_} = 1; } @{$trustconfig->{$cmdtype}->{'inc'}};
 1804:             }
 1805:         }
 1806:         if (keys(%possexc)) {
 1807:             if (keys(%possinc)) {
 1808:                 foreach my $key (sort(keys(%possexc))) {
 1809:                     next if ($key eq $intcalldom);
 1810:                     unless ($possinc{$key}) {
 1811:                         push(@allexc,$key);
 1812:                     }
 1813:                 }
 1814:             } else {
 1815:                 @allexc = sort(keys(%possexc));
 1816:             }
 1817:         }
 1818:         if (keys(%possinc)) {
 1819:             $possinc{$intcalldom} = 1;
 1820:             @allinc = sort(keys(%possinc));
 1821:         }
 1822:         if ((@allexc > 0) || (@allinc > 0)) {
 1823:             my %doms_by_intdom;
 1824:             my %allintdoms = &all_host_intdom();
 1825:             my %alldoms = &all_host_domain();
 1826:             foreach my $key (%allintdoms) {
 1827:                 if (ref($doms_by_intdom{$allintdoms{$key}}) eq 'ARRAY') {
 1828:                     unless (grep(/^\Q$alldoms{$key}\E$/,@{$doms_by_intdom{$allintdoms{$key}}})) {
 1829:                         push(@{$doms_by_intdom{$allintdoms{$key}}},$alldoms{$key});
 1830:                     }
 1831:                 } else {
 1832:                     $doms_by_intdom{$allintdoms{$key}} = [$alldoms{$key}]; 
 1833:                 }
 1834:             }
 1835:             foreach my $exc (@allexc) {
 1836:                 if (ref($doms_by_intdom{$exc}) eq 'ARRAY') {
 1837:                     push(@{$untrusted},@{$doms_by_intdom{$exc}});
 1838:                 }
 1839:             }
 1840:             foreach my $inc (@allinc) {
 1841:                 if (ref($doms_by_intdom{$inc}) eq 'ARRAY') {
 1842:                     push(@{$trusted},@{$doms_by_intdom{$inc}});
 1843:                 }
 1844:             }
 1845:         }
 1846:     }
 1847:     return ($trusted,$untrusted);
 1848: }
 1849: 
 1850: sub will_trust {
 1851:     my ($cmdtype,$domain,$possdom) = @_;
 1852:     return 1 if ($domain eq $possdom);
 1853:     my ($trustedref,$untrustedref) = &trusted_domains($cmdtype,$possdom);
 1854:     my $willtrust; 
 1855:     if ((ref($trustedref) eq 'ARRAY') && (@{$trustedref} > 0)) {
 1856:         if (grep(/^\Q$domain\E$/,@{$trustedref})) {
 1857:             $willtrust = 1;
 1858:         }
 1859:     } elsif ((ref($untrustedref) eq 'ARRAY') && (@{$untrustedref} > 0)) {
 1860:         unless (grep(/^\Q$domain\E$/,@{$untrustedref})) {
 1861:             $willtrust = 1;
 1862:         }
 1863:     } else {
 1864:         $willtrust = 1;
 1865:     }
 1866:     return $willtrust;
 1867: }
 1868: 
 1869: # ---------------------- Find the homebase for a user from domain's lib servers
 1870: 
 1871: my %homecache;
 1872: sub homeserver {
 1873:     my ($uname,$udom,$ignoreBadCache)=@_;
 1874:     my $index="$uname:$udom";
 1875: 
 1876:     if (exists($homecache{$index})) { return $homecache{$index}; }
 1877: 
 1878:     my %servers = &get_servers($udom,'library');
 1879:     foreach my $tryserver (keys(%servers)) {
 1880:         next if ($ignoreBadCache ne 'true' && 
 1881: 		 exists($badServerCache{$tryserver}));
 1882: 
 1883: 	my $answer=reply("home:$udom:$uname",$tryserver);
 1884: 	if ($answer eq 'found') {
 1885: 	    delete($badServerCache{$tryserver}); 
 1886: 	    return $homecache{$index}=$tryserver;
 1887: 	} elsif ($answer eq 'no_host') {
 1888: 	    $badServerCache{$tryserver}=1;
 1889: 	}
 1890:     }    
 1891:     return 'no_host';
 1892: }
 1893: 
 1894: # ----- Find the usernames behind a list of student/employee IDs or clicker IDs
 1895: 
 1896: sub idget {
 1897:     my ($udom,$idsref,$namespace)=@_;
 1898:     my %returnhash=();
 1899:     my @ids=(); 
 1900:     if (ref($idsref) eq 'ARRAY') {
 1901:         @ids = @{$idsref};
 1902:     } else {
 1903:         return %returnhash; 
 1904:     }
 1905:     if ($namespace eq '') {
 1906:         $namespace = 'ids';
 1907:     }
 1908:     
 1909:     my %servers = &get_servers($udom,'library');
 1910:     foreach my $tryserver (keys(%servers)) {
 1911: 	my $idlist=join('&', map { &escape($_); } @ids);
 1912: 	if ($namespace eq 'ids') {
 1913: 	    $idlist=~tr/A-Z/a-z/;
 1914: 	}
 1915: 	my $reply;
 1916: 	if ($namespace eq 'ids') {
 1917: 	    $reply=&reply("idget:$udom:".$idlist,$tryserver);
 1918: 	} else {
 1919: 	    $reply=&reply("getdom:$udom:$namespace:$idlist",$tryserver);
 1920: 	}
 1921: 	my @answer=();
 1922: 	if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
 1923: 	    @answer=split(/\&/,$reply);
 1924: 	}                    ;
 1925: 	my $i;
 1926: 	for ($i=0;$i<=$#ids;$i++) {
 1927: 	    if ($answer[$i]) {
 1928: 		$returnhash{$ids[$i]}=&unescape($answer[$i]);
 1929: 	    }
 1930: 	}
 1931:     }
 1932:     return %returnhash;
 1933: }
 1934: 
 1935: # ------------------------------------- Find the IDs behind a list of usernames
 1936: 
 1937: sub idrget {
 1938:     my ($udom,@unames)=@_;
 1939:     my %returnhash=();
 1940:     foreach my $uname (@unames) {
 1941:         $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
 1942:     }
 1943:     return %returnhash;
 1944: }
 1945: 
 1946: # Store away a list of names and associated student/employee IDs or clicker IDs
 1947: 
 1948: sub idput {
 1949:     my ($udom,$idsref,$uhom,$namespace)=@_;
 1950:     my %servers=();
 1951:     my %ids=();
 1952:     my %byid = ();
 1953:     if (ref($idsref) eq 'HASH') {
 1954:         %ids=%{$idsref};
 1955:     }
 1956:     if ($namespace eq '') {
 1957:         $namespace = 'ids'; 
 1958:     }
 1959:     foreach my $uname (keys(%ids)) {
 1960: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
 1961:         if ($uhom eq '') {
 1962:             $uhom=&homeserver($uname,$udom);
 1963:         }
 1964:         if ($uhom ne 'no_host') {
 1965:             my $esc_unam=&escape($uname);
 1966:             if ($namespace eq 'ids') {
 1967:                 my $id=&escape($ids{$uname});
 1968:                 $id=~tr/A-Z/a-z/;
 1969:                 my $esc_unam=&escape($uname);
 1970:                 $servers{$uhom}.=$id.'='.$esc_unam.'&';
 1971:             } else {
 1972:                 my @currids = split(/,/,$ids{$uname});
 1973:                 foreach my $id (@currids) {
 1974:                     $byid{$uhom}{$id} .= $uname.',';
 1975:                 }
 1976:             }
 1977:         }
 1978:     }
 1979:     if ($namespace eq 'clickers') {
 1980:         foreach my $server (keys(%byid)) {
 1981:             if (ref($byid{$server}) eq 'HASH') {
 1982:                 foreach my $id (keys(%{$byid{$server}})) {
 1983:                     $byid{$server} =~ s/,$//;
 1984:                     $servers{$uhom}.=&escape($id).'='.&escape($byid{$server}).'&'; 
 1985:                 }
 1986:             }
 1987:         }
 1988:     }
 1989:     foreach my $server (keys(%servers)) {
 1990:         $servers{$server} =~ s/\&$//;
 1991:         if ($namespace eq 'ids') {     
 1992:             &critical('idput:'.$udom.':'.$servers{$server},$server);
 1993:         } else {
 1994:             &critical('updateclickers:'.$udom.':add:'.$servers{$server},$server);
 1995:         }
 1996:     }
 1997: }
 1998: 
 1999: # ------------- Delete unwanted student/employee IDs or clicker IDs from domain
 2000: 
 2001: sub iddel {
 2002:     my ($udom,$idshashref,$uhome,$namespace)=@_;
 2003:     my %result=();
 2004:     my %ids=();
 2005:     my %byid = ();
 2006:     if (ref($idshashref) eq 'HASH') {
 2007:         %ids=%{$idshashref};
 2008:     } else {
 2009:         return %result;
 2010:     }
 2011:     if ($namespace eq '') {
 2012:         $namespace = 'ids';
 2013:     }
 2014:     my %servers=();
 2015:     while (my ($id,$unamestr) = each(%ids)) {
 2016:         if ($namespace eq 'ids') {
 2017:             my $uhom = $uhome;
 2018:             if ($uhom eq '') { 
 2019:                 $uhom=&homeserver($unamestr,$udom);
 2020:             }
 2021:             if ($uhom ne 'no_host') {
 2022:                 $servers{$uhom}.='&'.&escape($id);
 2023:             }
 2024:          } else {
 2025:             my @curritems = split(/,/,$ids{$id});
 2026:             foreach my $uname (@curritems) {
 2027:                 my $uhom = $uhome;
 2028:                 if ($uhom eq '') {
 2029:                     $uhom=&homeserver($uname,$udom);
 2030:                 }
 2031:                 if ($uhom ne 'no_host') { 
 2032:                     $byid{$uhom}{$id} .= $uname.',';
 2033:                 }
 2034:             }
 2035:         }
 2036:     }
 2037:     if ($namespace eq 'clickers') {
 2038:         foreach my $server (keys(%byid)) {
 2039:             if (ref($byid{$server}) eq 'HASH') {
 2040:                 foreach my $id (keys(%{$byid{$server}})) {
 2041:                     $byid{$server}{$id} =~ s/,$//;
 2042:                     $servers{$server}.=&escape($id).'='.&escape($byid{$server}{$id}).'&';
 2043:                 }
 2044:             }
 2045:         }
 2046:     }
 2047:     foreach my $server (keys(%servers)) {
 2048:         $servers{$server} =~ s/\&$//;
 2049:         if ($namespace eq 'ids') {
 2050:             $result{$server} = &critical('iddel:'.$udom.':'.$servers{$server},$uhome);
 2051:         } elsif ($namespace eq 'clickers') {
 2052:             $result{$server} = &critical('updateclickers:'.$udom.':del:'.$servers{$server},$server);
 2053:         }
 2054:     }
 2055:     return %result;
 2056: }
 2057: 
 2058: # ----- Update clicker ID-to-username look-ups in clickers.db on library server 
 2059: 
 2060: sub updateclickers {
 2061:     my ($udom,$action,$idshashref,$uhome,$critical) = @_;
 2062:     my %clickers;
 2063:     if (ref($idshashref) eq 'HASH') {
 2064:         %clickers=%{$idshashref};
 2065:     } else {
 2066:         return;
 2067:     }
 2068:     my $items='';
 2069:     foreach my $item (keys(%clickers)) {
 2070:         $items.=&escape($item).'='.&escape($clickers{$item}).'&';
 2071:     }
 2072:     $items=~s/\&$//;
 2073:     my $request = "updateclickers:$udom:$action:$items";
 2074:     if ($critical) {
 2075:         return &critical($request,$uhome);
 2076:     } else {
 2077:         return &reply($request,$uhome);
 2078:     }
 2079: }
 2080: 
 2081: # ------------------------------dump from db file owned by domainconfig user
 2082: sub dump_dom {
 2083:     my ($namespace, $udom, $regexp) = @_;
 2084: 
 2085:     $udom ||= $env{'user.domain'};
 2086: 
 2087:     return () unless $udom;
 2088: 
 2089:     return &dump($namespace, $udom, &get_domainconfiguser($udom), $regexp);
 2090: }
 2091: 
 2092: # ------------------------------------------ get items from domain db files   
 2093: 
 2094: sub get_dom {
 2095:     my ($namespace,$storearr,$udom,$uhome)=@_;
 2096:     return if ($udom eq 'public');
 2097:     my $items='';
 2098:     foreach my $item (@$storearr) {
 2099:         $items.=&escape($item).'&';
 2100:     }
 2101:     $items=~s/\&$//;
 2102:     if (!$udom) {
 2103:         $udom=$env{'user.domain'};
 2104:         return if ($udom eq 'public');
 2105:         if (defined(&domain($udom,'primary'))) {
 2106:             $uhome=&domain($udom,'primary');
 2107:         } else {
 2108:             undef($uhome);
 2109:         }
 2110:     } else {
 2111:         if (!$uhome) {
 2112:             if (defined(&domain($udom,'primary'))) {
 2113:                 $uhome=&domain($udom,'primary');
 2114:             }
 2115:         }
 2116:     }
 2117:     if ($udom && $uhome && ($uhome ne 'no_host')) {
 2118:         my $rep;
 2119:         if ($namespace =~ /^enc/) {
 2120:             $rep=&reply("encrypt:egetdom:$udom:$namespace:$items",$uhome);
 2121:         } else {
 2122:             $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
 2123:         }
 2124:         my %returnhash;
 2125:         if ($rep eq '' || $rep =~ /^error: 2 /) {
 2126:             return %returnhash;
 2127:         }
 2128:         my @pairs=split(/\&/,$rep);
 2129:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
 2130:             return @pairs;
 2131:         }
 2132:         my $i=0;
 2133:         foreach my $item (@$storearr) {
 2134:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
 2135:             $i++;
 2136:         }
 2137:         return %returnhash;
 2138:     } else {
 2139:         &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
 2140:     }
 2141: }
 2142: 
 2143: # -------------------------------------------- put items in domain db files 
 2144: 
 2145: sub put_dom {
 2146:     my ($namespace,$storehash,$udom,$uhome)=@_;
 2147:     if (!$udom) {
 2148:         $udom=$env{'user.domain'};
 2149:         if (defined(&domain($udom,'primary'))) {
 2150:             $uhome=&domain($udom,'primary');
 2151:         } else {
 2152:             undef($uhome);
 2153:         }
 2154:     } else {
 2155:         if (!$uhome) {
 2156:             if (defined(&domain($udom,'primary'))) {
 2157:                 $uhome=&domain($udom,'primary');
 2158:             }
 2159:         }
 2160:     } 
 2161:     if ($udom && $uhome && ($uhome ne 'no_host')) {
 2162:         my $items='';
 2163:         foreach my $item (keys(%$storehash)) {
 2164:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 2165:         }
 2166:         $items=~s/\&$//;
 2167:         if ($namespace =~ /^enc/) {
 2168:             return &reply("encrypt:putdom:$udom:$namespace:$items",$uhome);
 2169:         } else {
 2170:             return &reply("putdom:$udom:$namespace:$items",$uhome);
 2171:         }
 2172:     } else {
 2173:         &logthis("put_dom failed - no homeserver and/or domain");
 2174:     }
 2175: }
 2176: 
 2177: # --------------------- newput for items in db file owned by domainconfig user
 2178: sub newput_dom {
 2179:     my ($namespace,$storehash,$udom) = @_;
 2180:     my $result;
 2181:     if (!$udom) {
 2182:         $udom=$env{'user.domain'};
 2183:     }
 2184:     if ($udom) {
 2185:         my $uname = &get_domainconfiguser($udom);
 2186:         $result = &newput($namespace,$storehash,$udom,$uname);
 2187:     }
 2188:     return $result;
 2189: }
 2190: 
 2191: # --------------------- delete for items in db file owned by domainconfig user
 2192: sub del_dom {
 2193:     my ($namespace,$storearr,$udom)=@_;
 2194:     if (ref($storearr) eq 'ARRAY') {
 2195:         if (!$udom) {
 2196:             $udom=$env{'user.domain'};
 2197:         }
 2198:         if ($udom) {
 2199:             my $uname = &get_domainconfiguser($udom); 
 2200:             return &del($namespace,$storearr,$udom,$uname);
 2201:         }
 2202:     }
 2203: }
 2204: 
 2205: # ----------------------------------construct domainconfig user for a domain 
 2206: sub get_domainconfiguser {
 2207:     my ($udom) = @_;
 2208:     return $udom.'-domainconfig';
 2209: }
 2210: 
 2211: sub retrieve_inst_usertypes {
 2212:     my ($udom) = @_;
 2213:     my (%returnhash,@order);
 2214:     my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
 2215:     if ((ref($domdefs{'inststatustypes'}) eq 'HASH') && 
 2216:         (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
 2217:         return ($domdefs{'inststatustypes'},$domdefs{'inststatusorder'});
 2218:     } else {
 2219:         if (defined(&domain($udom,'primary'))) {
 2220:             my $uhome=&domain($udom,'primary');
 2221:             my $rep=&reply("inst_usertypes:$udom",$uhome);
 2222:             if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
 2223:                 &logthis("retrieve_inst_usertypes failed - $rep returned from $uhome in domain: $udom");
 2224:                 return (\%returnhash,\@order);
 2225:             }
 2226:             my ($hashitems,$orderitems) = split(/:/,$rep); 
 2227:             my @pairs=split(/\&/,$hashitems);
 2228:             foreach my $item (@pairs) {
 2229:                 my ($key,$value)=split(/=/,$item,2);
 2230:                 $key = &unescape($key);
 2231:                 next if ($key =~ /^error: 2 /);
 2232:                 $returnhash{$key}=&thaw_unescape($value);
 2233:             }
 2234:             my @esc_order = split(/\&/,$orderitems);
 2235:             foreach my $item (@esc_order) {
 2236:                 push(@order,&unescape($item));
 2237:             }
 2238:         } else {
 2239:             &logthis("retrieve_inst_usertypes failed - no primary domain server for $udom");
 2240:         }
 2241:         return (\%returnhash,\@order);
 2242:     }
 2243: }
 2244: 
 2245: sub is_domainimage {
 2246:     my ($url) = @_;
 2247:     if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+[^/]-) {
 2248:         if (&domain($1) ne '') {
 2249:             return '1';
 2250:         }
 2251:     }
 2252:     return;
 2253: }
 2254: 
 2255: sub inst_directory_query {
 2256:     my ($srch) = @_;
 2257:     my $udom = $srch->{'srchdomain'};
 2258:     my %results;
 2259:     my $homeserver = &domain($udom,'primary');
 2260:     my $outcome;
 2261:     if ($homeserver ne '') {
 2262:         unless ($homeserver eq $perlvar{'lonHostID'}) {
 2263:             if ($srch->{'srchby'} eq 'email') {
 2264:                 my $lcrev = &get_server_loncaparev(undef,$homeserver);
 2265:                 my ($major,$minor) = ($lcrev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
 2266:                 if (($major eq '' && $minor eq '') || ($major < 2) ||
 2267:                     (($major == 2) && ($minor < 12))) {
 2268:                     return;
 2269:                 }
 2270:             }
 2271:         }
 2272: 	my $queryid=&reply("querysend:instdirsearch:".
 2273: 			   &escape($srch->{'srchby'}).':'.
 2274: 			   &escape($srch->{'srchterm'}).':'.
 2275: 			   &escape($srch->{'srchtype'}),$homeserver);
 2276: 	my $host=&hostname($homeserver);
 2277: 	if ($queryid !~/^\Q$host\E\_/) {
 2278: 	    &logthis('institutional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.' in domain '.$udom);
 2279: 	    return;
 2280: 	}
 2281: 	my $response = &get_query_reply($queryid);
 2282: 	my $maxtries = 5;
 2283: 	my $tries = 1;
 2284: 	while (($response=~/^timeout/) && ($tries < $maxtries)) {
 2285: 	    $response = &get_query_reply($queryid);
 2286: 	    $tries ++;
 2287: 	}
 2288: 
 2289:         if (!&error($response) && $response ne 'refused') {
 2290:             if ($response eq 'unavailable') {
 2291:                 $outcome = $response;
 2292:             } else {
 2293:                 $outcome = 'ok';
 2294:                 my @matches = split(/\n/,$response);
 2295:                 foreach my $match (@matches) {
 2296:                     my ($key,$value) = split(/=/,$match);
 2297:                     $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
 2298:                 }
 2299:             }
 2300:         }
 2301:     }
 2302:     return ($outcome,%results);
 2303: }
 2304: 
 2305: sub usersearch {
 2306:     my ($srch) = @_;
 2307:     my $dom = $srch->{'srchdomain'};
 2308:     my %results;
 2309:     my %libserv = &all_library();
 2310:     my $query = 'usersearch';
 2311:     foreach my $tryserver (keys(%libserv)) {
 2312:         if (&host_domain($tryserver) eq $dom) {
 2313:             unless ($tryserver eq $perlvar{'lonHostID'}) {
 2314:                 if ($srch->{'srchby'} eq 'email') {
 2315:                     my $lcrev = &get_server_loncaparev(undef,$tryserver);
 2316:                     my ($major,$minor) = ($lcrev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
 2317:                     next if (($major eq '' && $minor eq '') || ($major < 2) ||
 2318:                              (($major == 2) && ($minor < 12)));
 2319:                 }
 2320:             }
 2321:             my $host=&hostname($tryserver);
 2322:             my $queryid=
 2323:                 &reply("querysend:".&escape($query).':'.
 2324:                        &escape($srch->{'srchby'}).':'.
 2325:                        &escape($srch->{'srchtype'}).':'.
 2326:                        &escape($srch->{'srchterm'}),$tryserver);
 2327:             if ($queryid !~/^\Q$host\E\_/) {
 2328:                 &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
 2329:                 next;
 2330:             }
 2331:             my $reply = &get_query_reply($queryid);
 2332:             my $maxtries = 1;
 2333:             my $tries = 1;
 2334:             while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 2335:                 $reply = &get_query_reply($queryid);
 2336:                 $tries ++;
 2337:             }
 2338:             if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 2339:                 &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') -  maxtries: '.$maxtries.' tries: '.$tries);
 2340:             } else {
 2341:                 my @matches;
 2342:                 if ($reply =~ /\n/) {
 2343:                     @matches = split(/\n/,$reply);
 2344:                 } else {
 2345:                     @matches = split(/\&/,$reply);
 2346:                 }
 2347:                 foreach my $match (@matches) {
 2348:                     my ($uname,$udom,%userhash);
 2349:                     foreach my $entry (split(/:/,$match)) {
 2350:                         my ($key,$value) =
 2351:                             map {&unescape($_);} split(/=/,$entry);
 2352:                         $userhash{$key} = $value;
 2353:                         if ($key eq 'username') {
 2354:                             $uname = $value;
 2355:                         } elsif ($key eq 'domain') {
 2356:                             $udom = $value;
 2357:                         }
 2358:                     }
 2359:                     $results{$uname.':'.$udom} = \%userhash;
 2360:                 }
 2361:             }
 2362:         }
 2363:     }
 2364:     return %results;
 2365: }
 2366: 
 2367: sub get_instuser {
 2368:     my ($udom,$uname,$id) = @_;
 2369:     my $homeserver = &domain($udom,'primary');
 2370:     my ($outcome,%results);
 2371:     if ($homeserver ne '') {
 2372:         my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
 2373:                            &escape($id).':'.&escape($udom),$homeserver);
 2374:         my $host=&hostname($homeserver);
 2375:         if ($queryid !~/^\Q$host\E\_/) {
 2376:             &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
 2377:             return;
 2378:         }
 2379:         my $response = &get_query_reply($queryid);
 2380:         my $maxtries = 5;
 2381:         my $tries = 1;
 2382:         while (($response=~/^timeout/) && ($tries < $maxtries)) {
 2383:             $response = &get_query_reply($queryid);
 2384:             $tries ++;
 2385:         }
 2386:         if (!&error($response) && $response ne 'refused') {
 2387:             if ($response eq 'unavailable') {
 2388:                 $outcome = $response;
 2389:             } else {
 2390:                 $outcome = 'ok';
 2391:                 my @matches = split(/\n/,$response);
 2392:                 foreach my $match (@matches) {
 2393:                     my ($key,$value) = split(/=/,$match);
 2394:                     $results{&unescape($key)} = &thaw_unescape($value);
 2395:                 }
 2396:             }
 2397:         }
 2398:     }
 2399:     my %userinfo;
 2400:     if (ref($results{$uname}) eq 'HASH') {
 2401:         %userinfo = %{$results{$uname}};
 2402:     } 
 2403:     return ($outcome,%userinfo);
 2404: }
 2405: 
 2406: sub get_multiple_instusers {
 2407:     my ($udom,$users,$caller) = @_;
 2408:     my ($outcome,$results);
 2409:     if (ref($users) eq 'HASH') {
 2410:         my $count = keys(%{$users}); 
 2411:         my $requested = &freeze_escape($users);
 2412:         my $homeserver = &domain($udom,'primary');
 2413:         if ($homeserver ne '') {
 2414:             my $queryid=&reply('querysend:getmultinstusers:::'.$caller.'='.$requested,$homeserver);
 2415:             my $host=&hostname($homeserver);
 2416:             if ($queryid !~/^\Q$host\E\_/) {
 2417:                 &logthis('get_multiple_instusers invalid queryid: '.$queryid.
 2418:                          ' for host: '.$homeserver.'in domain '.$udom);
 2419:                 return ($outcome,$results);
 2420:             }
 2421:             my $response = &get_query_reply($queryid);
 2422:             my $maxtries = 5;
 2423:             if ($count > 100) {
 2424:                 $maxtries = 1+int($count/20);
 2425:             }
 2426:             my $tries = 1;
 2427:             while (($response=~/^timeout/) && ($tries <= $maxtries)) {
 2428:                 $response = &get_query_reply($queryid);
 2429:                 $tries ++;
 2430:             }
 2431:             if ($response eq '') {
 2432:                 $results = {};
 2433:                 foreach my $key (keys(%{$users})) {
 2434:                     my ($uname,$id);
 2435:                     if ($caller eq 'id') {
 2436:                         $id = $key;
 2437:                     } else {
 2438:                         $uname = $key;
 2439:                     }
 2440:                     my ($resp,%info) = &get_instuser($udom,$uname,$id);
 2441:                     $outcome = $resp;
 2442:                     if ($resp eq 'ok') {
 2443:                         %{$results} = (%{$results}, %info);
 2444:                     } else {
 2445:                         last;
 2446:                     }
 2447:                 }
 2448:             } elsif(!&error($response) && ($response ne 'refused')) {
 2449:                 if (($response eq 'unavailable') || ($response eq 'invalid') || ($response eq 'timeout')) {
 2450:                     $outcome = $response;
 2451:                 } else {
 2452:                     ($outcome,my $userdata) = split(/=/,$response,2);
 2453:                     if ($outcome eq 'ok') {
 2454:                         $results = &thaw_unescape($userdata); 
 2455:                     }
 2456:                 }
 2457:             }
 2458:         }
 2459:     }
 2460:     return ($outcome,$results);
 2461: }
 2462: 
 2463: sub inst_rulecheck {
 2464:     my ($udom,$uname,$id,$item,$rules) = @_;
 2465:     my %returnhash;
 2466:     if ($udom ne '') {
 2467:         if (ref($rules) eq 'ARRAY') {
 2468:             @{$rules} = map {&escape($_);} (@{$rules});
 2469:             my $rulestr = join(':',@{$rules});
 2470:             my $homeserver=&domain($udom,'primary');
 2471:             if (($homeserver ne '') && ($homeserver ne 'no_host')) {
 2472:                 my $response;
 2473:                 if ($item eq 'username') {                
 2474:                     $response=&unescape(&reply('instrulecheck:'.&escape($udom).
 2475:                                               ':'.&escape($uname).':'.$rulestr,
 2476:                                               $homeserver));
 2477:                 } elsif ($item eq 'id') {
 2478:                     $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
 2479:                                               ':'.&escape($id).':'.$rulestr,
 2480:                                               $homeserver));
 2481:                 } elsif ($item eq 'selfcreate') {
 2482:                     $response=&unescape(&reply('instselfcreatecheck:'.
 2483:                                                &escape($udom).':'.&escape($uname).
 2484:                                               ':'.$rulestr,$homeserver));
 2485:                 }
 2486:                 if ($response ne 'refused') {
 2487:                     my @pairs=split(/\&/,$response);
 2488:                     foreach my $item (@pairs) {
 2489:                         my ($key,$value)=split(/=/,$item,2);
 2490:                         $key = &unescape($key);
 2491:                         next if ($key =~ /^error: 2 /);
 2492:                         $returnhash{$key}=&thaw_unescape($value);
 2493:                     }
 2494:                 }
 2495:             }
 2496:         }
 2497:     }
 2498:     return %returnhash;
 2499: }
 2500: 
 2501: sub inst_userrules {
 2502:     my ($udom,$check) = @_;
 2503:     my (%ruleshash,@ruleorder);
 2504:     if ($udom ne '') {
 2505:         my $homeserver=&domain($udom,'primary');
 2506:         if (($homeserver ne '') && ($homeserver ne 'no_host')) {
 2507:             my $response;
 2508:             if ($check eq 'id') {
 2509:                 $response=&reply('instidrules:'.&escape($udom),
 2510:                                  $homeserver);
 2511:             } elsif ($check eq 'email') {
 2512:                 $response=&reply('instemailrules:'.&escape($udom),
 2513:                                  $homeserver);
 2514:             } else {
 2515:                 $response=&reply('instuserrules:'.&escape($udom),
 2516:                                  $homeserver);
 2517:             }
 2518:             if (($response ne 'refused') && ($response ne 'error') && 
 2519:                 ($response ne 'unknown_cmd') && 
 2520:                 ($response ne 'no_such_host')) {
 2521:                 my ($hashitems,$orderitems) = split(/:/,$response);
 2522:                 my @pairs=split(/\&/,$hashitems);
 2523:                 foreach my $item (@pairs) {
 2524:                     my ($key,$value)=split(/=/,$item,2);
 2525:                     $key = &unescape($key);
 2526:                     next if ($key =~ /^error: 2 /);
 2527:                     $ruleshash{$key}=&thaw_unescape($value);
 2528:                 }
 2529:                 my @esc_order = split(/\&/,$orderitems);
 2530:                 foreach my $item (@esc_order) {
 2531:                     push(@ruleorder,&unescape($item));
 2532:                 }
 2533:             }
 2534:         }
 2535:     }
 2536:     return (\%ruleshash,\@ruleorder);
 2537: }
 2538: 
 2539: # ------------- Get Authentication, Language and User Tools Defaults for Domain
 2540: 
 2541: sub get_domain_defaults {
 2542:     my ($domain,$ignore_cache) = @_;
 2543:     return if (($domain eq '') || ($domain eq 'public'));
 2544:     my $cachetime = 60*60*24;
 2545:     unless ($ignore_cache) {
 2546:         my ($result,$cached)=&is_cached_new('domdefaults',$domain);
 2547:         if (defined($cached)) {
 2548:             if (ref($result) eq 'HASH') {
 2549:                 return %{$result};
 2550:             }
 2551:         }
 2552:     }
 2553:     my %domdefaults;
 2554:     my %domconfig =
 2555:          &Apache::lonnet::get_dom('configuration',['defaults','quotas',
 2556:                                   'requestcourses','inststatus',
 2557:                                   'coursedefaults','usersessions',
 2558:                                   'requestauthor','selfenrollment',
 2559:                                   'coursecategories','ssl','autoenroll',
 2560:                                   'trust','helpsettings'],$domain);
 2561:     my @coursetypes = ('official','unofficial','community','textbook','placement');
 2562:     if (ref($domconfig{'defaults'}) eq 'HASH') {
 2563:         $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'}; 
 2564:         $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
 2565:         $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
 2566:         $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
 2567:         $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
 2568:         $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
 2569:         $domdefaults{'intauth_cost'} = $domconfig{'defaults'}{'intauth_cost'};
 2570:         $domdefaults{'intauth_switch'} = $domconfig{'defaults'}{'intauth_switch'};
 2571:         $domdefaults{'intauth_check'} = $domconfig{'defaults'}{'intauth_check'};
 2572:     } else {
 2573:         $domdefaults{'lang_def'} = &domain($domain,'lang_def');
 2574:         $domdefaults{'auth_def'} = &domain($domain,'auth_def');
 2575:         $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
 2576:     }
 2577:     if (ref($domconfig{'quotas'}) eq 'HASH') {
 2578:         if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
 2579:             $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
 2580:         } else {
 2581:             $domdefaults{'defaultquota'} = $domconfig{'quotas'};
 2582:         }
 2583:         my @usertools = ('aboutme','blog','webdav','portfolio');
 2584:         foreach my $item (@usertools) {
 2585:             if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
 2586:                 $domdefaults{$item} = $domconfig{'quotas'}{$item};
 2587:             }
 2588:         }
 2589:         if (ref($domconfig{'quotas'}{'authorquota'}) eq 'HASH') {
 2590:             $domdefaults{'authorquota'} = $domconfig{'quotas'}{'authorquota'};
 2591:         }
 2592:     }
 2593:     if (ref($domconfig{'requestcourses'}) eq 'HASH') {
 2594:         foreach my $item ('official','unofficial','community','textbook','placement') {
 2595:             $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
 2596:         }
 2597:     }
 2598:     if (ref($domconfig{'requestauthor'}) eq 'HASH') {
 2599:         $domdefaults{'requestauthor'} = $domconfig{'requestauthor'};
 2600:     }
 2601:     if (ref($domconfig{'inststatus'}) eq 'HASH') {
 2602:         foreach my $item ('inststatustypes','inststatusorder','inststatusguest') {
 2603:             $domdefaults{$item} = $domconfig{'inststatus'}{$item};
 2604:         }
 2605:     }
 2606:     if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
 2607:         $domdefaults{'canuse_pdfforms'} = $domconfig{'coursedefaults'}{'canuse_pdfforms'};
 2608:         $domdefaults{'usejsme'} = $domconfig{'coursedefaults'}{'usejsme'};
 2609:         $domdefaults{'uselcmath'} = $domconfig{'coursedefaults'}{'uselcmath'};
 2610:         if (ref($domconfig{'coursedefaults'}{'postsubmit'}) eq 'HASH') {
 2611:             $domdefaults{'postsubmit'} = $domconfig{'coursedefaults'}{'postsubmit'}{'client'};
 2612:         }
 2613:         foreach my $type (@coursetypes) {
 2614:             if (ref($domconfig{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
 2615:                 unless ($type eq 'community') {
 2616:                     $domdefaults{$type.'credits'} = $domconfig{'coursedefaults'}{'coursecredits'}{$type};
 2617:                 }
 2618:             }
 2619:             if (ref($domconfig{'coursedefaults'}{'uploadquota'}) eq 'HASH') {
 2620:                 $domdefaults{$type.'quota'} = $domconfig{'coursedefaults'}{'uploadquota'}{$type};
 2621:             }
 2622:             if ($domdefaults{'postsubmit'} eq 'on') {
 2623:                 if (ref($domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}) eq 'HASH') {
 2624:                     $domdefaults{$type.'postsubtimeout'} = 
 2625:                         $domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}{$type}; 
 2626:                 }
 2627:             }
 2628:         }
 2629:         if (ref($domconfig{'coursedefaults'}{'canclone'}) eq 'HASH') {
 2630:             if (ref($domconfig{'coursedefaults'}{'canclone'}{'instcode'}) eq 'ARRAY') {
 2631:                 my @clonecodes = @{$domconfig{'coursedefaults'}{'canclone'}{'instcode'}};
 2632:                 if (@clonecodes) {
 2633:                     $domdefaults{'canclone'} = join('+',@clonecodes);
 2634:                 }
 2635:             }
 2636:         } elsif ($domconfig{'coursedefaults'}{'canclone'}) {
 2637:             $domdefaults{'canclone'}=$domconfig{'coursedefaults'}{'canclone'};
 2638:         }
 2639:         if ($domconfig{'coursedefaults'}{'texengine'}) {
 2640:             $domdefaults{'texengine'} = $domconfig{'coursedefaults'}{'texengine'};
 2641:         } 
 2642:     }
 2643:     if (ref($domconfig{'usersessions'}) eq 'HASH') {
 2644:         if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
 2645:             $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
 2646:         }
 2647:         if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
 2648:             $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
 2649:         }
 2650:         if (ref($domconfig{'usersessions'}{'offloadnow'}) eq 'HASH') {
 2651:             $domdefaults{'offloadnow'} = $domconfig{'usersessions'}{'offloadnow'};
 2652:         }
 2653:     }
 2654:     if (ref($domconfig{'selfenrollment'}) eq 'HASH') {
 2655:         if (ref($domconfig{'selfenrollment'}{'admin'}) eq 'HASH') {
 2656:             my @settings = ('types','registered','enroll_dates','access_dates','section',
 2657:                             'approval','limit');
 2658:             foreach my $type (@coursetypes) {
 2659:                 if (ref($domconfig{'selfenrollment'}{'admin'}{$type}) eq 'HASH') {
 2660:                     my @mgrdc = ();
 2661:                     foreach my $item (@settings) {
 2662:                         if ($domconfig{'selfenrollment'}{'admin'}{$type}{$item} eq '0') {
 2663:                             push(@mgrdc,$item);
 2664:                         }
 2665:                     }
 2666:                     if (@mgrdc) {
 2667:                         $domdefaults{$type.'selfenrolladmdc'} = join(',',@mgrdc);
 2668:                     }
 2669:                 }
 2670:             }
 2671:         }
 2672:         if (ref($domconfig{'selfenrollment'}{'default'}) eq 'HASH') {
 2673:             foreach my $type (@coursetypes) {
 2674:                 if (ref($domconfig{'selfenrollment'}{'default'}{$type}) eq 'HASH') {
 2675:                     foreach my $item (keys(%{$domconfig{'selfenrollment'}{'default'}{$type}})) {
 2676:                         $domdefaults{$type.'selfenroll'.$item} = $domconfig{'selfenrollment'}{'default'}{$type}{$item};
 2677:                     }
 2678:                 }
 2679:             }
 2680:         }
 2681:     }
 2682:     if (ref($domconfig{'coursecategories'}) eq 'HASH') {
 2683:         $domdefaults{'catauth'} = 'std';
 2684:         $domdefaults{'catunauth'} = 'std';
 2685:         if ($domconfig{'coursecategories'}{'auth'}) { 
 2686:             $domdefaults{'catauth'} = $domconfig{'coursecategories'}{'auth'};
 2687:         }
 2688:         if ($domconfig{'coursecategories'}{'unauth'}) {
 2689:             $domdefaults{'catunauth'} = $domconfig{'coursecategories'}{'unauth'};
 2690:         }
 2691:     }
 2692:     if (ref($domconfig{'ssl'}) eq 'HASH') {
 2693:         if (ref($domconfig{'ssl'}{'replication'}) eq 'HASH') {
 2694:             $domdefaults{'replication'} = $domconfig{'ssl'}{'replication'};
 2695:         }
 2696:         if (ref($domconfig{'ssl'}{'connto'}) eq 'HASH') {
 2697:             $domdefaults{'connect'} = $domconfig{'ssl'}{'connto'};
 2698:         }
 2699:         if (ref($domconfig{'ssl'}{'connfrom'}) eq 'HASH') {
 2700:             $domdefaults{'connect'} = $domconfig{'ssl'}{'connfrom'};
 2701:         }
 2702:     }
 2703:     if (ref($domconfig{'trust'}) eq 'HASH') {
 2704:         my @prefixes = qw(content shared enroll othcoau coaurem domroles catalog reqcrs msg);
 2705:         foreach my $prefix (@prefixes) {
 2706:             if (ref($domconfig{'trust'}{$prefix}) eq 'HASH') {
 2707:                 $domdefaults{'trust'.$prefix} = $domconfig{'trust'}{$prefix};
 2708:             }
 2709:         }
 2710:     }
 2711:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
 2712:         $domdefaults{'autofailsafe'} = $domconfig{'autoenroll'}{'autofailsafe'};
 2713:     }
 2714:     if (ref($domconfig{'helpsettings'}) eq 'HASH') {
 2715:         $domdefaults{'submitbugs'} = $domconfig{'helpsettings'}{'submitbugs'};
 2716:         if (ref($domconfig{'helpsettings'}{'adhoc'}) eq 'HASH') {
 2717:             $domdefaults{'adhocroles'} = $domconfig{'helpsettings'}{'adhoc'};
 2718:         }
 2719:     }
 2720:     &do_cache_new('domdefaults',$domain,\%domdefaults,$cachetime);
 2721:     return %domdefaults;
 2722: }
 2723: 
 2724: sub course_portal_url {
 2725:     my ($cnum,$cdom) = @_;
 2726:     my $chome = &homeserver($cnum,$cdom);
 2727:     my $hostname = &hostname($chome);
 2728:     my $protocol = $protocol{$chome};
 2729:     $protocol = 'http' if ($protocol ne 'https');
 2730:     my %domdefaults = &get_domain_defaults($cdom);
 2731:     my $firsturl;
 2732:     if ($domdefaults{'portal_def'}) {
 2733:         $firsturl = $domdefaults{'portal_def'};
 2734:     } else {
 2735:         $firsturl = $protocol.'://'.$hostname;
 2736:     }
 2737:     return $firsturl;
 2738: }
 2739: 
 2740: # --------------------------------------------- Get domain config for passwords
 2741: 
 2742: sub get_passwdconf {
 2743:     my ($dom) = @_;
 2744:     my (%passwdconf,$gotconf,$lookup);
 2745:     my ($result,$cached)=&is_cached_new('passwdconf',$dom);
 2746:     if (defined($cached)) {
 2747:         if (ref($result) eq 'HASH') {
 2748:             %passwdconf = %{$result};
 2749:             $gotconf = 1;
 2750:         }
 2751:     }
 2752:     unless ($gotconf) {
 2753:         my %domconfig = &get_dom('configuration',['passwords'],$dom);
 2754:         if (ref($domconfig{'passwords'}) eq 'HASH') {
 2755:             %passwdconf = %{$domconfig{'passwords'}};
 2756:         }
 2757:         my $cachetime = 24*60*60;
 2758:         &do_cache_new('passwdconf',$dom,\%passwdconf,$cachetime);
 2759:     }
 2760:     return %passwdconf;
 2761: }
 2762: 
 2763: # --------------------------------------------------- Assign a key to a student
 2764: 
 2765: sub assign_access_key {
 2766: #
 2767: # a valid key looks like uname:udom#comments
 2768: # comments are being appended
 2769: #
 2770:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
 2771:     $kdom=
 2772:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
 2773:     $knum=
 2774:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
 2775:     $cdom=
 2776:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 2777:     $cnum=
 2778:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 2779:     $udom=$env{'user.name'} unless (defined($udom));
 2780:     $uname=$env{'user.domain'} unless (defined($uname));
 2781:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
 2782:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
 2783:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
 2784:                                                   # assigned to this person
 2785:                                                   # - this should not happen,
 2786:                                                   # unless something went wrong
 2787:                                                   # the first time around
 2788: # ready to assign
 2789:         $logentry=$1.'; '.$logentry;
 2790:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
 2791:                                                  $kdom,$knum) eq 'ok') {
 2792: # key now belongs to user
 2793: 	    my $envkey='key.'.$cdom.'_'.$cnum;
 2794:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
 2795:                 &appenv({'environment.'.$envkey => $ckey});
 2796:                 return 'ok';
 2797:             } else {
 2798:                 return 
 2799:   'error: Count not permanently assign key, will need to be re-entered later.';
 2800: 	    }
 2801:         } else {
 2802:             return 'error: Could not assign key, try again later.';
 2803:         }
 2804:     } elsif (!$existing{$ckey}) {
 2805: # the key does not exist
 2806: 	return 'error: The key does not exist';
 2807:     } else {
 2808: # the key is somebody else's
 2809: 	return 'error: The key is already in use';
 2810:     }
 2811: }
 2812: 
 2813: # ------------------------------------------ put an additional comment on a key
 2814: 
 2815: sub comment_access_key {
 2816: #
 2817: # a valid key looks like uname:udom#comments
 2818: # comments are being appended
 2819: #
 2820:     my ($ckey,$cdom,$cnum,$logentry)=@_;
 2821:     $cdom=
 2822:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 2823:     $cnum=
 2824:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 2825:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
 2826:     if ($existing{$ckey}) {
 2827:         $existing{$ckey}.='; '.$logentry;
 2828: # ready to assign
 2829:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
 2830:                                                  $cdom,$cnum) eq 'ok') {
 2831: 	    return 'ok';
 2832:         } else {
 2833: 	    return 'error: Count not store comment.';
 2834:         }
 2835:     } else {
 2836: # the key does not exist
 2837: 	return 'error: The key does not exist';
 2838:     }
 2839: }
 2840: 
 2841: # ------------------------------------------------------ Generate a set of keys
 2842: 
 2843: sub generate_access_keys {
 2844:     my ($number,$cdom,$cnum,$logentry)=@_;
 2845:     $cdom=
 2846:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 2847:     $cnum=
 2848:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 2849:     unless (&allowed('mky',$cdom)) { return 0; }
 2850:     unless (($cdom) && ($cnum)) { return 0; }
 2851:     if ($number>10000) { return 0; }
 2852:     sleep(2); # make sure don't get same seed twice
 2853:     srand(time()^($$+($$<<15))); # from "Programming Perl"
 2854:     my $total=0;
 2855:     for (my $i=1;$i<=$number;$i++) {
 2856:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
 2857:                   sprintf("%lx",int(100000*rand)).'-'.
 2858:                   sprintf("%lx",int(100000*rand));
 2859:        $newkey=~s/1/g/g; # folks mix up 1 and l
 2860:        $newkey=~s/0/h/g; # and also 0 and O
 2861:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
 2862:        if ($existing{$newkey}) {
 2863:            $i--;
 2864:        } else {
 2865: 	  if (&put('accesskeys',
 2866:               { $newkey => '# generated '.localtime().
 2867:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
 2868:                            '; '.$logentry },
 2869: 		   $cdom,$cnum) eq 'ok') {
 2870:               $total++;
 2871: 	  }
 2872:        }
 2873:     }
 2874:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
 2875:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
 2876:     return $total;
 2877: }
 2878: 
 2879: # ------------------------------------------------------- Validate an accesskey
 2880: 
 2881: sub validate_access_key {
 2882:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
 2883:     $cdom=
 2884:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 2885:     $cnum=
 2886:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 2887:     $udom=$env{'user.domain'} unless (defined($udom));
 2888:     $uname=$env{'user.name'} unless (defined($uname));
 2889:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
 2890:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
 2891: }
 2892: 
 2893: # ------------------------------------- Find the section of student in a course
 2894: sub devalidate_getsection_cache {
 2895:     my ($udom,$unam,$courseid)=@_;
 2896:     my $hashid="$udom:$unam:$courseid";
 2897:     &devalidate_cache_new('getsection',$hashid);
 2898: }
 2899: 
 2900: sub courseid_to_courseurl {
 2901:     my ($courseid) = @_;
 2902:     #already url style courseid
 2903:     return $courseid if ($courseid =~ m{^/});
 2904: 
 2905:     if (exists($env{'course.'.$courseid.'.num'})) {
 2906: 	my $cnum = $env{'course.'.$courseid.'.num'};
 2907: 	my $cdom = $env{'course.'.$courseid.'.domain'};
 2908: 	return "/$cdom/$cnum";
 2909:     }
 2910: 
 2911:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
 2912:     if (exists($courseinfo{'num'})) {
 2913: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
 2914:     }
 2915: 
 2916:     return undef;
 2917: }
 2918: 
 2919: sub getsection {
 2920:     my ($udom,$unam,$courseid)=@_;
 2921:     my $cachetime=1800;
 2922: 
 2923:     my $hashid="$udom:$unam:$courseid";
 2924:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
 2925:     if (defined($cached)) { return $result; }
 2926: 
 2927:     my %Pending; 
 2928:     my %Expired;
 2929:     #
 2930:     # Each role can either have not started yet (pending), be active, 
 2931:     #    or have expired.
 2932:     #
 2933:     # If there is an active role, we are done.
 2934:     #
 2935:     # If there is more than one role which has not started yet, 
 2936:     #     choose the one which will start sooner
 2937:     # If there is one role which has not started yet, return it.
 2938:     #
 2939:     # If there is more than one expired role, choose the one which ended last.
 2940:     # If there is a role which has expired, return it.
 2941:     #
 2942:     $courseid = &courseid_to_courseurl($courseid);
 2943:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
 2944:     foreach my $key (keys(%roleshash)) {
 2945:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
 2946:         my $section=$1;
 2947:         if ($key eq $courseid.'_st') { $section=''; }
 2948:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
 2949:         my $now=time;
 2950:         if (defined($end) && $end && ($now > $end)) {
 2951:             $Expired{$end}=$section;
 2952:             next;
 2953:         }
 2954:         if (defined($start) && $start && ($now < $start)) {
 2955:             $Pending{$start}=$section;
 2956:             next;
 2957:         }
 2958:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
 2959:     }
 2960:     #
 2961:     # Presumedly there will be few matching roles from the above
 2962:     # loop and the sorting time will be negligible.
 2963:     if (scalar(keys(%Pending))) {
 2964:         my ($time) = sort {$a <=> $b} keys(%Pending);
 2965:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
 2966:     } 
 2967:     if (scalar(keys(%Expired))) {
 2968:         my @sorted = sort {$a <=> $b} keys(%Expired);
 2969:         my $time = pop(@sorted);
 2970:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
 2971:     }
 2972:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
 2973: }
 2974: 
 2975: sub save_cache {
 2976:     &purge_remembered();
 2977:     #&Apache::loncommon::validate_page();
 2978:     undef(%env);
 2979:     undef($env_loaded);
 2980: }
 2981: 
 2982: my $to_remember=-1;
 2983: my %remembered;
 2984: my %accessed;
 2985: my $kicks=0;
 2986: my $hits=0;
 2987: sub make_key {
 2988:     my ($name,$id) = @_;
 2989:     if (length($id) > 65 
 2990: 	&& length(&escape($id)) > 200) {
 2991: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
 2992:     }
 2993:     return &escape($name.':'.$id);
 2994: }
 2995: 
 2996: sub devalidate_cache_new {
 2997:     my ($name,$id,$debug) = @_;
 2998:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
 2999:     my $remembered_id=$name.':'.$id;
 3000:     $id=&make_key($name,$id);
 3001:     $memcache->delete($id);
 3002:     delete($remembered{$remembered_id});
 3003:     delete($accessed{$remembered_id});
 3004: }
 3005: 
 3006: sub is_cached_new {
 3007:     my ($name,$id,$debug) = @_;
 3008:     my $remembered_id=$name.':'.$id; # this is to avoid make_key (which is slow) whenever possible
 3009:     if (exists($remembered{$remembered_id})) {
 3010: 	if ($debug) { &Apache::lonnet::logthis("Early return $remembered_id of $remembered{$remembered_id} "); }
 3011: 	$accessed{$remembered_id}=[&gettimeofday()];
 3012: 	$hits++;
 3013: 	return ($remembered{$remembered_id},1);
 3014:     }
 3015:     $id=&make_key($name,$id);
 3016:     my $value = $memcache->get($id);
 3017:     if (!(defined($value))) {
 3018: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
 3019: 	return (undef,undef);
 3020:     }
 3021:     if ($value eq '__undef__') {
 3022: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
 3023: 	$value=undef;
 3024:     }
 3025:     &make_room($remembered_id,$value,$debug);
 3026:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
 3027:     return ($value,1);
 3028: }
 3029: 
 3030: sub do_cache_new {
 3031:     my ($name,$id,$value,$time,$debug) = @_;
 3032:     my $remembered_id=$name.':'.$id;
 3033:     $id=&make_key($name,$id);
 3034:     my $setvalue=$value;
 3035:     if (!defined($setvalue)) {
 3036: 	$setvalue='__undef__';
 3037:     }
 3038:     if (!defined($time) ) {
 3039: 	$time=600;
 3040:     }
 3041:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
 3042:     my $result = $memcache->set($id,$setvalue,$time);
 3043:     if (! $result) {
 3044: 	&logthis("caching of id -> $id  failed");
 3045: 	$memcache->disconnect_all();
 3046:     }
 3047:     # need to make a copy of $value
 3048:     &make_room($remembered_id,$value,$debug);
 3049:     return $value;
 3050: }
 3051: 
 3052: sub make_room {
 3053:     my ($remembered_id,$value,$debug)=@_;
 3054: 
 3055:     $remembered{$remembered_id}= (ref($value)) ? &Storable::dclone($value)
 3056:                                     : $value;
 3057:     if ($to_remember<0) { return; }
 3058:     $accessed{$remembered_id}=[&gettimeofday()];
 3059:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
 3060:     my $to_kick;
 3061:     my $max_time=0;
 3062:     foreach my $other (keys(%accessed)) {
 3063: 	if (&tv_interval($accessed{$other}) > $max_time) {
 3064: 	    $to_kick=$other;
 3065: 	    $max_time=&tv_interval($accessed{$other});
 3066: 	}
 3067:     }
 3068:     delete($remembered{$to_kick});
 3069:     delete($accessed{$to_kick});
 3070:     $kicks++;
 3071:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
 3072:     return;
 3073: }
 3074: 
 3075: sub purge_remembered {
 3076:     #&logthis("Tossing ".scalar(keys(%remembered)));
 3077:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
 3078:     undef(%remembered);
 3079:     undef(%accessed);
 3080: }
 3081: # ------------------------------------- Read an entry from a user's environment
 3082: 
 3083: sub userenvironment {
 3084:     my ($udom,$unam,@what)=@_;
 3085:     my $items;
 3086:     foreach my $item (@what) {
 3087:         $items.=&escape($item).'&';
 3088:     }
 3089:     $items=~s/\&$//;
 3090:     my %returnhash=();
 3091:     my $uhome = &homeserver($unam,$udom);
 3092:     unless ($uhome eq 'no_host') {
 3093:         my @answer=split(/\&/, 
 3094:             &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
 3095:         if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
 3096:             return %returnhash;
 3097:         }
 3098:         my $i;
 3099:         for ($i=0;$i<=$#what;$i++) {
 3100: 	    $returnhash{$what[$i]}=&unescape($answer[$i]);
 3101:         }
 3102:     }
 3103:     return %returnhash;
 3104: }
 3105: 
 3106: # ---------------------------------------------------------- Get a studentphoto
 3107: sub studentphoto {
 3108:     my ($udom,$unam,$ext) = @_;
 3109:     my $home=&Apache::lonnet::homeserver($unam,$udom);
 3110:     if (defined($env{'request.course.id'})) {
 3111:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
 3112:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
 3113:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
 3114:             } else {
 3115:                 my ($result,$perm_reqd)=
 3116: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
 3117:                 if ($result eq 'ok') {
 3118:                     if (!($perm_reqd eq 'yes')) {
 3119:                         return(&retrievestudentphoto($udom,$unam,$ext));
 3120:                     }
 3121:                 }
 3122:             }
 3123:         }
 3124:     } else {
 3125:         my ($result,$perm_reqd) = 
 3126: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
 3127:         if ($result eq 'ok') {
 3128:             if (!($perm_reqd eq 'yes')) {
 3129:                 return(&retrievestudentphoto($udom,$unam,$ext));
 3130:             }
 3131:         }
 3132:     }
 3133:     return '/adm/lonKaputt/lonlogo_broken.gif';
 3134: }
 3135: 
 3136: sub retrievestudentphoto {
 3137:     my ($udom,$unam,$ext,$type) = @_;
 3138:     my $home=&Apache::lonnet::homeserver($unam,$udom);
 3139:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
 3140:     if ($ret eq 'ok') {
 3141:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
 3142:         if ($type eq 'thumbnail') {
 3143:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
 3144:         }
 3145:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
 3146:         return $tokenurl;
 3147:     } else {
 3148:         if ($type eq 'thumbnail') {
 3149:             return '/adm/lonKaputt/genericstudent_tn.gif';
 3150:         } else { 
 3151:             return '/adm/lonKaputt/lonlogo_broken.gif';
 3152:         }
 3153:     }
 3154: }
 3155: 
 3156: # -------------------------------------------------------------------- New chat
 3157: 
 3158: sub chatsend {
 3159:     my ($newentry,$anon,$group)=@_;
 3160:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
 3161:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 3162:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
 3163:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
 3164: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
 3165: 		   &escape($newentry)).':'.$group,$chome);
 3166: }
 3167: 
 3168: # ------------------------------------------ Find current version of a resource
 3169: 
 3170: sub getversion {
 3171:     my $fname=&clutter(shift);
 3172:     unless ($fname=~m{^(/adm/wrapper|)/res/}) { return -1; }
 3173:     return &currentversion(&filelocation('',$fname));
 3174: }
 3175: 
 3176: sub currentversion {
 3177:     my $fname=shift;
 3178:     my $author=$fname;
 3179:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 3180:     my ($udom,$uname)=split(/\//,$author);
 3181:     my $home=&homeserver($uname,$udom);
 3182:     if ($home eq 'no_host') { 
 3183:         return -1; 
 3184:     }
 3185:     my $answer=&reply("currentversion:$fname",$home);
 3186:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
 3187: 	return -1;
 3188:     }
 3189:     return $answer;
 3190: }
 3191: 
 3192: #
 3193: # Return special version number of resource if set by override, empty otherwise
 3194: #
 3195: sub usedversion {
 3196:     my $fname=shift;
 3197:     unless ($fname) { $fname=$env{'request.uri'}; }
 3198:     my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
 3199:     if ($urlversion) { return $urlversion; }
 3200:     return '';
 3201: }
 3202: 
 3203: # ----------------------------- Subscribe to a resource, return URL if possible
 3204: 
 3205: sub subscribe {
 3206:     my $fname=shift;
 3207:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
 3208:     $fname=~s/[\n\r]//g;
 3209:     my $author=$fname;
 3210:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 3211:     my ($udom,$uname)=split(/\//,$author);
 3212:     my $home=homeserver($uname,$udom);
 3213:     if ($home eq 'no_host') {
 3214:         return 'not_found';
 3215:     }
 3216:     my $answer=reply("sub:$fname",$home);
 3217:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
 3218: 	$answer.=' by '.$home;
 3219:     }
 3220:     return $answer;
 3221: }
 3222:     
 3223: # -------------------------------------------------------------- Replicate file
 3224: 
 3225: sub repcopy {
 3226:     my $filename=shift;
 3227:     $filename=~s/\/+/\//g;
 3228:     my $londocroot = $perlvar{'lonDocRoot'};
 3229:     if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
 3230:     if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
 3231:     if ($filename=~m{^\Q$londocroot/userfiles/\E} or
 3232: 	$filename=~m{^/*(uploaded|editupload)/}) {
 3233: 	return &repcopy_userfile($filename);
 3234:     }
 3235:     $filename=~s/[\n\r]//g;
 3236:     my $transname="$filename.in.transfer";
 3237: # FIXME: this should flock
 3238:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
 3239:     my $remoteurl=subscribe($filename);
 3240:     if ($remoteurl =~ /^con_lost by/) {
 3241: 	   &logthis("Subscribe returned $remoteurl: $filename");
 3242:            return 'unavailable';
 3243:     } elsif ($remoteurl eq 'not_found') {
 3244: 	   #&logthis("Subscribe returned not_found: $filename");
 3245: 	   return 'not_found';
 3246:     } elsif ($remoteurl =~ /^rejected by/) {
 3247: 	   &logthis("Subscribe returned $remoteurl: $filename");
 3248:            return 'forbidden';
 3249:     } elsif ($remoteurl eq 'directory') {
 3250:            return 'ok';
 3251:     } else {
 3252:         my $author=$filename;
 3253:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 3254:         my ($udom,$uname)=split(/\//,$author);
 3255:         my $home=homeserver($uname,$udom);
 3256:         unless ($home eq $perlvar{'lonHostID'}) {
 3257:            my @parts=split(/\//,$filename);
 3258:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
 3259:            if ($path ne "$londocroot/res") {
 3260:                &logthis("Malconfiguration for replication: $filename");
 3261: 	       return 'bad_request';
 3262:            }
 3263:            my $count;
 3264:            for ($count=5;$count<$#parts;$count++) {
 3265:                $path.="/$parts[$count]";
 3266:                if ((-e $path)!=1) {
 3267: 		   mkdir($path,0777);
 3268:                }
 3269:            }
 3270:            my $request=new HTTP::Request('GET',"$remoteurl");
 3271:            my $response;
 3272:            if ($remoteurl =~ m{/raw/}) {
 3273:                $response=&LONCAPA::LWPReq::makerequest($home,$request,$transname,\%perlvar,'',0,1);
 3274:            } else {
 3275:                $response=&LONCAPA::LWPReq::makerequest($home,$request,$transname,\%perlvar,'',1);
 3276:            }
 3277:            if ($response->is_error()) {
 3278: 	       unlink($transname);
 3279:                my $message=$response->status_line;
 3280:                &logthis("<font color=\"blue\">WARNING:"
 3281:                        ." LWP get: $message: $filename</font>");
 3282:                return 'unavailable';
 3283:            } else {
 3284: 	       if ($remoteurl!~/\.meta$/) {
 3285:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
 3286:                   my $mresponse;
 3287:                   if ($remoteurl =~ m{/raw/}) {
 3288:                       $mresponse = &LONCAPA::LWPReq::makerequest($home,$mrequest,$filename.'.meta',\%perlvar,'',0,1);
 3289:                   } else {
 3290:                       $mresponse = &LONCAPA::LWPReq::makerequest($home,$mrequest,$filename.'.meta',\%perlvar,'',1);
 3291:                   }
 3292:                   if ($mresponse->is_error()) {
 3293: 		      unlink($filename.'.meta');
 3294:                       &logthis(
 3295:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
 3296:                   }
 3297: 	       }
 3298:                rename($transname,$filename);
 3299:                return 'ok';
 3300:            }
 3301:        }
 3302:     }
 3303: }
 3304: 
 3305: # ------------------------------------------------ Get server side include body
 3306: sub ssi_body {
 3307:     my ($filelink,%form)=@_;
 3308:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
 3309:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
 3310:     }
 3311:     my $output='';
 3312:     my $response;
 3313:     if ($filelink=~/^https?\:/) {
 3314:        ($output,$response)=&externalssi($filelink);
 3315:     } else {
 3316:        $filelink .= $filelink=~/\?/ ? '&' : '?';
 3317:        $filelink .= 'inhibitmenu=yes';
 3318:        ($output,$response)=&ssi($filelink,%form);
 3319:     }
 3320:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
 3321:     $output=~s/^.*?\<body[^\>]*\>//si;
 3322:     $output=~s/\<\/body\s*\>.*?$//si;
 3323:     if (wantarray) {
 3324:         return ($output, $response);
 3325:     } else {
 3326:         return $output;
 3327:     }
 3328: }
 3329: 
 3330: # --------------------------------------------------------- Server Side Include
 3331: 
 3332: sub absolute_url {
 3333:     my ($host_name) = @_;
 3334:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
 3335:     if ($host_name eq '') {
 3336: 	$host_name = $ENV{'SERVER_NAME'};
 3337:     }
 3338:     return $protocol.$host_name;
 3339: }
 3340: 
 3341: #
 3342: #   Server side include.
 3343: # Parameters:
 3344: #  fn     Possibly encrypted resource name/id.
 3345: #  form   Hash that describes how the rendering should be done
 3346: #         and other things.
 3347: # Returns:
 3348: #   Scalar context: The content of the response.
 3349: #   Array context:  2 element list of the content and the full response object.
 3350: #     
 3351: sub ssi {
 3352: 
 3353:     my ($fn,%form)=@_;
 3354:     my $request;
 3355: 
 3356:     $form{'no_update_last_known'}=1;
 3357:     &Apache::lonenc::check_encrypt(\$fn);
 3358:     if (%form) {
 3359:       $request=new HTTP::Request('POST',&absolute_url().$fn);
 3360:       $request->content(join('&',map { 
 3361:             my $name = escape($_);
 3362:             "$name=" . ( ref($form{$_}) eq 'ARRAY' 
 3363:             ? join("&$name=", map {escape($_) } @{$form{$_}}) 
 3364:             : &escape($form{$_}) );    
 3365:         } keys(%form)));
 3366:     } else {
 3367:       $request=new HTTP::Request('GET',&absolute_url().$fn);
 3368:     }
 3369: 
 3370:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
 3371:     my $lonhost = $perlvar{'lonHostID'};
 3372:     my $islocal;
 3373:     if (($env{'request.course.id'}) &&
 3374:         ($form{'grade_courseid'} eq $env{'request.course.id'}) &&
 3375:         ($form{'grade_username'} ne '') && ($form{'grade_domain'} ne '') &&
 3376:         ($form{'grade_symb'} ne '') &&
 3377:         (&Apache::lonnet::allowed('mgr',$env{'request.course.id'}.
 3378:                                  ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:'')))) {
 3379:         $islocal = 1;
 3380:     }
 3381:     my $response= &LONCAPA::LWPReq::makerequest($lonhost,$request,'',\%perlvar,
 3382:                                                 '','','',$islocal);
 3383: 
 3384:     if (wantarray) {
 3385: 	return ($response->content, $response);
 3386:     } else {
 3387: 	return $response->content;
 3388:     }
 3389: }
 3390: 
 3391: sub externalssi {
 3392:     my ($url)=@_;
 3393:     my $request=new HTTP::Request('GET',$url);
 3394:     my $response = &LONCAPA::LWPReq::makerequest('',$request,'',\%perlvar);
 3395:     if (wantarray) {
 3396:         return ($response->content, $response);
 3397:     } else {
 3398:         return $response->content;
 3399:     }
 3400: }
 3401: 
 3402: 
 3403: # If the local copy of a replicated resource is outdated, trigger a  
 3404: # connection from the homeserver to flush the delayed queue. If no update 
 3405: # happens, remove local copies of outdated resource (and corresponding
 3406: # metadata file).
 3407: 
 3408: sub remove_stale_resfile {
 3409:     my ($url) = @_;
 3410:     my $removed;
 3411:     if ($url=~m{^/res/($match_domain)/($match_username)/}) {
 3412:         my $audom = $1;
 3413:         my $auname = $2;
 3414:         unless (($url =~ /\.\d+\.\w+$/) || ($url =~ m{^/res/lib/templates/})) {
 3415:             my $homeserver = &homeserver($auname,$audom);
 3416:             unless (($homeserver eq 'no_host') ||
 3417:                     (grep { $_ eq $homeserver } &current_machine_ids())) {
 3418:                 my $fname = &filelocation('',$url);
 3419:                 if (-e $fname) {
 3420:                     my $hostname = &hostname($homeserver);
 3421:                     if ($hostname) {
 3422:                         my $protocol = $protocol{$homeserver};
 3423:                         $protocol = 'http' if ($protocol ne 'https');
 3424:                         my $uri = &declutter($url);
 3425:                         my $request=new HTTP::Request('HEAD',$protocol.'://'.$hostname.'/raw/'.$uri);
 3426:                         my $response = &LONCAPA::LWPReq::makerequest($homeserver,$request,'',\%perlvar,5,0,1);
 3427:                         if ($response->is_success()) {
 3428:                             my $remmodtime = &HTTP::Date::str2time( $response->header('Last-modified') );
 3429:                             my $locmodtime = (stat($fname))[9];
 3430:                             if ($locmodtime < $remmodtime) {
 3431:                                 my $stale;
 3432:                                 my $answer = &reply('pong',$homeserver);
 3433:                                 if ($answer eq $homeserver.':'.$perlvar{'lonHostID'}) {
 3434:                                     sleep(0.2);
 3435:                                     $locmodtime = (stat($fname))[9];
 3436:                                     if ($locmodtime < $remmodtime) {
 3437:                                         my $posstransfer = $fname.'.in.transfer';
 3438:                                         if ((-e $posstransfer) && ($remmodtime < (stat($posstransfer))[9])) {
 3439:                                             $removed = 1;
 3440:                                         } else {
 3441:                                             $stale = 1;
 3442:                                         }
 3443:                                     } else {
 3444:                                         $removed = 1;
 3445:                                     }
 3446:                                 } else {
 3447:                                     $stale = 1;
 3448:                                 }
 3449:                                 if ($stale) {
 3450:                                     unlink($fname);
 3451:                                     if ($uri!~/\.meta$/) {
 3452:                                         unlink($fname.'.meta');
 3453:                                     }
 3454:                                     &reply("unsub:$fname",$homeserver);
 3455:                                     $removed = 1;
 3456:                                 }
 3457:                             }
 3458:                         }
 3459:                     }
 3460:                 }
 3461:             }
 3462:         }
 3463:     }
 3464:     return $removed;
 3465: }
 3466: 
 3467: # -------------------------------- Allow a /uploaded/ URI to be vouched for
 3468: 
 3469: sub allowuploaded {
 3470:     my ($srcurl,$url)=@_;
 3471:     $url=&clutter(&declutter($url));
 3472:     my $dir=$url;
 3473:     $dir=~s/\/[^\/]+$//;
 3474:     my %httpref=();
 3475:     my $httpurl=&hreflocation('',$url);
 3476:     $httpref{'httpref.'.$httpurl}=$srcurl;
 3477:     &Apache::lonnet::appenv(\%httpref);
 3478: }
 3479: 
 3480: #
 3481: # Determine if the current user should be able to edit a particular resource,
 3482: # when viewing in course context.
 3483: # (a) When viewing resource used to determine if "Edit" item is included in 
 3484: #     Functions.
 3485: # (b) When displaying folder contents in course editor, used to determine if
 3486: #     "Edit" link will be displayed alongside resource.
 3487: #
 3488: #  input: six args -- filename (decluttered), course number, course domain,
 3489: #                   url, symb (if registered) and group (if this is a group
 3490: #                   item -- e.g., bulletin board, group page etc.).
 3491: #  output: array of five scalars -- 
 3492: #          $cfile -- url for file editing if editable on current server
 3493: #          $home -- homeserver of resource (i.e., for author if published,
 3494: #                                           or course if uploaded.).
 3495: #          $switchserver --  1 if server switch will be needed.
 3496: #          $forceedit -- 1 if icon/link should be to go to edit mode 
 3497: #          $forceview -- 1 if icon/link should be to go to view mode
 3498: #
 3499: 
 3500: sub can_edit_resource {
 3501:     my ($file,$cnum,$cdom,$resurl,$symb,$group) = @_;
 3502:     my ($cfile,$home,$switchserver,$forceedit,$forceview,$uploaded,$incourse);
 3503: #
 3504: # For aboutme pages user can only edit his/her own.
 3505: #
 3506:     if ($resurl =~ m{^/?adm/($match_domain)/($match_username)/aboutme$}) {
 3507:         my ($sdom,$sname) = ($1,$2);
 3508:         if (($sdom eq $env{'user.domain'}) && ($sname eq $env{'user.name'})) {
 3509:             $home = $env{'user.home'};
 3510:             $cfile = $resurl;
 3511:             if ($env{'form.forceedit'}) {
 3512:                 $forceview = 1;
 3513:             } else {
 3514:                 $forceedit = 1;
 3515:             }
 3516:             return ($cfile,$home,$switchserver,$forceedit,$forceview);
 3517:         } else {
 3518:             return;
 3519:         }
 3520:     }
 3521: 
 3522:     if ($env{'request.course.id'}) {
 3523:         my $crsedit = &Apache::lonnet::allowed('mdc',$env{'request.course.id'});
 3524:         if ($group ne '') {
 3525: # if this is a group homepage or group bulletin board, check group privs
 3526:             my $allowed = 0;
 3527:             if ($resurl =~ m{^/?adm/$cdom/$cnum/$group/smppg$}) {
 3528:                 if ((&allowed('mdg',$env{'request.course.id'}.
 3529:                               ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
 3530:                         (&allowed('mgh',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
 3531:                     $allowed = 1;
 3532:                 }
 3533:             } elsif ($resurl =~ m{^/?adm/$cdom/$cnum/\d+/bulletinboard$}) {
 3534:                 if ((&allowed('mdg',$env{'request.course.id'}.($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
 3535:                         (&allowed('cgb',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
 3536:                     $allowed = 1;
 3537:                 }
 3538:             }
 3539:             if ($allowed) {
 3540:                 $home=&homeserver($cnum,$cdom);
 3541:                 if ($env{'form.forceedit'}) {
 3542:                     $forceview = 1;
 3543:                 } else {
 3544:                     $forceedit = 1;
 3545:                 }
 3546:                 $cfile = $resurl;
 3547:             } else {
 3548:                 return;
 3549:             }
 3550:         } else {
 3551:             if ($resurl =~ m{^/?adm/viewclasslist$}) {
 3552:                 unless (&Apache::lonnet::allowed('opa',$env{'request.course.id'})) {
 3553:                     return;
 3554:                 }
 3555:             } elsif (!$crsedit) {
 3556: #
 3557: # No edit allowed where CC has switched to student role.
 3558: #
 3559:                 return;
 3560:             }
 3561:         }
 3562:     }
 3563: 
 3564:     if ($file ne '') {
 3565:         if (($cnum =~ /$match_courseid/) && ($cdom =~ /$match_domain/)) {
 3566:             if (&is_course_upload($file,$cnum,$cdom)) {
 3567:                 $uploaded = 1;
 3568:                 $incourse = 1;
 3569:                 if ($file =~/\.(htm|html|css|js|txt)$/) {
 3570:                     $cfile = &hreflocation('',$file);
 3571:                     if ($env{'form.forceedit'}) {
 3572:                         $forceview = 1;
 3573:                     } else {
 3574:                         $forceedit = 1;
 3575:                     }
 3576:                 }
 3577:             } elsif ($resurl =~ m{^/public/$cdom/$cnum/syllabus}) {
 3578:                 $incourse = 1;
 3579:                 if ($env{'form.forceedit'}) {
 3580:                     $forceview = 1;
 3581:                 } else {
 3582:                     $forceedit = 1;
 3583:                 }
 3584:                 $cfile = $resurl;
 3585:             } elsif (($resurl ne '') && (&is_on_map($resurl))) { 
 3586:                 if ($resurl =~ m{^/adm/$match_domain/$match_username/\d+/smppg|bulletinboard$}) {
 3587:                     $incourse = 1;
 3588:                     if ($env{'form.forceedit'}) {
 3589:                         $forceview = 1;
 3590:                     } else {
 3591:                         $forceedit = 1;
 3592:                     }
 3593:                     $cfile = $resurl;
 3594:                 } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem') {
 3595:                     $incourse = 1;
 3596:                     $cfile = $resurl.'/smpedit';
 3597:                 } elsif ($resurl =~ m{^/adm/wrapper/ext/}) {
 3598:                     $incourse = 1;
 3599:                     if ($env{'form.forceedit'}) {
 3600:                         $forceview = 1;
 3601:                     } else {
 3602:                         $forceedit = 1;
 3603:                     }
 3604:                     $cfile = $resurl;
 3605:                 } elsif ($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/ext\.tool$}) {
 3606:                     $incourse = 1;
 3607:                     if ($env{'form.forceedit'}) {
 3608:                         $forceview = 1;
 3609:                     } else {
 3610:                         $forceedit = 1;
 3611:                     }
 3612:                     $cfile = $resurl;
 3613:                 } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
 3614:                     $incourse = 1;
 3615:                     if ($env{'form.forceedit'}) {
 3616:                         $forceview = 1;
 3617:                     } else {
 3618:                         $forceedit = 1;
 3619:                     }
 3620:                     $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
 3621:                 }
 3622:             } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem/smpedit') {
 3623:                 my $template = '/res/lib/templates/simpleproblem.problem';
 3624:                 if (&is_on_map($template)) { 
 3625:                     $incourse = 1;
 3626:                     $forceview = 1;
 3627:                     $cfile = $template;
 3628:                 }
 3629:             } elsif (($resurl =~ m{^/adm/wrapper/ext/}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
 3630:                     $incourse = 1;
 3631:                     if ($env{'form.forceedit'}) {
 3632:                         $forceview = 1;
 3633:                     } else {
 3634:                         $forceedit = 1;
 3635:                     }
 3636:                     $cfile = $resurl;
 3637:             } elsif (($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/ext\.tool$}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
 3638:                 $incourse = 1;
 3639:                 if ($env{'form.forceedit'}) {
 3640:                     $forceview = 1;
 3641:                 } else {
 3642:                     $forceedit = 1;
 3643:                 }
 3644:                 $cfile = $resurl;
 3645:             } elsif (($resurl eq '/adm/extresedit') && ($symb || $env{'form.folderpath'})) {
 3646:                 $incourse = 1;
 3647:                 $forceview = 1;
 3648:                 if ($symb) {
 3649:                     my ($map,$id,$res)=&decode_symb($symb);
 3650:                     $env{'request.symb'} = $symb;
 3651:                     $cfile = &clutter($res);
 3652:                 } else {
 3653:                     $cfile = $env{'form.suppurl'};
 3654:                     my $escfile = &unescape($cfile);
 3655:                     if ($escfile =~ m{^/adm/$cdom/$cnum/\d+/ext\.tool$}) {
 3656:                         $cfile = '/adm/wrapper'.$escfile;
 3657:                     } else {
 3658:                         $escfile =~ s{^http://}{};
 3659:                         $cfile = &escape("/adm/wrapper/ext/$escfile");
 3660:                     }
 3661:                 }
 3662:             } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
 3663:                 if ($env{'form.forceedit'}) {
 3664:                     $forceview = 1;
 3665:                 } else {
 3666:                     $forceedit = 1;
 3667:                 }
 3668:                 $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
 3669:             }
 3670:         }
 3671:         if ($uploaded || $incourse) {
 3672:             $home=&homeserver($cnum,$cdom);
 3673:         } elsif ($file !~ m{/$}) {
 3674:             $file=~s{^(priv/$match_domain/$match_username)}{/$1};
 3675:             $file=~s{^($match_domain/$match_username)}{/priv/$1};
 3676:             # Check that the user has permission to edit this resource
 3677:             my $setpriv = 1;
 3678:             my ($cfuname,$cfudom)=&constructaccess($file,$setpriv);
 3679:             if (defined($cfudom)) {
 3680:                 $home=&homeserver($cfuname,$cfudom);
 3681:                 $cfile=$file;
 3682:             }
 3683:         }
 3684:         if (($cfile ne '') && (!$incourse || $uploaded) && 
 3685:             (($home ne '') && ($home ne 'no_host'))) {
 3686:             my @ids=&current_machine_ids();
 3687:             unless (grep(/^\Q$home\E$/,@ids)) {
 3688:                 $switchserver=1;
 3689:             }
 3690:         }
 3691:     }
 3692:     return ($cfile,$home,$switchserver,$forceedit,$forceview);
 3693: }
 3694: 
 3695: sub is_course_upload {
 3696:     my ($file,$cnum,$cdom) = @_;
 3697:     my $uploadpath = &LONCAPA::propath($cdom,$cnum);
 3698:     $uploadpath =~ s{^\/}{};
 3699:     if (($file =~ m{^\Q$uploadpath\E/userfiles/(docs|supplemental)/}) ||
 3700:         ($file =~ m{^userfiles/\Q$cdom\E/\Q$cnum\E/(docs|supplemental)/})) {
 3701:         return 1;
 3702:     }
 3703:     return;
 3704: }
 3705: 
 3706: sub in_course {
 3707:     my ($udom,$uname,$cdom,$cnum,$type,$hideprivileged) = @_;
 3708:     if ($hideprivileged) {
 3709:         my $skipuser;
 3710:         my %coursehash = &coursedescription($cdom.'_'.$cnum);
 3711:         my @possdoms = ($cdom);  
 3712:         if ($coursehash{'checkforpriv'}) { 
 3713:             push(@possdoms,split(/,/,$coursehash{'checkforpriv'})); 
 3714:         }
 3715:         if (&privileged($uname,$udom,\@possdoms)) {
 3716:             $skipuser = 1;
 3717:             if ($coursehash{'nothideprivileged'}) {
 3718:                 foreach my $item (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 3719:                     my $user;
 3720:                     if ($item =~ /:/) {
 3721:                         $user = $item;
 3722:                     } else {
 3723:                         $user = join(':',split(/[\@]/,$item));
 3724:                     }
 3725:                     if ($user eq $uname.':'.$udom) {
 3726:                         undef($skipuser);
 3727:                         last;
 3728:                     }
 3729:                 }
 3730:             }
 3731:             if ($skipuser) {
 3732:                 return 0;
 3733:             }
 3734:         }
 3735:     }
 3736:     $type ||= 'any';
 3737:     if (!defined($cdom) || !defined($cnum)) {
 3738:         my $cid  = $env{'request.course.id'};
 3739:         $cdom = $env{'course.'.$cid.'.domain'};
 3740:         $cnum = $env{'course.'.$cid.'.num'};
 3741:     }
 3742:     my $typesref;
 3743:     if (($type eq 'any') || ($type eq 'all')) {
 3744:         $typesref = ['active','previous','future'];
 3745:     } elsif ($type eq 'previous' || $type eq 'future') {
 3746:         $typesref = [$type];
 3747:     }
 3748:     my %roles = &get_my_roles($uname,$udom,'userroles',
 3749:                               $typesref,undef,[$cdom]);
 3750:     my ($tmp) = keys(%roles);
 3751:     return 0 if ($tmp =~ /^(con_lost|error|no_such_host)/i);
 3752:     my @course_roles = grep(/^\Q$cnum\E:\Q$cdom\E:/, keys(%roles));
 3753:     if (@course_roles > 0) {
 3754:         return 1;
 3755:     }
 3756:     return 0;
 3757: }
 3758: 
 3759: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
 3760: # input: action, courseID, current domain, intended
 3761: #        path to file, source of file, instruction to parse file for objects,
 3762: #        ref to hash for embedded objects,
 3763: #        ref to hash for codebase of java objects.
 3764: #        reference to scalar to accommodate mime type determined
 3765: #          from File::MMagic if $parser = parse.
 3766: #
 3767: # output: url to file (if action was uploaddoc), 
 3768: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
 3769: #
 3770: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
 3771: # course.
 3772: #
 3773: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 3774: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
 3775: #          course's home server.
 3776: #
 3777: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
 3778: #          be copied from $source (current location) to 
 3779: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 3780: #         and will then be copied to
 3781: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
 3782: #         course's home server.
 3783: #
 3784: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 3785: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
 3786: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 3787: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
 3788: #         in course's home server.
 3789: #
 3790: 
 3791: sub process_coursefile {
 3792:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
 3793:         $mimetype)=@_;
 3794:     my $fetchresult;
 3795:     my $home=&homeserver($docuname,$docudom);
 3796:     if ($action eq 'propagate') {
 3797:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 3798: 			     $home);
 3799:     } else {
 3800:         my $fpath = '';
 3801:         my $fname = $file;
 3802:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 3803:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 3804:         my $filepath = &build_filepath($fpath);
 3805:         if ($action eq 'copy') {
 3806:             if ($source eq '') {
 3807:                 $fetchresult = 'no source file';
 3808:                 return $fetchresult;
 3809:             } else {
 3810:                 my $destination = $filepath.'/'.$fname;
 3811:                 rename($source,$destination);
 3812:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 3813:                                  $home);
 3814:             }
 3815:         } elsif ($action eq 'uploaddoc') {
 3816:             open(my $fh,'>',$filepath.'/'.$fname);
 3817:             print $fh $env{'form.'.$source};
 3818:             close($fh);
 3819:             if ($parser eq 'parse') {
 3820:                 my $mm = new File::MMagic;
 3821:                 my $type = $mm->checktype_filename($filepath.'/'.$fname);
 3822:                 if ($type eq 'text/html') {
 3823:                     my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
 3824:                     unless ($parse_result eq 'ok') {
 3825:                         &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
 3826:                     }
 3827:                 }
 3828:                 if (ref($mimetype)) {
 3829:                     $$mimetype = $type;
 3830:                 } 
 3831:             }
 3832:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 3833:                                  $home);
 3834:             if ($fetchresult eq 'ok') {
 3835:                 return '/uploaded/'.$fpath.'/'.$fname;
 3836:             } else {
 3837:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 3838:                         ' to host '.$home.': '.$fetchresult);
 3839:                 return '/adm/notfound.html';
 3840:             }
 3841:         }
 3842:     }
 3843:     unless ( $fetchresult eq 'ok') {
 3844:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 3845:              ' to host '.$home.': '.$fetchresult);
 3846:     }
 3847:     return $fetchresult;
 3848: }
 3849: 
 3850: sub build_filepath {
 3851:     my ($fpath) = @_;
 3852:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
 3853:     unless ($fpath eq '') {
 3854:         my @parts=split('/',$fpath);
 3855:         foreach my $part (@parts) {
 3856:             $filepath.= '/'.$part;
 3857:             if ((-e $filepath)!=1) {
 3858:                 mkdir($filepath,0777);
 3859:             }
 3860:         }
 3861:     }
 3862:     return $filepath;
 3863: }
 3864: 
 3865: sub store_edited_file {
 3866:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
 3867:     my $file = $primary_url;
 3868:     $file =~ s#^/uploaded/$docudom/$docuname/##;
 3869:     my $fpath = '';
 3870:     my $fname = $file;
 3871:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 3872:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 3873:     my $filepath = &build_filepath($fpath);
 3874:     open(my $fh,'>',$filepath.'/'.$fname);
 3875:     print $fh $content;
 3876:     close($fh);
 3877:     my $home=&homeserver($docuname,$docudom);
 3878:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 3879: 			  $home);
 3880:     if ($$fetchresult eq 'ok') {
 3881:         return '/uploaded/'.$fpath.'/'.$fname;
 3882:     } else {
 3883:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 3884: 		 ' to host '.$home.': '.$$fetchresult);
 3885:         return '/adm/notfound.html';
 3886:     }
 3887: }
 3888: 
 3889: sub clean_filename {
 3890:     my ($fname,$args)=@_;
 3891: # Replace Windows backslashes by forward slashes
 3892:     $fname=~s/\\/\//g;
 3893:     if (!$args->{'keep_path'}) {
 3894:         # Get rid of everything but the actual filename
 3895: 	$fname=~s/^.*\/([^\/]+)$/$1/;
 3896:     }
 3897: # Replace spaces by underscores
 3898:     $fname=~s/\s+/\_/g;
 3899: # Transliterate non-ascii text to ascii
 3900:     my $lang = &Apache::lonlocal::current_language();
 3901:     $fname = &LONCAPA::transliterate::fname_to_ascii($fname,$lang);
 3902: # Replace all other weird characters by nothing
 3903:     $fname=~s{[^/\w\.\-]}{}g;
 3904: # Replace all .\d. sequences with _\d. so they no longer look like version
 3905: # numbers
 3906:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
 3907:     return $fname;
 3908: }
 3909: 
 3910: # This Function checks if an Image's dimensions exceed either $resizewidth (width) 
 3911: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an 
 3912: # image with the same aspect ratio as the original, but with dimensions which do 
 3913: # not exceed $resizewidth and $resizeheight.
 3914:  
 3915: sub resizeImage {
 3916:     my ($img_path,$resizewidth,$resizeheight) = @_;
 3917:     my $ima = Image::Magick->new;
 3918:     my $resized;
 3919:     if (-e $img_path) {
 3920:         $ima->Read($img_path);
 3921:         if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
 3922:             my $width = $ima->Get('width');
 3923:             my $height = $ima->Get('height');
 3924:             if ($width > $resizewidth) {
 3925: 	        my $factor = $width/$resizewidth;
 3926:                 my $newheight = $height/$factor;
 3927:                 $ima->Scale(width=>$resizewidth,height=>$newheight);
 3928:                 $resized = 1;
 3929:             }
 3930:         }
 3931:         if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
 3932:             my $width = $ima->Get('width');
 3933:             my $height = $ima->Get('height');
 3934:             if ($height > $resizeheight) {
 3935:                 my $factor = $height/$resizeheight;
 3936:                 my $newwidth = $width/$factor;
 3937:                 $ima->Scale(width=>$newwidth,height=>$resizeheight);
 3938:                 $resized = 1;
 3939:             }
 3940:         }
 3941:         if ($resized) {
 3942:             $ima->Write($img_path);
 3943:         }
 3944:     }
 3945:     return;
 3946: }
 3947: 
 3948: # --------------- Take an uploaded file and put it into the userfiles directory
 3949: # input: $formname - the contents of the file are in $env{"form.$formname"}
 3950: #                    the desired filename is in $env{"form.$formname.filename"}
 3951: #        $context - possible values: coursedoc, existingfile, overwrite, 
 3952: #                                    canceloverwrite, scantron or ''.
 3953: #                   if 'coursedoc': upload to the current course
 3954: #                   if 'existingfile': write file to tmp/overwrites directory 
 3955: #                   if 'canceloverwrite': delete file written to tmp/overwrites directory
 3956: #                   $context is passed as argument to &finishuserfileupload
 3957: #        $subdir - directory in userfile to store the file into
 3958: #        $parser - instruction to parse file for objects ($parser = parse) or
 3959: #                  if context is 'scantron', $parser is hashref of csv column mapping
 3960: #                  (e.g.,{ PaperID => 0, LastName => 1, FirstName => 2, ID => 3, 
 3961: #                          Section => 4, CODE => 5, FirstQuestion => 9 }).
 3962: #        $allfiles - reference to hash for embedded objects
 3963: #        $codebase - reference to hash for codebase of java objects
 3964: #        $desuname - username for permanent storage of uploaded file
 3965: #        $dsetudom - domain for permanaent storage of uploaded file
 3966: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
 3967: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
 3968: #        $resizewidth - width (pixels) to which to resize uploaded image
 3969: #        $resizeheight - height (pixels) to which to resize uploaded image
 3970: #        $mimetype - reference to scalar to accommodate mime type determined
 3971: #                    from File::MMagic.
 3972: # 
 3973: # output: url of file in userspace, or error: <message> 
 3974: #             or /adm/notfound.html if failure to upload occurse
 3975: 
 3976: sub userfileupload {
 3977:     my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
 3978:         $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
 3979:     if (!defined($subdir)) { $subdir='unknown'; }
 3980:     my $fname=$env{'form.'.$formname.'.filename'};
 3981:     $fname=&clean_filename($fname);
 3982:     # See if there is anything left
 3983:     unless ($fname) { return 'error: no uploaded file'; }
 3984:     # If filename now begins with a . prepend unix timestamp _ milliseconds
 3985:     if ($fname =~ /^\./) {
 3986:         my ($s,$usec) = &gettimeofday();
 3987:         while (length($usec) < 6) {
 3988:             $usec = '0'.$usec;
 3989:         }
 3990:         $fname = $s.'_'.substr($usec,0,3).$fname;
 3991:     }
 3992:     # Files uploaded to help request form, or uploaded to "create course" page are handled differently
 3993:     if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
 3994:         (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
 3995:          ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
 3996:         my $now = time;
 3997:         my $filepath;
 3998:         if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
 3999:              $filepath = 'tmp/helprequests/'.$now;
 4000:         } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
 4001:              $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
 4002:                          '_'.$env{'user.domain'}.'/pending';
 4003:         } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
 4004:             my ($docuname,$docudom);
 4005:             if ($destudom =~ /^$match_domain$/) {
 4006:                 $docudom = $destudom;
 4007:             } else {
 4008:                 $docudom = $env{'user.domain'};
 4009:             }
 4010:             if ($destuname =~ /^$match_username$/) {
 4011:                 $docuname = $destuname;
 4012:             } else {
 4013:                 $docuname = $env{'user.name'};
 4014:             }
 4015:             if (exists($env{'form.group'})) {
 4016:                 $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 4017:                 $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 4018:             }
 4019:             $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
 4020:             if ($context eq 'canceloverwrite') {
 4021:                 my $tempfile =  $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
 4022:                 if (-e  $tempfile) {
 4023:                     my @info = stat($tempfile);
 4024:                     if ($info[9] eq $env{'form.timestamp'}) {
 4025:                         unlink($tempfile);
 4026:                     }
 4027:                 }
 4028:                 return;
 4029:             }
 4030:         }
 4031:         # Create the directory if not present
 4032:         my @parts=split(/\//,$filepath);
 4033:         my $fullpath = $perlvar{'lonDaemons'};
 4034:         for (my $i=0;$i<@parts;$i++) {
 4035:             $fullpath .= '/'.$parts[$i];
 4036:             if ((-e $fullpath)!=1) {
 4037:                 mkdir($fullpath,0777);
 4038:             }
 4039:         }
 4040:         open(my $fh,'>',$fullpath.'/'.$fname);
 4041:         print $fh $env{'form.'.$formname};
 4042:         close($fh);
 4043:         if ($context eq 'existingfile') {
 4044:             my @info = stat($fullpath.'/'.$fname);
 4045:             return ($fullpath.'/'.$fname,$info[9]);
 4046:         } else {
 4047:             return $fullpath.'/'.$fname;
 4048:         }
 4049:     }
 4050:     if ($subdir eq 'scantron') {
 4051:         $fname = 'scantron_orig_'.$fname;
 4052:     } else {
 4053:         $fname="$subdir/$fname";
 4054:     }
 4055:     if ($context eq 'coursedoc') {
 4056: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 4057: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 4058:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
 4059:             return &finishuserfileupload($docuname,$docudom,
 4060: 					 $formname,$fname,$parser,$allfiles,
 4061: 					 $codebase,$thumbwidth,$thumbheight,
 4062:                                          $resizewidth,$resizeheight,$context,$mimetype);
 4063:         } else {
 4064:             if ($env{'form.folder'}) {
 4065:                 $fname=$env{'form.folder'}.'/'.$fname;
 4066:             }
 4067:             return &process_coursefile('uploaddoc',$docuname,$docudom,
 4068: 				       $fname,$formname,$parser,
 4069: 				       $allfiles,$codebase,$mimetype);
 4070:         }
 4071:     } elsif (defined($destuname)) {
 4072:         my $docuname=$destuname;
 4073:         my $docudom=$destudom;
 4074: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
 4075: 				     $parser,$allfiles,$codebase,
 4076:                                      $thumbwidth,$thumbheight,
 4077:                                      $resizewidth,$resizeheight,$context,$mimetype);
 4078:     } else {
 4079:         my $docuname=$env{'user.name'};
 4080:         my $docudom=$env{'user.domain'};
 4081:         if ((exists($env{'form.group'})) || ($context eq 'syllabus')) {
 4082:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 4083:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 4084:         }
 4085: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
 4086: 				     $parser,$allfiles,$codebase,
 4087:                                      $thumbwidth,$thumbheight,
 4088:                                      $resizewidth,$resizeheight,$context,$mimetype);
 4089:     }
 4090: }
 4091: 
 4092: sub finishuserfileupload {
 4093:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
 4094:         $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
 4095:     my $path=$docudom.'/'.$docuname.'/';
 4096:     my $filepath=$perlvar{'lonDocRoot'};
 4097:   
 4098:     my ($fnamepath,$file,$fetchthumb);
 4099:     $file=$fname;
 4100:     if ($fname=~m|/|) {
 4101:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
 4102: 	$path.=$fnamepath.'/';
 4103:     }
 4104:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
 4105:     my $count;
 4106:     for ($count=4;$count<=$#parts;$count++) {
 4107:         $filepath.="/$parts[$count]";
 4108:         if ((-e $filepath)!=1) {
 4109: 	    mkdir($filepath,0777);
 4110:         }
 4111:     }
 4112: 
 4113: # Save the file
 4114:     {
 4115: 	if (!open(FH,'>',$filepath.'/'.$file)) {
 4116: 	    &logthis('Failed to create '.$filepath.'/'.$file);
 4117: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
 4118: 	    return '/adm/notfound.html';
 4119: 	}
 4120:         if ($context eq 'overwrite') {
 4121:             my $source =  LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
 4122:             my $target = $filepath.'/'.$file;
 4123:             if (-e $source) {
 4124:                 my @info = stat($source);
 4125:                 if ($info[9] eq $env{'form.timestamp'}) {   
 4126:                     unless (&File::Copy::move($source,$target)) {
 4127:                         &logthis('Failed to overwrite '.$filepath.'/'.$file);
 4128:                         return "Moving from $source failed";
 4129:                     }
 4130:                 } else {
 4131:                     return "Temporary file: $source had unexpected date/time for last modification";
 4132:                 }
 4133:             } else {
 4134:                 return "Temporary file: $source missing";
 4135:             }
 4136:         } elsif (!print FH ($env{'form.'.$formname})) {
 4137: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
 4138: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
 4139: 	    return '/adm/notfound.html';
 4140: 	}
 4141: 	close(FH);
 4142:         if ($resizewidth && $resizeheight) {
 4143:             my $mm = new File::MMagic;
 4144:             my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
 4145:             if ($mime_type =~ m{^image/}) {
 4146: 	        &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
 4147:             }  
 4148: 	}
 4149:     }
 4150:     if (($context eq 'coursedoc') || ($parser eq 'parse')) {
 4151:         if (ref($mimetype)) {
 4152:             if ($$mimetype eq '') {
 4153:                 my $mm = new File::MMagic;
 4154:                 my $type = $mm->checktype_filename($filepath.'/'.$file);
 4155:                 $$mimetype = $type;
 4156:             }
 4157:         }
 4158:     }
 4159:     if (($context ne 'scantron') && ($parser eq 'parse')) {
 4160:         if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
 4161:             my $parse_result = &extract_embedded_items($filepath.'/'.$file,
 4162:                                                        $allfiles,$codebase);
 4163:             unless ($parse_result eq 'ok') {
 4164:                 &logthis('Failed to parse '.$filepath.$file.
 4165: 	   	         ' for embedded media: '.$parse_result); 
 4166:             }
 4167:         }
 4168:     } elsif (($context eq 'scantron') && (ref($parser) eq 'HASH')) {
 4169:         my $format = $env{'form.scantron_format'};
 4170:         &bubblesheet_converter($docudom,$filepath.'/'.$file,$parser,$format);
 4171:     }
 4172:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
 4173:         my $input = $filepath.'/'.$file;
 4174:         my $output = $filepath.'/'.'tn-'.$file;
 4175:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
 4176:         my @args = ('convert','-sample',$thumbsize,$input,$output);
 4177:         system({$args[0]} @args);
 4178:         if (-e $filepath.'/'.'tn-'.$file) {
 4179:             $fetchthumb  = 1; 
 4180:         }
 4181:     }
 4182:  
 4183: # Notify homeserver to grep it
 4184: #
 4185:     my $docuhome=&homeserver($docuname,$docudom);	
 4186:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
 4187:     if ($fetchresult eq 'ok') {
 4188:         if ($fetchthumb) {
 4189:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
 4190:             if ($thumbresult ne 'ok') {
 4191:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
 4192:                          $docuhome.': '.$thumbresult);
 4193:             }
 4194:         }
 4195: #
 4196: # Return the URL to it
 4197:         return '/uploaded/'.$path.$file;
 4198:     } else {
 4199:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
 4200: 		 ': '.$fetchresult);
 4201:         return '/adm/notfound.html';
 4202:     }
 4203: }
 4204: 
 4205: sub extract_embedded_items {
 4206:     my ($fullpath,$allfiles,$codebase,$content) = @_;
 4207:     my @state = ();
 4208:     my (%lastids,%related,%shockwave,%flashvars);
 4209:     my %javafiles = (
 4210:                       codebase => '',
 4211:                       code => '',
 4212:                       archive => ''
 4213:                     );
 4214:     my %mediafiles = (
 4215:                       src => '',
 4216:                       movie => '',
 4217:                      );
 4218:     my $p;
 4219:     if ($content) {
 4220:         $p = HTML::LCParser->new($content);
 4221:     } else {
 4222:         $p = HTML::LCParser->new($fullpath);
 4223:     }
 4224:     while (my $t=$p->get_token()) {
 4225: 	if ($t->[0] eq 'S') {
 4226: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
 4227: 	    push(@state, $tagname);
 4228:             if (lc($tagname) eq 'allow') {
 4229:                 &add_filetype($allfiles,$attr->{'src'},'src');
 4230:             }
 4231: 	    if (lc($tagname) eq 'img') {
 4232: 		&add_filetype($allfiles,$attr->{'src'},'src');
 4233: 	    }
 4234: 	    if (lc($tagname) eq 'a') {
 4235:                 unless (($attr->{'href'} =~ /^#/) || ($attr->{'href'} eq '')) {
 4236:                     &add_filetype($allfiles,$attr->{'href'},'href');
 4237:                 }
 4238: 	    }
 4239:             if (lc($tagname) eq 'script') {
 4240:                 my $src;
 4241:                 if ($attr->{'archive'} =~ /\.jar$/i) {
 4242:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
 4243:                 } else {
 4244:                     if ($attr->{'src'} ne '') {
 4245:                         $src = $attr->{'src'};
 4246:                         &add_filetype($allfiles,$src,'src');
 4247:                     }
 4248:                 }
 4249:                 my $text = $p->get_trimmed_text();
 4250:                 if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
 4251:                     my @swfargs = split(/,/,$1);
 4252:                     foreach my $item (@swfargs) {
 4253:                         $item =~ s/["']//g;
 4254:                         $item =~ s/^\s+//;
 4255:                         $item =~ s/\s+$//;
 4256:                     }
 4257:                     if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
 4258:                         if (ref($related{$swfargs[0]}) eq 'ARRAY') {
 4259:                             push(@{$related{$swfargs[0]}},$swfargs[2]);
 4260:                         } else {
 4261:                             $related{$swfargs[0]} = [$swfargs[2]];
 4262:                         }
 4263:                     }
 4264:                 }
 4265:             }
 4266:             if (lc($tagname) eq 'link') {
 4267:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
 4268:                     &add_filetype($allfiles,$attr->{'href'},'href');
 4269:                 }
 4270:             }
 4271: 	    if (lc($tagname) eq 'object' ||
 4272: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
 4273: 		foreach my $item (keys(%javafiles)) {
 4274: 		    $javafiles{$item} = '';
 4275: 		}
 4276:                 if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
 4277:                     $lastids{lc($tagname)} = $attr->{'id'};
 4278:                 }
 4279: 	    }
 4280: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
 4281: 		my $name = lc($attr->{'name'});
 4282: 		foreach my $item (keys(%javafiles)) {
 4283: 		    if ($name eq $item) {
 4284: 			$javafiles{$item} = $attr->{'value'};
 4285: 			last;
 4286: 		    }
 4287: 		}
 4288:                 my $pathfrom;
 4289: 		foreach my $item (keys(%mediafiles)) {
 4290: 		    if ($name eq $item) {
 4291:                         $pathfrom = $attr->{'value'};
 4292:                         $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
 4293: 			&add_filetype($allfiles,$pathfrom,$name);
 4294: 			last;
 4295: 		    }
 4296: 		}
 4297:                 if ($name eq 'flashvars') {
 4298:                     $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
 4299:                 }
 4300:                 if ($pathfrom ne '') {
 4301:                     &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
 4302:                                          $pathfrom);
 4303:                 }
 4304: 	    }
 4305: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
 4306: 		foreach my $item (keys(%javafiles)) {
 4307: 		    if ($attr->{$item}) {
 4308: 			$javafiles{$item} = $attr->{$item};
 4309: 			last;
 4310: 		    }
 4311: 		}
 4312: 		foreach my $item (keys(%mediafiles)) {
 4313: 		    if ($attr->{$item}) {
 4314: 			&add_filetype($allfiles,$attr->{$item},$item);
 4315: 			last;
 4316: 		    }
 4317: 		}
 4318:                 if (lc($tagname) eq 'embed') {
 4319:                     if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
 4320:                         &embedded_dependency($allfiles,\%related,$attr->{'name'},
 4321:                                              $attr->{'src'});
 4322:                     }
 4323:                 }
 4324: 	    }
 4325:             if (lc($tagname) eq 'iframe') {
 4326:                 my $src = $attr->{'src'} ;
 4327:                 if (($src ne '') && ($src !~ m{^(/|https?://)})) {
 4328:                     &add_filetype($allfiles,$src,'src');
 4329:                 } elsif ($src =~ m{^/}) {
 4330:                     if ($env{'request.course.id'}) {
 4331:                         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 4332:                         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 4333:                         my $url = &hreflocation('',$fullpath);
 4334:                         if ($url =~ m{^/uploaded/$cdom/$cnum/docs/(\w+/\d+)/}) {
 4335:                             my $relpath = $1;
 4336:                             if ($src =~ m{^/uploaded/$cdom/$cnum/docs/\Q$relpath\E/(.+)$}) {
 4337:                                 &add_filetype($allfiles,$1,'src');
 4338:                             }
 4339:                         }
 4340:                     }
 4341:                 }
 4342:             }
 4343:             if ($t->[4] =~ m{/>$}) {
 4344:                 pop(@state);
 4345:             }
 4346: 	} elsif ($t->[0] eq 'E') {
 4347: 	    my ($tagname) = ($t->[1]);
 4348: 	    if ($javafiles{'codebase'} ne '') {
 4349: 		$javafiles{'codebase'} .= '/';
 4350: 	    }  
 4351: 	    if (lc($tagname) eq 'applet' ||
 4352: 		lc($tagname) eq 'object' ||
 4353: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
 4354: 		) {
 4355: 		foreach my $item (keys(%javafiles)) {
 4356: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
 4357: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
 4358: 			&add_filetype($allfiles,$file,$item);
 4359: 		    }
 4360: 		}
 4361: 	    } 
 4362: 	    pop @state;
 4363: 	}
 4364:     }
 4365:     foreach my $id (sort(keys(%flashvars))) {
 4366:         if ($shockwave{$id} ne '') {
 4367:             my @pairs = split(/\&/,$flashvars{$id});
 4368:             foreach my $pair (@pairs) {
 4369:                 my ($key,$value) = split(/\=/,$pair);
 4370:                 if ($key eq 'thumb') {
 4371:                     &add_filetype($allfiles,$value,$key);
 4372:                 } elsif ($key eq 'content') {
 4373:                     my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
 4374:                     my ($ext) = ($value =~ /\.([^.]+)$/);
 4375:                     if ($ext ne '') {
 4376:                         &add_filetype($allfiles,$path.$value,$ext);
 4377:                     }
 4378:                 }
 4379:             }
 4380:         }
 4381:     }
 4382:     return 'ok';
 4383: }
 4384: 
 4385: sub add_filetype {
 4386:     my ($allfiles,$file,$type)=@_;
 4387:     if (exists($allfiles->{$file})) {
 4388: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
 4389: 	    push(@{$allfiles->{$file}}, &escape($type));
 4390: 	}
 4391:     } else {
 4392: 	@{$allfiles->{$file}} = (&escape($type));
 4393:     }
 4394: }
 4395: 
 4396: sub embedded_dependency {
 4397:     my ($allfiles,$related,$identifier,$pathfrom) = @_;
 4398:     if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
 4399:         if (($identifier ne '') &&
 4400:             (ref($related->{$identifier}) eq 'ARRAY') &&
 4401:             ($pathfrom ne '')) {
 4402:             my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
 4403:             foreach my $dep (@{$related->{$identifier}}) {
 4404:                 &add_filetype($allfiles,$path.$dep,'object');
 4405:             }
 4406:         }
 4407:     }
 4408:     return;
 4409: }
 4410: 
 4411: sub bubblesheet_converter {
 4412:     my ($cdom,$fullpath,$config,$format) = @_;
 4413:     if ((&domain($cdom) ne '') &&
 4414:         ($fullpath =~ m{^\Q$perlvar{'lonDocRoot'}/userfiles/$cdom/\E$match_courseid/scantron_orig}) &&
 4415:         (-e $fullpath) && (ref($config) eq 'HASH') && ($format ne '')) {
 4416:         my (%csvcols,%csvoptions);
 4417:         if (ref($config->{'fields'}) eq 'HASH') {  
 4418:             %csvcols = %{$config->{'fields'}};
 4419:         }
 4420:         if (ref($config->{'options'}) eq 'HASH') {
 4421:             %csvoptions = %{$config->{'options'}};
 4422:         }
 4423:         my %csvbynum = reverse(%csvcols);
 4424:         my %scantronconf = &get_scantron_config($format,$cdom);
 4425:         if (keys(%scantronconf)) {
 4426:             my %bynum = (
 4427:                           $scantronconf{CODEstart} => 'CODEstart',
 4428:                           $scantronconf{IDstart}   => 'IDstart',
 4429:                           $scantronconf{PaperID}   => 'PaperID',
 4430:                           $scantronconf{FirstName} => 'FirstName',
 4431:                           $scantronconf{LastName}  => 'LastName',
 4432:                           $scantronconf{Qstart}    => 'Qstart',
 4433:                         );
 4434:             my @ordered;
 4435:             foreach my $item (sort { $a <=> $b } keys(%bynum)) {
 4436:                 push(@ordered,$bynum{$item});
 4437:             }
 4438:             my %mapstart = (
 4439:                               CODEstart => 'CODE',
 4440:                               IDstart   => 'ID',
 4441:                               PaperID   => 'PaperID',
 4442:                               FirstName => 'FirstName',
 4443:                               LastName  => 'LastName',
 4444:                               Qstart    => 'FirstQuestion',
 4445:                            );
 4446:             my %maplength = (
 4447:                               CODEstart => 'CODElength',
 4448:                               IDstart   => 'IDlength',
 4449:                               PaperID   => 'PaperIDlength',
 4450:                               FirstName => 'FirstNamelength',
 4451:                               LastName  => 'LastNamelength',
 4452:             );
 4453:             if (open(my $fh,'<',$fullpath)) {
 4454:                 my $output;
 4455:                 my %lettdig = &letter_to_digits();
 4456:                 my %diglett = reverse(%lettdig);
 4457:                 my $numletts = scalar(keys(%lettdig));
 4458:                 my $num = 0;
 4459:                 while (my $line=<$fh>) {
 4460:                     $num ++;
 4461:                     next if (($num == 1) && ($csvoptions{'hdr'} == 1));
 4462:                     $line =~ s{[\r\n]+$}{};
 4463:                     my %found;
 4464:                     my @values = split(/,/,$line);
 4465:                     my ($qstart,$record);
 4466:                     for (my $i=0; $i<@values; $i++) {
 4467:                         if ((($qstart ne '') && ($i > $qstart)) ||
 4468:                             ($csvbynum{$i} eq 'FirstQuestion')) {
 4469:                             if ($values[$i] eq '') {
 4470:                                 $values[$i] = $scantronconf{'Qoff'};
 4471:                             } elsif ($scantronconf{'Qon'} eq 'number') {
 4472:                                 if ($values[$i] =~ /^[A-Ja-j]$/) {
 4473:                                     $values[$i] = $lettdig{uc($values[$i])};
 4474:                                 }
 4475:                             } elsif ($scantronconf{'Qon'} eq 'letter') {
 4476:                                 if ($values[$i] =~ /^[0-9]$/) {
 4477:                                     $values[$i] = $diglett{$values[$i]};
 4478:                                 }
 4479:                             } else {
 4480:                                 if ($values[$i] =~ /^[0-9A-Ja-j]$/) {
 4481:                                     my $digit;
 4482:                                     if ($values[$i] =~ /^[A-Ja-j]$/) {
 4483:                                         $digit = $lettdig{uc($values[$i])}-1;
 4484:                                         if ($values[$i] eq 'J') {
 4485:                                             $digit += $numletts;
 4486:                                         }
 4487:                                     } elsif ($values[$i] =~ /^[0-9]$/) {
 4488:                                         $digit = $values[$i]-1;
 4489:                                         if ($values[$i] eq '0') {
 4490:                                             $digit += $numletts;
 4491:                                         }
 4492:                                     }
 4493:                                     my $qval='';
 4494:                                     for (my $j=0; $j<$scantronconf{'Qlength'}; $j++) {
 4495:                                         if ($j == $digit) {
 4496:                                             $qval .= $scantronconf{'Qon'};
 4497:                                         } else {
 4498:                                             $qval .= $scantronconf{'Qoff'};
 4499:                                         }
 4500:                                     }
 4501:                                     $values[$i] = $qval;
 4502:                                 }
 4503:                             }
 4504:                             if (length($values[$i]) > $scantronconf{'Qlength'}) {
 4505:                                 $values[$i] = substr($values[$i],0,$scantronconf{'Qlength'});
 4506:                             }
 4507:                             my $numblank = $scantronconf{'Qlength'} - length($values[$i]);
 4508:                             if ($numblank > 0) {
 4509:                                  $values[$i] .= ($scantronconf{'Qoff'} x $numblank);
 4510:                             }
 4511:                             if ($csvbynum{$i} eq 'FirstQuestion') {
 4512:                                 $qstart = $i;
 4513:                                 $found{$csvbynum{$i}} = $values[$i];
 4514:                             } else {
 4515:                                 $found{'FirstQuestion'} .= $values[$i];
 4516:                             }
 4517:                         } elsif (exists($csvbynum{$i})) {
 4518:                             if ($csvoptions{'rem'}) {
 4519:                                 $values[$i] =~ s/^\s+//;
 4520:                             }
 4521:                             if (($csvbynum{$i} eq 'PaperID') && ($csvoptions{'pad'})) {
 4522:                                 while (length($values[$i]) < $scantronconf{$maplength{$csvbynum{$i}}}) {
 4523:                                     $values[$i] = '0'.$values[$i];
 4524:                                 }
 4525:                             }
 4526:                             $found{$csvbynum{$i}} = $values[$i];
 4527:                         }
 4528:                     }
 4529:                     foreach my $item (@ordered) {
 4530:                         my $currlength = 1+length($record);
 4531:                         my $numspaces = $scantronconf{$item} - $currlength;
 4532:                         if ($numspaces > 0) {
 4533:                             $record .= (' ' x $numspaces);
 4534:                         }
 4535:                         if (($mapstart{$item} ne '') && (exists($found{$mapstart{$item}}))) {
 4536:                             unless ($item eq 'Qstart') {
 4537:                                 if (length($found{$mapstart{$item}}) > $scantronconf{$maplength{$item}}) {
 4538:                                     $found{$mapstart{$item}} = substr($found{$mapstart{$item}},0,$scantronconf{$maplength{$item}});
 4539:                                 }
 4540:                             }
 4541:                             $record .= $found{$mapstart{$item}};
 4542:                         }
 4543:                     }
 4544:                     $output .= "$record\n";
 4545:                 }
 4546:                 close($fh);
 4547:                 if ($output) {
 4548:                     if (open(my $fh,'>',$fullpath)) {
 4549:                         print $fh $output;
 4550:                         close($fh);
 4551:                     }
 4552:                 }
 4553:             }
 4554:         }
 4555:         return;
 4556:     }
 4557: }
 4558: 
 4559: sub letter_to_digits {
 4560:     my %lettdig = (
 4561:                     A => 1,
 4562:                     B => 2,
 4563:                     C => 3,
 4564:                     D => 4,
 4565:                     E => 5,
 4566:                     F => 6,
 4567:                     G => 7,
 4568:                     H => 8,
 4569:                     I => 9,
 4570:                     J => 0,
 4571:                   );
 4572:     return %lettdig;
 4573: }
 4574: 
 4575: sub get_scantron_config {
 4576:     my ($which,$cdom) = @_;
 4577:     my @lines = &get_scantronformat_file($cdom);
 4578:     my %config;
 4579:     #FIXME probably should move to XML it has already gotten a bit much now
 4580:     foreach my $line (@lines) {
 4581:         my ($name,$descrip)=split(/:/,$line);
 4582:         if ($name ne $which ) { next; }
 4583:         chomp($line);
 4584:         my @config=split(/:/,$line);
 4585:         $config{'name'}=$config[0];
 4586:         $config{'description'}=$config[1];
 4587:         $config{'CODElocation'}=$config[2];
 4588:         $config{'CODEstart'}=$config[3];
 4589:         $config{'CODElength'}=$config[4];
 4590:         $config{'IDstart'}=$config[5];
 4591:         $config{'IDlength'}=$config[6];
 4592:         $config{'Qstart'}=$config[7];
 4593:         $config{'Qlength'}=$config[8];
 4594:         $config{'Qoff'}=$config[9];
 4595:         $config{'Qon'}=$config[10];
 4596:         $config{'PaperID'}=$config[11];
 4597:         $config{'PaperIDlength'}=$config[12];
 4598:         $config{'FirstName'}=$config[13];
 4599:         $config{'FirstNamelength'}=$config[14];
 4600:         $config{'LastName'}=$config[15];
 4601:         $config{'LastNamelength'}=$config[16];
 4602:         $config{'BubblesPerRow'}=$config[17];
 4603:         last;
 4604:     }
 4605:     return %config;
 4606: }
 4607: 
 4608: sub get_scantronformat_file {
 4609:     my ($cdom) = @_;
 4610:     if ($cdom eq '') {
 4611:         $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
 4612:     }
 4613:     my %domconfig = &get_dom('configuration',['scantron'],$cdom);
 4614:     my $gottab = 0;
 4615:     my @lines;
 4616:     if (ref($domconfig{'scantron'}) eq 'HASH') {
 4617:         if ($domconfig{'scantron'}{'scantronformat'} ne '') {
 4618:             my $formatfile = &getfile($perlvar{'lonDocRoot'}.$domconfig{'scantron'}{'scantronformat'});
 4619:             if ($formatfile ne '-1') {
 4620:                 @lines = split("\n",$formatfile,-1);
 4621:                 $gottab = 1;
 4622:             }
 4623:         }
 4624:     }
 4625:     if (!$gottab) {
 4626:         my $confname = $cdom.'-domainconfig';
 4627:         my $default = $perlvar{'lonDocRoot'}.'/res/'.$cdom.'/'.$confname.'/default.tab';
 4628:         my $formatfile = &getfile($default);
 4629:         if ($formatfile ne '-1') {
 4630:             @lines = split("\n",$formatfile,-1);
 4631:             $gottab = 1;
 4632:         }
 4633:     }
 4634:     if (!$gottab) {
 4635:         my @domains = &current_machine_domains();
 4636:         if (grep(/^\Q$cdom\E$/,@domains)) {
 4637:             if (open(my $fh,'<',$perlvar{'lonTabDir'}.'/scantronformat.tab')) {
 4638:                 @lines = <$fh>;
 4639:                 close($fh);
 4640:             }
 4641:         } else {
 4642:             if (open(my $fh,'<',$perlvar{'lonTabDir'}.'/default_scantronformat.tab')) {
 4643:                 @lines = <$fh>;
 4644:                 close($fh);
 4645:             }
 4646:         }
 4647:     }
 4648:     return @lines;
 4649: }
 4650: 
 4651: sub removeuploadedurl {
 4652:     my ($url)=@_;	
 4653:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);    
 4654:     return &removeuserfile($uname,$udom,$fname);
 4655: }
 4656: 
 4657: sub removeuserfile {
 4658:     my ($docuname,$docudom,$fname)=@_;
 4659:     my $home=&homeserver($docuname,$docudom);    
 4660:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
 4661:     if ($result eq 'ok') {	
 4662:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
 4663:             my $metafile = $fname.'.meta';
 4664:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
 4665: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
 4666:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];	   
 4667:             my $sqlresult = 
 4668:                 &update_portfolio_table($docuname,$docudom,$file,
 4669:                                         'portfolio_metadata',$group,
 4670:                                         'delete');
 4671:         }
 4672:     }
 4673:     return $result;
 4674: }
 4675: 
 4676: sub mkdiruserfile {
 4677:     my ($docuname,$docudom,$dir)=@_;
 4678:     my $home=&homeserver($docuname,$docudom);
 4679:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
 4680: }
 4681: 
 4682: sub renameuserfile {
 4683:     my ($docuname,$docudom,$old,$new)=@_;
 4684:     my $home=&homeserver($docuname,$docudom);
 4685:     my $result = &reply("renameuserfile:$docudom:$docuname:".
 4686:                         &escape("$old").':'.&escape("$new"),$home);
 4687:     if ($result eq 'ok') {
 4688:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
 4689:             my $oldmeta = $old.'.meta';
 4690:             my $newmeta = $new.'.meta';
 4691:             my $metaresult = 
 4692:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
 4693: 	    my $url = "/uploaded/$docudom/$docuname/$old";
 4694:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
 4695:             my $sqlresult = 
 4696:                 &update_portfolio_table($docuname,$docudom,$file,
 4697:                                         'portfolio_metadata',$group,
 4698:                                         'delete');
 4699:         }
 4700:     }
 4701:     return $result;
 4702: }
 4703: 
 4704: # ------------------------------------------------------------------------- Log
 4705: 
 4706: sub log {
 4707:     my ($dom,$nam,$hom,$what)=@_;
 4708:     return critical("log:$dom:$nam:$what",$hom);
 4709: }
 4710: 
 4711: # ------------------------------------------------------------------ Course Log
 4712: #
 4713: # This routine flushes several buffers of non-mission-critical nature
 4714: #
 4715: 
 4716: sub flushcourselogs {
 4717:     &logthis('Flushing log buffers');
 4718: #
 4719: # course logs
 4720: # This is a log of all transactions in a course, which can be used
 4721: # for data mining purposes
 4722: #
 4723: # It also collects the courseid database, which lists last transaction
 4724: # times and course titles for all courseids
 4725: #
 4726:     my %courseidbuffer=();
 4727:     foreach my $crsid (keys(%courselogs)) {
 4728:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
 4729: 		          &escape($courselogs{$crsid}),
 4730: 		          $coursehombuf{$crsid}) eq 'ok') {
 4731: 	    delete $courselogs{$crsid};
 4732:         } else {
 4733:             &logthis('Failed to flush log buffer for '.$crsid);
 4734:             if (length($courselogs{$crsid})>40000) {
 4735:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
 4736:                         " exceeded maximum size, deleting.</font>");
 4737:                delete $courselogs{$crsid};
 4738:             }
 4739:         }
 4740:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
 4741:             'description' => $coursedescrbuf{$crsid},
 4742:             'inst_code'    => $courseinstcodebuf{$crsid},
 4743:             'type'        => $coursetypebuf{$crsid},
 4744:             'owner'       => $courseownerbuf{$crsid},
 4745:         };
 4746:     }
 4747: #
 4748: # Write course id database (reverse lookup) to homeserver of courses 
 4749: # Is used in pickcourse
 4750: #
 4751:     foreach my $crs_home (keys(%courseidbuffer)) {
 4752:         my $response = &courseidput(&host_domain($crs_home),
 4753:                                     $courseidbuffer{$crs_home},
 4754:                                     $crs_home,'timeonly');
 4755:     }
 4756: #
 4757: # File accesses
 4758: # Writes to the dynamic metadata of resources to get hit counts, etc.
 4759: #
 4760:     foreach my $entry (keys(%accesshash)) {
 4761:         if ($entry =~ /___count$/) {
 4762:             my ($dom,$name);
 4763:             ($dom,$name,undef)=
 4764: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
 4765:             if (! defined($dom) || $dom eq '' || 
 4766:                 ! defined($name) || $name eq '') {
 4767:                 my $cid = $env{'request.course.id'};
 4768:                 $dom  = $env{'request.'.$cid.'.domain'};
 4769:                 $name = $env{'request.'.$cid.'.num'};
 4770:             }
 4771:             my $value = $accesshash{$entry};
 4772:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
 4773:             my %temphash=($url => $value);
 4774:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
 4775:             if ($result eq 'ok') {
 4776:                 delete $accesshash{$entry};
 4777:             }
 4778:         } else {
 4779:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
 4780:             if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
 4781:             my %temphash=($entry => $accesshash{$entry});
 4782:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
 4783:                 delete $accesshash{$entry};
 4784:             }
 4785:         }
 4786:     }
 4787: #
 4788: # Roles
 4789: # Reverse lookup of user roles for course faculty/staff and co-authorship
 4790: #
 4791:     foreach my $entry (keys(%userrolehash)) {
 4792:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
 4793: 	    split(/\:/,$entry);
 4794:         if (&Apache::lonnet::put('nohist_userroles',
 4795:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
 4796:                 $rudom,$runame) eq 'ok') {
 4797: 	    delete $userrolehash{$entry};
 4798:         }
 4799:     }
 4800: #
 4801: # Reverse lookup of domain roles (dc, ad, li, sc, dh, da, au)
 4802: #
 4803:     my %domrolebuffer = ();
 4804:     foreach my $entry (keys(%domainrolehash)) {
 4805:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
 4806:         if ($domrolebuffer{$rudom}) {
 4807:             $domrolebuffer{$rudom}.='&'.&escape($entry).
 4808:                       '='.&escape($domainrolehash{$entry});
 4809:         } else {
 4810:             $domrolebuffer{$rudom}.=&escape($entry).
 4811:                       '='.&escape($domainrolehash{$entry});
 4812:         }
 4813:         delete $domainrolehash{$entry};
 4814:     }
 4815:     foreach my $dom (keys(%domrolebuffer)) {
 4816: 	my %servers;
 4817: 	if (defined(&domain($dom,'primary'))) {
 4818: 	    my $primary=&domain($dom,'primary');
 4819: 	    my $hostname=&hostname($primary);
 4820: 	    $servers{$primary} = $hostname;
 4821: 	} else { 
 4822: 	    %servers = &get_servers($dom,'library');
 4823: 	}
 4824: 	foreach my $tryserver (keys(%servers)) {
 4825: 	    if (&reply('domroleput:'.$dom.':'.
 4826: 		       $domrolebuffer{$dom},$tryserver) eq 'ok') {
 4827: 		last;
 4828: 	    } else {  
 4829: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
 4830: 	    }
 4831:         }
 4832:     }
 4833:     $dumpcount++;
 4834: }
 4835: 
 4836: sub courselog {
 4837:     my $what=shift;
 4838:     $what=time.':'.$what;
 4839:     unless ($env{'request.course.id'}) { return ''; }
 4840:     $coursedombuf{$env{'request.course.id'}}=
 4841:        $env{'course.'.$env{'request.course.id'}.'.domain'};
 4842:     $coursenumbuf{$env{'request.course.id'}}=
 4843:        $env{'course.'.$env{'request.course.id'}.'.num'};
 4844:     $coursehombuf{$env{'request.course.id'}}=
 4845:        $env{'course.'.$env{'request.course.id'}.'.home'};
 4846:     $coursedescrbuf{$env{'request.course.id'}}=
 4847:        $env{'course.'.$env{'request.course.id'}.'.description'};
 4848:     $courseinstcodebuf{$env{'request.course.id'}}=
 4849:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
 4850:     $courseownerbuf{$env{'request.course.id'}}=
 4851:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
 4852:     $coursetypebuf{$env{'request.course.id'}}=
 4853:        $env{'course.'.$env{'request.course.id'}.'.type'};
 4854:     if (defined $courselogs{$env{'request.course.id'}}) {
 4855: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
 4856:     } else {
 4857: 	$courselogs{$env{'request.course.id'}}.=$what;
 4858:     }
 4859:     if (length($courselogs{$env{'request.course.id'}})>4048) {
 4860: 	&flushcourselogs();
 4861:     }
 4862: }
 4863: 
 4864: sub courseacclog {
 4865:     my $fnsymb=shift;
 4866:     unless ($env{'request.course.id'}) { return ''; }
 4867:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
 4868:     if ($fnsymb=~/$LONCAPA::assess_re/) {
 4869:         $what.=':POST';
 4870:         # FIXME: Probably ought to escape things....
 4871: 	foreach my $key (keys(%env)) {
 4872:             if ($key=~/^form\.(.*)/) {
 4873:                 my $formitem = $1;
 4874:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
 4875:                     $what.=':'.$formitem.'='.$env{$key};
 4876:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
 4877:                     $what.=':'.$formitem.'='.$env{$key};
 4878:                 }
 4879:             }
 4880:         }
 4881:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
 4882:         # FIXME: We should not be depending on a form parameter that someone
 4883:         # editing lonsearchcat.pm might change in the future.
 4884:         if ($env{'form.phase'} eq 'course_search') {
 4885:             $what.= ':POST';
 4886:             # FIXME: Probably ought to escape things....
 4887:             foreach my $element ('courseexp','crsfulltext','crsrelated',
 4888:                                  'crsdiscuss') {
 4889:                 $what.=':'.$element.'='.$env{'form.'.$element};
 4890:             }
 4891:         }
 4892:     }
 4893:     &courselog($what);
 4894: }
 4895: 
 4896: sub countacc {
 4897:     my $url=&declutter(shift);
 4898:     return if (! defined($url) || $url eq '');
 4899:     unless ($env{'request.course.id'}) { return ''; }
 4900: #
 4901: # Mark that this url was used in this course
 4902: #
 4903:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
 4904: #
 4905: # Increase the access count for this resource in this child process
 4906: #
 4907:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
 4908:     $accesshash{$key}++;
 4909: }
 4910: 
 4911: sub linklog {
 4912:     my ($from,$to)=@_;
 4913:     $from=&declutter($from);
 4914:     $to=&declutter($to);
 4915:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
 4916:     $accesshash{$to.'___'.$from.'___goto'}=1;
 4917: }
 4918: 
 4919: sub statslog {
 4920:     my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
 4921:     if ($users<2) { return; }
 4922:     my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
 4923:             'course'       => $env{'request.course.id'},
 4924:             'sections'     => '"all"',
 4925:             'num_students' => $users,
 4926:             'part'         => $part,
 4927:             'symb'         => $symb,
 4928:             'mean_tries'   => $av_attempts,
 4929:             'deg_of_diff'  => $degdiff});
 4930:     foreach my $key (keys(%dynstore)) {
 4931:         $accesshash{$key}=$dynstore{$key};
 4932:     }
 4933: }
 4934:   
 4935: sub userrolelog {
 4936:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
 4937:     if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
 4938:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 4939:        $userrolehash
 4940:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 4941:                     =$tend.':'.$tstart;
 4942:     }
 4943:     if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
 4944:        $userrolehash
 4945:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
 4946:                     =$tend.':'.$tstart;
 4947:     }
 4948:     if ($trole =~ /^(dc|ad|li|au|dg|sc|dh|da)/ ) {
 4949:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 4950:        $domainrolehash
 4951:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 4952:                     = $tend.':'.$tstart;
 4953:     }
 4954: }
 4955: 
 4956: sub courserolelog {
 4957:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
 4958:     if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
 4959:         my $cdom = $1;
 4960:         my $cnum = $2;
 4961:         my $sec = $3;
 4962:         my $namespace = 'rolelog';
 4963:         my %storehash = (
 4964:                            role    => $trole,
 4965:                            start   => $tstart,
 4966:                            end     => $tend,
 4967:                            selfenroll => $selfenroll,
 4968:                            context    => $context,
 4969:                         );
 4970:         if ($trole eq 'gr') {
 4971:             $namespace = 'groupslog';
 4972:             $storehash{'group'} = $sec;
 4973:         } else {
 4974:             $storehash{'section'} = $sec;
 4975:         }
 4976:         &write_log('course',$namespace,\%storehash,$delflag,$username,
 4977:                    $domain,$cnum,$cdom);
 4978:         if (($trole ne 'st') || ($sec ne '')) {
 4979:             &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
 4980:         }
 4981:     }
 4982:     return;
 4983: }
 4984: 
 4985: sub domainrolelog {
 4986:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
 4987:     if ($area =~ m{^/($match_domain)/$}) {
 4988:         my $cdom = $1;
 4989:         my $domconfiguser = &Apache::lonnet::get_domainconfiguser($cdom);
 4990:         my $namespace = 'rolelog';
 4991:         my %storehash = (
 4992:                            role    => $trole,
 4993:                            start   => $tstart,
 4994:                            end     => $tend,
 4995:                            context => $context,
 4996:                         );
 4997:         &write_log('domain',$namespace,\%storehash,$delflag,$username,
 4998:                    $domain,$domconfiguser,$cdom);
 4999:     }
 5000:     return;
 5001: 
 5002: }
 5003: 
 5004: sub coauthorrolelog {
 5005:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
 5006:     if ($area =~ m{^/($match_domain)/($match_username)$}) {
 5007:         my $audom = $1;
 5008:         my $auname = $2;
 5009:         my $namespace = 'rolelog';
 5010:         my %storehash = (
 5011:                            role    => $trole,
 5012:                            start   => $tstart,
 5013:                            end     => $tend,
 5014:                            context => $context,
 5015:                         );
 5016:         &write_log('author',$namespace,\%storehash,$delflag,$username,
 5017:                    $domain,$auname,$audom);
 5018:     }
 5019:     return;
 5020: }
 5021: 
 5022: sub get_course_adv_roles {
 5023:     my ($cid,$codes) = @_;
 5024:     $cid=$env{'request.course.id'} unless (defined($cid));
 5025:     my %coursehash=&coursedescription($cid);
 5026:     my $crstype = &Apache::loncommon::course_type($cid);
 5027:     my %nothide=();
 5028:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 5029:         if ($user !~ /:/) {
 5030: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
 5031:         } else {
 5032:             $nothide{$user}=1;
 5033:         }
 5034:     }
 5035:     my @possdoms = ($coursehash{'domain'});
 5036:     if ($coursehash{'checkforpriv'}) {
 5037:         push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
 5038:     }
 5039:     my %returnhash=();
 5040:     my %dumphash=
 5041:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
 5042:     my $now=time;
 5043:     my %privileged;
 5044:     foreach my $entry (keys(%dumphash)) {
 5045: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
 5046:         if (($tstart) && ($tstart<0)) { next; }
 5047:         if (($tend) && ($tend<$now)) { next; }
 5048:         if (($tstart) && ($now<$tstart)) { next; }
 5049:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
 5050: 	if ($username eq '' || $domain eq '') { next; }
 5051:         if ((&privileged($username,$domain,\@possdoms)) &&
 5052:             (!$nothide{$username.':'.$domain})) { next; }
 5053: 	if ($role eq 'cr') { next; }
 5054:         if ($codes) {
 5055:             if ($section) { $role .= ':'.$section; }
 5056:             if ($returnhash{$role}) {
 5057:                 $returnhash{$role}.=','.$username.':'.$domain;
 5058:             } else {
 5059:                 $returnhash{$role}=$username.':'.$domain;
 5060:             }
 5061:         } else {
 5062:             my $key=&plaintext($role,$crstype);
 5063:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
 5064:             if ($returnhash{$key}) {
 5065: 	        $returnhash{$key}.=','.$username.':'.$domain;
 5066:             } else {
 5067:                 $returnhash{$key}=$username.':'.$domain;
 5068:             }
 5069:         }
 5070:     }
 5071:     return %returnhash;
 5072: }
 5073: 
 5074: sub get_my_roles {
 5075:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
 5076:     unless (defined($uname)) { $uname=$env{'user.name'}; }
 5077:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
 5078:     my (%dumphash,%nothide);
 5079:     if ($context eq 'userroles') {
 5080:         %dumphash = &dump('roles',$udom,$uname);
 5081:     } else {
 5082:         %dumphash = &dump('nohist_userroles',$udom,$uname);
 5083:         if ($hidepriv) {
 5084:             my %coursehash=&coursedescription($udom.'_'.$uname);
 5085:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 5086:                 if ($user !~ /:/) {
 5087:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
 5088:                 } else {
 5089:                     $nothide{$user} = 1;
 5090:                 }
 5091:             }
 5092:         }
 5093:     }
 5094:     my %returnhash=();
 5095:     my $now=time;
 5096:     my %privileged;
 5097:     foreach my $entry (keys(%dumphash)) {
 5098:         my ($role,$tend,$tstart);
 5099:         if ($context eq 'userroles') {
 5100:             next if ($entry =~ /^rolesdef/);
 5101: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
 5102:         } else {
 5103:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
 5104:         }
 5105:         if (($tstart) && ($tstart<0)) { next; }
 5106:         my $status = 'active';
 5107:         if (($tend) && ($tend<=$now)) {
 5108:             $status = 'previous';
 5109:         } 
 5110:         if (($tstart) && ($now<$tstart)) {
 5111:             $status = 'future';
 5112:         }
 5113:         if (ref($types) eq 'ARRAY') {
 5114:             if (!grep(/^\Q$status\E$/,@{$types})) {
 5115:                 next;
 5116:             } 
 5117:         } else {
 5118:             if ($status ne 'active') {
 5119:                 next;
 5120:             }
 5121:         }
 5122:         my ($rolecode,$username,$domain,$section,$area);
 5123:         if ($context eq 'userroles') {
 5124:             ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
 5125:             (undef,$domain,$username,$section) = split(/\//,$area);
 5126:         } else {
 5127:             ($role,$username,$domain,$section) = split(/\:/,$entry);
 5128:         }
 5129:         if (ref($roledoms) eq 'ARRAY') {
 5130:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
 5131:                 next;
 5132:             }
 5133:         }
 5134:         if (ref($roles) eq 'ARRAY') {
 5135:             if (!grep(/^\Q$role\E$/,@{$roles})) {
 5136:                 if ($role =~ /^cr\//) {
 5137:                     if (!grep(/^cr$/,@{$roles})) {
 5138:                         next;
 5139:                     }
 5140:                 } elsif ($role =~ /^gr\//) {
 5141:                     if (!grep(/^gr$/,@{$roles})) {
 5142:                         next;
 5143:                     }
 5144:                 } else {
 5145:                     next;
 5146:                 }
 5147:             }
 5148:         }
 5149:         if ($hidepriv) {
 5150:             my @privroles = ('dc','su');
 5151:             if ($context eq 'userroles') {
 5152:                 next if (grep(/^\Q$role\E$/,@privroles));
 5153:             } else {
 5154:                 my $possdoms = [$domain];
 5155:                 if (ref($roledoms) eq 'ARRAY') {
 5156:                    push(@{$possdoms},@{$roledoms}); 
 5157:                 }
 5158:                 if (&privileged($username,$domain,$possdoms,\@privroles)) {
 5159:                     if (!$nothide{$username.':'.$domain}) {
 5160:                         next;
 5161:                     }
 5162:                 }
 5163:             }
 5164:         }
 5165:         if ($withsec) {
 5166:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
 5167:                 $tstart.':'.$tend;
 5168:         } else {
 5169:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
 5170:         }
 5171:     }
 5172:     return %returnhash;
 5173: }
 5174: 
 5175: sub get_all_adhocroles {
 5176:     my ($dom) = @_;
 5177:     my @roles_by_num = ();
 5178:     my %domdefaults = &get_domain_defaults($dom);
 5179:     my (%description,%access_in_dom,%access_info);
 5180:     if (ref($domdefaults{'adhocroles'}) eq 'HASH') {
 5181:         my $count = 0;
 5182:         my %domcurrent = %{$domdefaults{'adhocroles'}};
 5183:         my %ordered;
 5184:         foreach my $role (sort(keys(%domcurrent))) {
 5185:             my ($order,$desc,$access_in_dom);
 5186:             if (ref($domcurrent{$role}) eq 'HASH') {
 5187:                 $order = $domcurrent{$role}{'order'};
 5188:                 $desc = $domcurrent{$role}{'desc'};
 5189:                 $access_in_dom{$role} = $domcurrent{$role}{'access'};
 5190:                 $access_info{$role} = $domcurrent{$role}{$access_in_dom{$role}};
 5191:             }
 5192:             if ($order eq '') {
 5193:                 $order = $count;
 5194:             }
 5195:             $ordered{$order} = $role;
 5196:             if ($desc ne '') {
 5197:                 $description{$role} = $desc;
 5198:             } else {
 5199:                 $description{$role}= $role;
 5200:             }
 5201:             $count++;
 5202:         }
 5203:         foreach my $item (sort {$a <=> $b } (keys(%ordered))) {
 5204:             push(@roles_by_num,$ordered{$item});
 5205:         }
 5206:     }
 5207:     return (\@roles_by_num,\%description,\%access_in_dom,\%access_info);
 5208: }
 5209: 
 5210: sub get_my_adhocroles {
 5211:     my ($cid,$checkreg) = @_;
 5212:     my ($cdom,$cnum,%info,@possroles,$description,$roles_by_num);
 5213:     if ($env{'request.course.id'} eq $cid) {
 5214:         $cdom = $env{'course.'.$cid.'.domain'};
 5215:         $cnum = $env{'course.'.$cid.'.num'};
 5216:         $info{'internal.coursecode'} = $env{'course.'.$cid.'.internal.coursecode'};
 5217:     } elsif ($cid =~ /^($match_domain)_($match_courseid)$/) {
 5218:         $cdom = $1;
 5219:         $cnum = $2;
 5220:         %info = &Apache::lonnet::get('environment',['internal.coursecode'],
 5221:                                      $cdom,$cnum);
 5222:     }
 5223:     if (($info{'internal.coursecode'} ne '') && ($checkreg)) {
 5224:         my $user = $env{'user.name'}.':'.$env{'user.domain'};
 5225:         my %rosterhash = &get('classlist',[$user],$cdom,$cnum);
 5226:         if ($rosterhash{$user} ne '') {
 5227:             my $type = (split(/:/,$rosterhash{$user}))[5];
 5228:             return ([],{}) if ($type eq 'auto');
 5229:         }
 5230:     }
 5231:     if (($cdom ne '') && ($cnum ne ''))  {
 5232:         if (($env{"user.role.dh./$cdom/"}) || ($env{"user.role.da./$cdom/"})) {
 5233:             my $then=$env{'user.login.time'};
 5234:             my $update=$env{'user.update.time'};
 5235:             if (!$update) {
 5236:                 $update = $then;
 5237:             }
 5238:             my @liveroles;
 5239:             foreach my $role ('dh','da') {
 5240:                 if ($env{"user.role.$role./$cdom/"}) {
 5241:                     my ($tstart,$tend)=split(/\./,$env{"user.role.$role./$cdom/"});
 5242:                     my $limit = $update;
 5243:                     if ($env{'request.role'} eq "$role./$cdom/") {
 5244:                         $limit = $then;
 5245:                     }
 5246:                     my $activerole = 1;
 5247:                     if ($tstart && $tstart>$limit) { $activerole = 0; }
 5248:                     if ($tend   && $tend  <$limit) { $activerole = 0; }
 5249:                     if ($activerole) {
 5250:                         push(@liveroles,$role);
 5251:                     }
 5252:                 }
 5253:             }
 5254:             if (@liveroles) {
 5255:                 if (&homeserver($cnum,$cdom) ne 'no_host') {
 5256:                     my ($accessref,$accessinfo,%access_in_dom);
 5257:                     ($roles_by_num,$description,$accessref,$accessinfo) = &get_all_adhocroles($cdom);
 5258:                     if (ref($roles_by_num) eq 'ARRAY') {
 5259:                         if (@{$roles_by_num}) {
 5260:                             my %settings;
 5261:                             if ($env{'request.course.id'} eq $cid) {
 5262:                                 foreach my $envkey (keys(%env)) {
 5263:                                     if ($envkey =~ /^\Qcourse.$cid.\E(internal\.adhoc.+)$/) {
 5264:                                         $settings{$1} = $env{$envkey};
 5265:                                     }
 5266:                                 }
 5267:                             } else {
 5268:                                 %settings = &dump('environment',$cdom,$cnum,'internal\.adhoc');
 5269:                             }
 5270:                             my %setincrs;
 5271:                             if ($settings{'internal.adhocaccess'}) {
 5272:                                 map { $setincrs{$_} = 1; } split(/,/,$settings{'internal.adhocaccess'});
 5273:                             }
 5274:                             my @statuses;
 5275:                             if ($env{'environment.inststatus'}) {
 5276:                                 @statuses = split(/,/,$env{'environment.inststatus'});
 5277:                             }
 5278:                             my $user = $env{'user.name'}.':'.$env{'user.domain'};
 5279:                             if (ref($accessref) eq 'HASH') {
 5280:                                 %access_in_dom = %{$accessref};
 5281:                             }
 5282:                             foreach my $role (@{$roles_by_num}) {
 5283:                                 my ($curraccess,@okstatus,@personnel);
 5284:                                 if ($setincrs{$role}) {
 5285:                                     ($curraccess,my $rest) = split(/=/,$settings{'internal.adhoc.'.$role});
 5286:                                     if ($curraccess eq 'status') {
 5287:                                         @okstatus = split(/\&/,$rest);
 5288:                                     } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
 5289:                                         @personnel = split(/\&/,$rest);
 5290:                                     }
 5291:                                 } else {
 5292:                                     $curraccess = $access_in_dom{$role};
 5293:                                     if (ref($accessinfo) eq 'HASH') {
 5294:                                         if ($curraccess eq 'status') {
 5295:                                             if (ref($accessinfo->{$role}) eq 'ARRAY') {
 5296:                                                 @okstatus = @{$accessinfo->{$role}};
 5297:                                             }
 5298:                                         } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
 5299:                                             if (ref($accessinfo->{$role}) eq 'ARRAY') {
 5300:                                                 @personnel = @{$accessinfo->{$role}};
 5301:                                             }
 5302:                                         }
 5303:                                     }
 5304:                                 }
 5305:                                 if ($curraccess eq 'none') {
 5306:                                     next;
 5307:                                 } elsif ($curraccess eq 'all') {
 5308:                                     push(@possroles,$role);
 5309:                                 } elsif ($curraccess eq 'dh') {
 5310:                                     if (grep(/^dh$/,@liveroles)) {
 5311:                                         push(@possroles,$role);
 5312:                                     } else {
 5313:                                         next;
 5314:                                     }
 5315:                                 } elsif ($curraccess eq 'da') {
 5316:                                     if (grep(/^da$/,@liveroles)) {
 5317:                                         push(@possroles,$role);
 5318:                                     } else {
 5319:                                         next;
 5320:                                     }
 5321:                                 } elsif ($curraccess eq 'status') {
 5322:                                     if (@okstatus) {
 5323:                                         if (!@statuses) {
 5324:                                             if (grep(/^default$/,@okstatus)) {
 5325:                                                 push(@possroles,$role);
 5326:                                             }
 5327:                                         } else {
 5328:                                             foreach my $status (@okstatus) {
 5329:                                                 if (grep(/^\Q$status\E$/,@statuses)) {
 5330:                                                     push(@possroles,$role);
 5331:                                                     last;
 5332:                                                 }
 5333:                                             }
 5334:                                         }
 5335:                                     }
 5336:                                 } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
 5337:                                     if (grep(/^\Q$user\E$/,@personnel)) {
 5338:                                         if ($curraccess eq 'exc') {
 5339:                                             push(@possroles,$role);
 5340:                                         }
 5341:                                     } elsif ($curraccess eq 'inc') {
 5342:                                         push(@possroles,$role);
 5343:                                     }
 5344:                                 }
 5345:                             }
 5346:                         }
 5347:                     }
 5348:                 }
 5349:             }
 5350:         }
 5351:     }
 5352:     unless (ref($description) eq 'HASH') {
 5353:         if (ref($roles_by_num) eq 'ARRAY') {
 5354:             my %desc;
 5355:             map { $desc{$_} = $_; } (@{$roles_by_num});
 5356:             $description = \%desc;
 5357:         } else {
 5358:             $description = {};
 5359:         }
 5360:     }
 5361:     return (\@possroles,$description);
 5362: }
 5363: 
 5364: # ----------------------------------------------------- Frontpage Announcements
 5365: #
 5366: #
 5367: 
 5368: sub postannounce {
 5369:     my ($server,$text)=@_;
 5370:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
 5371:     unless ($text=~/\w/) { $text=''; }
 5372:     return &reply('setannounce:'.&escape($text),$server);
 5373: }
 5374: 
 5375: sub getannounce {
 5376: 
 5377:     if (open(my $fh,"<",$perlvar{'lonDocRoot'}.'/announcement.txt')) {
 5378: 	my $announcement='';
 5379: 	while (my $line = <$fh>) { $announcement .= $line; }
 5380: 	close($fh);
 5381: 	if ($announcement=~/\w/) { 
 5382: 	    return 
 5383:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
 5384:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
 5385: 	} else {
 5386: 	    return '';
 5387: 	}
 5388:     } else {
 5389: 	return '';
 5390:     }
 5391: }
 5392: 
 5393: # ---------------------------------------------------------- Course ID routines
 5394: # Deal with domain's nohist_courseid.db files
 5395: #
 5396: 
 5397: sub courseidput {
 5398:     my ($domain,$storehash,$coursehome,$caller) = @_;
 5399:     return unless (ref($storehash) eq 'HASH');
 5400:     my $outcome;
 5401:     if ($caller eq 'timeonly') {
 5402:         my $cids = '';
 5403:         foreach my $item (keys(%$storehash)) {
 5404:             $cids.=&escape($item).'&';
 5405:         }
 5406:         $cids=~s/\&$//;
 5407:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
 5408:                           $coursehome);       
 5409:     } else {
 5410:         my $items = '';
 5411:         foreach my $item (keys(%$storehash)) {
 5412:             $items.= &escape($item).'='.
 5413:                      &freeze_escape($$storehash{$item}).'&';
 5414:         }
 5415:         $items=~s/\&$//;
 5416:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
 5417:                           $coursehome);
 5418:     }
 5419:     if ($outcome eq 'unknown_cmd') {
 5420:         my $what;
 5421:         foreach my $cid (keys(%$storehash)) {
 5422:             $what .= &escape($cid).'=';
 5423:             foreach my $item ('description','inst_code','owner','type') {
 5424:                 $what .= &escape($storehash->{$cid}{$item}).':';
 5425:             }
 5426:             $what =~ s/\:$/&/;
 5427:         }
 5428:         $what =~ s/\&$//;  
 5429:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
 5430:     } else {
 5431:         return $outcome;
 5432:     }
 5433: }
 5434: 
 5435: sub courseiddump {
 5436:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
 5437:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
 5438:         $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
 5439:         $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner,
 5440:         $hasuniquecode,$reqcrsdom,$reqinstcode)=@_;
 5441:     my $as_hash = 1;
 5442:     my %returnhash;
 5443:     if (!$domfilter) { $domfilter=''; }
 5444:     my %libserv = &all_library();
 5445:     foreach my $tryserver (keys(%libserv)) {
 5446:         if ( (  $hostidflag == 1 
 5447: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
 5448: 	     || (!defined($hostidflag)) ) {
 5449: 
 5450: 	    if (($domfilter eq '') ||
 5451: 		(&host_domain($tryserver) eq $domfilter)) {
 5452:                 my $rep;
 5453:                 if (grep { $_ eq $tryserver } current_machine_ids()) {
 5454:                     $rep = LONCAPA::Lond::dump_course_id_handler(
 5455:                         join(":", (&host_domain($tryserver), $sincefilter, 
 5456:                                 &escape($descfilter), &escape($instcodefilter), 
 5457:                                 &escape($ownerfilter), &escape($coursefilter),
 5458:                                 &escape($typefilter), &escape($regexp_ok), 
 5459:                                 $as_hash, &escape($selfenrollonly), 
 5460:                                 &escape($catfilter), $showhidden, $caller, 
 5461:                                 &escape($cloner), &escape($cc_clone), $cloneonly, 
 5462:                                 &escape($createdbefore), &escape($createdafter), 
 5463:                                 &escape($creationcontext),$domcloner,$hasuniquecode,
 5464:                                 $reqcrsdom,&escape($reqinstcode))));
 5465:                 } else {
 5466:                     $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
 5467:                              $sincefilter.':'.&escape($descfilter).':'.
 5468:                              &escape($instcodefilter).':'.&escape($ownerfilter).
 5469:                              ':'.&escape($coursefilter).':'.&escape($typefilter).
 5470:                              ':'.&escape($regexp_ok).':'.$as_hash.':'.
 5471:                              &escape($selfenrollonly).':'.&escape($catfilter).':'.
 5472:                              $showhidden.':'.$caller.':'.&escape($cloner).':'.
 5473:                              &escape($cc_clone).':'.$cloneonly.':'.
 5474:                              &escape($createdbefore).':'.&escape($createdafter).':'.
 5475:                              &escape($creationcontext).':'.$domcloner.':'.$hasuniquecode.
 5476:                              ':'.$reqcrsdom.':'.&escape($reqinstcode),$tryserver);
 5477:                 }
 5478:                      
 5479:                 my @pairs=split(/\&/,$rep);
 5480:                 foreach my $item (@pairs) {
 5481:                     my ($key,$value)=split(/\=/,$item,2);
 5482:                     $key = &unescape($key);
 5483:                     next if ($key =~ /^error: 2 /);
 5484:                     my $result = &thaw_unescape($value);
 5485:                     if (ref($result) eq 'HASH') {
 5486:                         $returnhash{$key}=$result;
 5487:                     } else {
 5488:                         my @responses = split(/:/,$value);
 5489:                         my @items = ('description','inst_code','owner','type');
 5490:                         for (my $i=0; $i<@responses; $i++) {
 5491:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
 5492:                         }
 5493:                     }
 5494:                 }
 5495:             }
 5496:         }
 5497:     }
 5498:     return %returnhash;
 5499: }
 5500: 
 5501: sub courselastaccess {
 5502:     my ($cdom,$cnum,$hostidref) = @_;
 5503:     my %returnhash;
 5504:     if ($cdom && $cnum) {
 5505:         my $chome = &homeserver($cnum,$cdom);
 5506:         if ($chome ne 'no_host') {
 5507:             my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
 5508:             &extract_lastaccess(\%returnhash,$rep);
 5509:         }
 5510:     } else {
 5511:         if (!$cdom) { $cdom=''; }
 5512:         my %libserv = &all_library();
 5513:         foreach my $tryserver (keys(%libserv)) {
 5514:             if (ref($hostidref) eq 'ARRAY') {
 5515:                 next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
 5516:             } 
 5517:             if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
 5518:                 my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
 5519:                 &extract_lastaccess(\%returnhash,$rep);
 5520:             }
 5521:         }
 5522:     }
 5523:     return %returnhash;
 5524: }
 5525: 
 5526: sub extract_lastaccess {
 5527:     my ($returnhash,$rep) = @_;
 5528:     if (ref($returnhash) eq 'HASH') {
 5529:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' || 
 5530:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
 5531:                  $rep eq '') {
 5532:             my @pairs=split(/\&/,$rep);
 5533:             foreach my $item (@pairs) {
 5534:                 my ($key,$value)=split(/\=/,$item,2);
 5535:                 $key = &unescape($key);
 5536:                 next if ($key =~ /^error: 2 /);
 5537:                 $returnhash->{$key} = &thaw_unescape($value);
 5538:             }
 5539:         }
 5540:     }
 5541:     return;
 5542: }
 5543: 
 5544: # ---------------------------------------------------------- DC e-mail
 5545: 
 5546: sub dcmailput {
 5547:     my ($domain,$msgid,$message,$server)=@_;
 5548:     my $status = &Apache::lonnet::critical(
 5549:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
 5550:        &escape($message),$server);
 5551:     return $status;
 5552: }
 5553: 
 5554: sub dcmaildump {
 5555:     my ($dom,$startdate,$enddate,$senders) = @_;
 5556:     my %returnhash=();
 5557: 
 5558:     if (defined(&domain($dom,'primary'))) {
 5559:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
 5560:                                                          &escape($enddate).':';
 5561: 	my @esc_senders=map { &escape($_)} @$senders;
 5562: 	$cmd.=&escape(join('&',@esc_senders));
 5563: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
 5564:             my ($key,$value) = split(/\=/,$line,2);
 5565:             if (($key) && ($value)) {
 5566:                 $returnhash{&unescape($key)} = &unescape($value);
 5567:             }
 5568:         }
 5569:     }
 5570:     return %returnhash;
 5571: }
 5572: # ---------------------------------------------------------- Domain roles
 5573: 
 5574: sub get_domain_roles {
 5575:     my ($dom,$roles,$startdate,$enddate)=@_;
 5576:     if ((!defined($startdate)) || ($startdate eq '')) {
 5577:         $startdate = '.';
 5578:     }
 5579:     if ((!defined($enddate)) || ($enddate eq '')) {
 5580:         $enddate = '.';
 5581:     }
 5582:     my $rolelist;
 5583:     if (ref($roles) eq 'ARRAY') {
 5584:         $rolelist = join('&',@{$roles});
 5585:     }
 5586:     my %personnel = ();
 5587: 
 5588:     my %servers = &get_servers($dom,'library');
 5589:     foreach my $tryserver (keys(%servers)) {
 5590: 	%{$personnel{$tryserver}}=();
 5591: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
 5592: 					    &escape($startdate).':'.
 5593: 					    &escape($enddate).':'.
 5594: 					    &escape($rolelist), $tryserver))) {
 5595: 	    my ($key,$value) = split(/\=/,$line,2);
 5596: 	    if (($key) && ($value)) {
 5597: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
 5598: 	    }
 5599: 	}
 5600:     }
 5601:     return %personnel;
 5602: }
 5603: 
 5604: sub get_active_domroles {
 5605:     my ($dom,$roles) = @_;
 5606:     return () unless (ref($roles) eq 'ARRAY');
 5607:     my $now = time;
 5608:     my %dompersonnel = &get_domain_roles($dom,$roles,$now,$now);
 5609:     my %domroles;
 5610:     foreach my $server (keys(%dompersonnel)) {
 5611:         foreach my $user (sort(keys(%{$dompersonnel{$server}}))) {
 5612:             my ($trole,$uname,$udom,$runame,$rudom,$rsec) = split(/:/,$user);
 5613:             $domroles{$uname.':'.$udom} = $dompersonnel{$server}{$user};
 5614:         }
 5615:     }
 5616:     return %domroles;
 5617: }
 5618: 
 5619: # ----------------------------------------------------------- Interval timing 
 5620: 
 5621: {
 5622: # Caches needed for speedup of navmaps
 5623: # We don't want to cache this for very long at all (5 seconds at most)
 5624: # 
 5625: # The user for whom we cache
 5626: my $cachedkey='';
 5627: # The cached times for this user
 5628: my %cachedtimes=();
 5629: # When this was last done
 5630: my $cachedtime='';
 5631: 
 5632: sub load_all_first_access {
 5633:     my ($uname,$udom,$ignorecache)=@_;
 5634:     if (($cachedkey eq $uname.':'.$udom) &&
 5635:         (abs($cachedtime-time)<5) && (!$env{'form.markaccess'}) &&
 5636:         (!$ignorecache)) {
 5637:         return;
 5638:     }
 5639:     $cachedtime=time;
 5640:     $cachedkey=$uname.':'.$udom;
 5641:     %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
 5642: }
 5643: 
 5644: sub get_first_access {
 5645:     my ($type,$argsymb,$argmap,$ignorecache)=@_;
 5646:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 5647:     if ($argsymb) { $symb=$argsymb; }
 5648:     my ($map,$id,$res)=&decode_symb($symb);
 5649:     if ($argmap) { $map = $argmap; }
 5650:     if ($type eq 'course') {
 5651: 	$res='course';
 5652:     } elsif ($type eq 'map') {
 5653: 	$res=&symbread($map);
 5654:     } else {
 5655: 	$res=$symb;
 5656:     }
 5657:     &load_all_first_access($uname,$udom,$ignorecache);
 5658:     return $cachedtimes{"$courseid\0$res"};
 5659: }
 5660: 
 5661: sub set_first_access {
 5662:     my ($type,$interval)=@_;
 5663:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 5664:     my ($map,$id,$res)=&decode_symb($symb);
 5665:     if ($type eq 'course') {
 5666: 	$res='course';
 5667:     } elsif ($type eq 'map') {
 5668: 	$res=&symbread($map);
 5669:     } else {
 5670: 	$res=$symb;
 5671:     }
 5672:     $cachedkey='';
 5673:     my $firstaccess=&get_first_access($type,$symb,$map);
 5674:     if ($firstaccess) {
 5675:         &logthis("First access time already set ($firstaccess) when attempting ".
 5676:                  "to set new value (type: $type, extent: $res) for $uname:$udom ".
 5677:                  "in $courseid");
 5678:         return 'already_set';
 5679:     } else {
 5680:         my $start = time;
 5681: 	my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
 5682:                           $udom,$uname);
 5683:         if ($putres eq 'ok') {
 5684:             &put('timerinterval',{"$courseid\0$res"=>$interval},
 5685:                  $udom,$uname); 
 5686:             &appenv(
 5687:                      {
 5688:                         'course.'.$courseid.'.firstaccess.'.$res   => $start,
 5689:                         'course.'.$courseid.'.timerinterval.'.$res => $interval,
 5690:                      }
 5691:                   );
 5692:             if (($cachedtime) && (abs($start-$cachedtime) < 5)) {
 5693:                 $cachedtimes{"$courseid\0$res"} = $start;
 5694:             }
 5695:         } elsif ($putres ne 'refused') {
 5696:             &logthis("Result: $putres when attempting to set first access time ".
 5697:                      "(type: $type, extent: $res) for $uname:$udom in $courseid");
 5698:         }
 5699:         return $putres;
 5700:     }
 5701:     return 'already_set';
 5702: }
 5703: }
 5704: 
 5705: # --------------------------------------------- Set Expire Date for Spreadsheet
 5706: 
 5707: sub expirespread {
 5708:     my ($uname,$udom,$stype,$usymb)=@_;
 5709:     my $cid=$env{'request.course.id'}; 
 5710:     if ($cid) {
 5711:        my $now=time;
 5712:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
 5713:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
 5714:                             $env{'course.'.$cid.'.num'}.
 5715: 	        	    ':nohist_expirationdates:'.
 5716:                             &escape($key).'='.$now,
 5717:                             $env{'course.'.$cid.'.home'})
 5718:     }
 5719:     return 'ok';
 5720: }
 5721: 
 5722: # ----------------------------------------------------- Devalidate Spreadsheets
 5723: 
 5724: sub devalidate {
 5725:     my ($symb,$uname,$udom)=@_;
 5726:     my $cid=$env{'request.course.id'}; 
 5727:     if ($cid) {
 5728:         # delete the stored spreadsheets for
 5729:         # - the student level sheet of this user in course's homespace
 5730:         # - the assessment level sheet for this resource 
 5731:         #   for this user in user's homespace
 5732: 	# - current conditional state info
 5733: 	my $key=$uname.':'.$udom.':';
 5734:         my $status=
 5735: 	    &del('nohist_calculatedsheets',
 5736: 		 [$key.'studentcalc:'],
 5737: 		 $env{'course.'.$cid.'.domain'},
 5738: 		 $env{'course.'.$cid.'.num'})
 5739: 		.' '.
 5740: 	    &del('nohist_calculatedsheets_'.$cid,
 5741: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
 5742:         unless ($status eq 'ok ok') {
 5743:            &logthis('Could not devalidate spreadsheet '.
 5744:                     $uname.' at '.$udom.' for '.
 5745: 		    $symb.': '.$status);
 5746:         }
 5747: 	&delenv('user.state.'.$cid);
 5748:     }
 5749: }
 5750: 
 5751: sub get_scalar {
 5752:     my ($string,$end) = @_;
 5753:     my $value;
 5754:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
 5755: 	$value = $1;
 5756:     } elsif ($$string =~ s/^([^&]*?)&//) {
 5757: 	$value = $1;
 5758:     }
 5759:     return &unescape($value);
 5760: }
 5761: 
 5762: sub array2str {
 5763:   my (@array) = @_;
 5764:   my $result=&arrayref2str(\@array);
 5765:   $result=~s/^__ARRAY_REF__//;
 5766:   $result=~s/__END_ARRAY_REF__$//;
 5767:   return $result;
 5768: }
 5769: 
 5770: sub arrayref2str {
 5771:   my ($arrayref) = @_;
 5772:   my $result='__ARRAY_REF__';
 5773:   foreach my $elem (@$arrayref) {
 5774:     if(ref($elem) eq 'ARRAY') {
 5775:       $result.=&arrayref2str($elem).'&';
 5776:     } elsif(ref($elem) eq 'HASH') {
 5777:       $result.=&hashref2str($elem).'&';
 5778:     } elsif(ref($elem)) {
 5779:       #print("Got a ref of ".(ref($elem))." skipping.");
 5780:     } else {
 5781:       $result.=&escape($elem).'&';
 5782:     }
 5783:   }
 5784:   $result=~s/\&$//;
 5785:   $result .= '__END_ARRAY_REF__';
 5786:   return $result;
 5787: }
 5788: 
 5789: sub hash2str {
 5790:   my (%hash) = @_;
 5791:   my $result=&hashref2str(\%hash);
 5792:   $result=~s/^__HASH_REF__//;
 5793:   $result=~s/__END_HASH_REF__$//;
 5794:   return $result;
 5795: }
 5796: 
 5797: sub hashref2str {
 5798:   my ($hashref)=@_;
 5799:   my $result='__HASH_REF__';
 5800:   foreach my $key (sort(keys(%$hashref))) {
 5801:     if (ref($key) eq 'ARRAY') {
 5802:       $result.=&arrayref2str($key).'=';
 5803:     } elsif (ref($key) eq 'HASH') {
 5804:       $result.=&hashref2str($key).'=';
 5805:     } elsif (ref($key)) {
 5806:       $result.='=';
 5807:       #print("Got a ref of ".(ref($key))." skipping.");
 5808:     } else {
 5809: 	if (defined($key)) {$result.=&escape($key).'=';} else { last; }
 5810:     }
 5811: 
 5812:     if(ref($hashref->{$key}) eq 'ARRAY') {
 5813:       $result.=&arrayref2str($hashref->{$key}).'&';
 5814:     } elsif(ref($hashref->{$key}) eq 'HASH') {
 5815:       $result.=&hashref2str($hashref->{$key}).'&';
 5816:     } elsif(ref($hashref->{$key})) {
 5817:        $result.='&';
 5818:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
 5819:     } else {
 5820:       $result.=&escape($hashref->{$key}).'&';
 5821:     }
 5822:   }
 5823:   $result=~s/\&$//;
 5824:   $result .= '__END_HASH_REF__';
 5825:   return $result;
 5826: }
 5827: 
 5828: sub str2hash {
 5829:     my ($string)=@_;
 5830:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
 5831:     return %$hash;
 5832: }
 5833: 
 5834: sub str2hashref {
 5835:   my ($string) = @_;
 5836: 
 5837:   my %hash;
 5838: 
 5839:   if($string !~ /^__HASH_REF__/) {
 5840:       if (! ($string eq '' || !defined($string))) {
 5841: 	  $hash{'error'}='Not hash reference';
 5842:       }
 5843:       return (\%hash, $string);
 5844:   }
 5845: 
 5846:   $string =~ s/^__HASH_REF__//;
 5847: 
 5848:   while($string !~ /^__END_HASH_REF__/) {
 5849:       #key
 5850:       my $key='';
 5851:       if($string =~ /^__HASH_REF__/) {
 5852:           ($key, $string)=&str2hashref($string);
 5853:           if(defined($key->{'error'})) {
 5854:               $hash{'error'}='Bad data';
 5855:               return (\%hash, $string);
 5856:           }
 5857:       } elsif($string =~ /^__ARRAY_REF__/) {
 5858:           ($key, $string)=&str2arrayref($string);
 5859:           if($key->[0] eq 'Array reference error') {
 5860:               $hash{'error'}='Bad data';
 5861:               return (\%hash, $string);
 5862:           }
 5863:       } else {
 5864:           $string =~ s/^(.*?)=//;
 5865: 	  $key=&unescape($1);
 5866:       }
 5867:       $string =~ s/^=//;
 5868: 
 5869:       #value
 5870:       my $value='';
 5871:       if($string =~ /^__HASH_REF__/) {
 5872:           ($value, $string)=&str2hashref($string);
 5873:           if(defined($value->{'error'})) {
 5874:               $hash{'error'}='Bad data';
 5875:               return (\%hash, $string);
 5876:           }
 5877:       } elsif($string =~ /^__ARRAY_REF__/) {
 5878:           ($value, $string)=&str2arrayref($string);
 5879:           if($value->[0] eq 'Array reference error') {
 5880:               $hash{'error'}='Bad data';
 5881:               return (\%hash, $string);
 5882:           }
 5883:       } else {
 5884: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
 5885:       }
 5886:       $string =~ s/^&//;
 5887: 
 5888:       $hash{$key}=$value;
 5889:   }
 5890: 
 5891:   $string =~ s/^__END_HASH_REF__//;
 5892: 
 5893:   return (\%hash, $string);
 5894: }
 5895: 
 5896: sub str2array {
 5897:     my ($string)=@_;
 5898:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
 5899:     return @$array;
 5900: }
 5901: 
 5902: sub str2arrayref {
 5903:   my ($string) = @_;
 5904:   my @array;
 5905: 
 5906:   if($string !~ /^__ARRAY_REF__/) {
 5907:       if (! ($string eq '' || !defined($string))) {
 5908: 	  $array[0]='Array reference error';
 5909:       }
 5910:       return (\@array, $string);
 5911:   }
 5912: 
 5913:   $string =~ s/^__ARRAY_REF__//;
 5914: 
 5915:   while($string !~ /^__END_ARRAY_REF__/) {
 5916:       my $value='';
 5917:       if($string =~ /^__HASH_REF__/) {
 5918:           ($value, $string)=&str2hashref($string);
 5919:           if(defined($value->{'error'})) {
 5920:               $array[0] ='Array reference error';
 5921:               return (\@array, $string);
 5922:           }
 5923:       } elsif($string =~ /^__ARRAY_REF__/) {
 5924:           ($value, $string)=&str2arrayref($string);
 5925:           if($value->[0] eq 'Array reference error') {
 5926:               $array[0] ='Array reference error';
 5927:               return (\@array, $string);
 5928:           }
 5929:       } else {
 5930: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
 5931:       }
 5932:       $string =~ s/^&//;
 5933: 
 5934:       push(@array, $value);
 5935:   }
 5936: 
 5937:   $string =~ s/^__END_ARRAY_REF__//;
 5938: 
 5939:   return (\@array, $string);
 5940: }
 5941: 
 5942: # -------------------------------------------------------------------Temp Store
 5943: 
 5944: sub tmpreset {
 5945:   my ($symb,$namespace,$domain,$stuname) = @_;
 5946:   if (!$symb) {
 5947:     $symb=&symbread();
 5948:     if (!$symb) { $symb= $env{'request.url'}; }
 5949:   }
 5950:   $symb=escape($symb);
 5951: 
 5952:   if (!$namespace) { $namespace=$env{'request.state'}; }
 5953:   $namespace=~s/\//\_/g;
 5954:   $namespace=~s/\W//g;
 5955: 
 5956:   if (!$domain) { $domain=$env{'user.domain'}; }
 5957:   if (!$stuname) { $stuname=$env{'user.name'}; }
 5958:   if ($domain eq 'public' && $stuname eq 'public') {
 5959:       $stuname=$ENV{'REMOTE_ADDR'};
 5960:   }
 5961:   my $path=LONCAPA::tempdir();
 5962:   my %hash;
 5963:   if (tie(%hash,'GDBM_File',
 5964: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 5965: 	  &GDBM_WRCREAT(),0640)) {
 5966:     foreach my $key (keys(%hash)) {
 5967:       if ($key=~ /:$symb/) {
 5968: 	delete($hash{$key});
 5969:       }
 5970:     }
 5971:   }
 5972: }
 5973: 
 5974: sub tmpstore {
 5975:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 5976: 
 5977:   if (!$symb) {
 5978:     $symb=&symbread();
 5979:     if (!$symb) { $symb= $env{'request.url'}; }
 5980:   }
 5981:   $symb=escape($symb);
 5982: 
 5983:   if (!$namespace) {
 5984:     # I don't think we would ever want to store this for a course.
 5985:     # it seems this will only be used if we don't have a course.
 5986:     #$namespace=$env{'request.course.id'};
 5987:     #if (!$namespace) {
 5988:       $namespace=$env{'request.state'};
 5989:     #}
 5990:   }
 5991:   $namespace=~s/\//\_/g;
 5992:   $namespace=~s/\W//g;
 5993:   if (!$domain) { $domain=$env{'user.domain'}; }
 5994:   if (!$stuname) { $stuname=$env{'user.name'}; }
 5995:   if ($domain eq 'public' && $stuname eq 'public') {
 5996:       $stuname=$ENV{'REMOTE_ADDR'};
 5997:   }
 5998:   my $now=time;
 5999:   my %hash;
 6000:   my $path=LONCAPA::tempdir();
 6001:   if (tie(%hash,'GDBM_File',
 6002: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 6003: 	  &GDBM_WRCREAT(),0640)) {
 6004:     $hash{"version:$symb"}++;
 6005:     my $version=$hash{"version:$symb"};
 6006:     my $allkeys=''; 
 6007:     foreach my $key (keys(%$storehash)) {
 6008:       $allkeys.=$key.':';
 6009:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
 6010:     }
 6011:     $hash{"$version:$symb:timestamp"}=$now;
 6012:     $allkeys.='timestamp';
 6013:     $hash{"$version:keys:$symb"}=$allkeys;
 6014:     if (untie(%hash)) {
 6015:       return 'ok';
 6016:     } else {
 6017:       return "error:$!";
 6018:     }
 6019:   } else {
 6020:     return "error:$!";
 6021:   }
 6022: }
 6023: 
 6024: # -----------------------------------------------------------------Temp Restore
 6025: 
 6026: sub tmprestore {
 6027:   my ($symb,$namespace,$domain,$stuname) = @_;
 6028: 
 6029:   if (!$symb) {
 6030:     $symb=&symbread();
 6031:     if (!$symb) { $symb= $env{'request.url'}; }
 6032:   }
 6033:   $symb=escape($symb);
 6034: 
 6035:   if (!$namespace) { $namespace=$env{'request.state'}; }
 6036: 
 6037:   if (!$domain) { $domain=$env{'user.domain'}; }
 6038:   if (!$stuname) { $stuname=$env{'user.name'}; }
 6039:   if ($domain eq 'public' && $stuname eq 'public') {
 6040:       $stuname=$ENV{'REMOTE_ADDR'};
 6041:   }
 6042:   my %returnhash;
 6043:   $namespace=~s/\//\_/g;
 6044:   $namespace=~s/\W//g;
 6045:   my %hash;
 6046:   my $path=LONCAPA::tempdir();
 6047:   if (tie(%hash,'GDBM_File',
 6048: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 6049: 	  &GDBM_READER(),0640)) {
 6050:     my $version=$hash{"version:$symb"};
 6051:     $returnhash{'version'}=$version;
 6052:     my $scope;
 6053:     for ($scope=1;$scope<=$version;$scope++) {
 6054:       my $vkeys=$hash{"$scope:keys:$symb"};
 6055:       my @keys=split(/:/,$vkeys);
 6056:       my $key;
 6057:       $returnhash{"$scope:keys"}=$vkeys;
 6058:       foreach $key (@keys) {
 6059: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 6060: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 6061:       }
 6062:     }
 6063:     if (!(untie(%hash))) {
 6064:       return "error:$!";
 6065:     }
 6066:   } else {
 6067:     return "error:$!";
 6068:   }
 6069:   return %returnhash;
 6070: }
 6071: 
 6072: # ----------------------------------------------------------------------- Store
 6073: 
 6074: sub store {
 6075:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
 6076:     my $home='';
 6077: 
 6078:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 6079: 
 6080:     $symb=&symbclean($symb);
 6081:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 6082: 
 6083:     if (!$domain) { $domain=$env{'user.domain'}; }
 6084:     if (!$stuname) { $stuname=$env{'user.name'}; }
 6085: 
 6086:     &devalidate($symb,$stuname,$domain);
 6087: 
 6088:     $symb=escape($symb);
 6089:     if (!$namespace) { 
 6090:        unless ($namespace=$env{'request.course.id'}) { 
 6091:           return ''; 
 6092:        } 
 6093:     }
 6094:     if (!$home) { $home=$env{'user.home'}; }
 6095: 
 6096:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
 6097:     $$storehash{'host'}=$perlvar{'lonHostID'};
 6098: 
 6099:     my $namevalue='';
 6100:     foreach my $key (keys(%$storehash)) {
 6101:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 6102:     }
 6103:     $namevalue=~s/\&$//;
 6104:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
 6105:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
 6106: }
 6107: 
 6108: # -------------------------------------------------------------- Critical Store
 6109: 
 6110: sub cstore {
 6111:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
 6112:     my $home='';
 6113: 
 6114:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 6115: 
 6116:     $symb=&symbclean($symb);
 6117:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 6118: 
 6119:     if (!$domain) { $domain=$env{'user.domain'}; }
 6120:     if (!$stuname) { $stuname=$env{'user.name'}; }
 6121: 
 6122:     &devalidate($symb,$stuname,$domain);
 6123: 
 6124:     $symb=escape($symb);
 6125:     if (!$namespace) { 
 6126:        unless ($namespace=$env{'request.course.id'}) { 
 6127:           return ''; 
 6128:        } 
 6129:     }
 6130:     if (!$home) { $home=$env{'user.home'}; }
 6131: 
 6132:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
 6133:     $$storehash{'host'}=$perlvar{'lonHostID'};
 6134: 
 6135:     my $namevalue='';
 6136:     foreach my $key (keys(%$storehash)) {
 6137:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 6138:     }
 6139:     $namevalue=~s/\&$//;
 6140:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
 6141:     return critical
 6142:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
 6143: }
 6144: 
 6145: # --------------------------------------------------------------------- Restore
 6146: 
 6147: sub restore {
 6148:     my ($symb,$namespace,$domain,$stuname) = @_;
 6149:     my $home='';
 6150: 
 6151:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 6152: 
 6153:     if (!$symb) {
 6154:         return if ($namespace eq 'courserequests');
 6155:         unless ($symb=escape(&symbread())) { return ''; }
 6156:     } else {
 6157:         unless ($namespace eq 'courserequests') {
 6158:             $symb=&escape(&symbclean($symb));
 6159:         }
 6160:     }
 6161:     if (!$namespace) { 
 6162:        unless ($namespace=$env{'request.course.id'}) { 
 6163:           return ''; 
 6164:        } 
 6165:     }
 6166:     if (!$domain) { $domain=$env{'user.domain'}; }
 6167:     if (!$stuname) { $stuname=$env{'user.name'}; }
 6168:     if (!$home) { $home=$env{'user.home'}; }
 6169:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
 6170: 
 6171:     my %returnhash=();
 6172:     foreach my $line (split(/\&/,$answer)) {
 6173: 	my ($name,$value)=split(/\=/,$line);
 6174:         $returnhash{&unescape($name)}=&thaw_unescape($value);
 6175:     }
 6176:     my $version;
 6177:     for ($version=1;$version<=$returnhash{'version'};$version++) {
 6178:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
 6179:           $returnhash{$item}=$returnhash{$version.':'.$item};
 6180:        }
 6181:     }
 6182:     return %returnhash;
 6183: }
 6184: 
 6185: # ---------------------------------------------------------- Course Description
 6186: #
 6187: #  
 6188: 
 6189: sub coursedescription {
 6190:     my ($courseid,$args)=@_;
 6191:     $courseid=~s/^\///;
 6192:     $courseid=~s/\_/\//g;
 6193:     my ($cdomain,$cnum)=split(/\//,$courseid);
 6194:     my $chome=&homeserver($cnum,$cdomain);
 6195:     my $normalid=$cdomain.'_'.$cnum;
 6196:     # need to always cache even if we get errors otherwise we keep 
 6197:     # trying and trying and trying to get the course description.
 6198:     my %envhash=();
 6199:     my %returnhash=();
 6200:     
 6201:     my $expiretime=600;
 6202:     if ($env{'request.course.id'} eq $normalid) {
 6203: 	$expiretime=120;
 6204:     }
 6205: 
 6206:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
 6207:     if (!$args->{'freshen_cache'}
 6208: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
 6209: 	foreach my $key (keys(%env)) {
 6210: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
 6211: 	    my ($setting) = $1;
 6212: 	    $returnhash{$setting} = $env{$key};
 6213: 	}
 6214: 	return %returnhash;
 6215:     }
 6216: 
 6217:     # get the data again
 6218: 
 6219:     if (!$args->{'one_time'}) {
 6220: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
 6221:     }
 6222: 
 6223:     if ($chome ne 'no_host') {
 6224:        %returnhash=&dump('environment',$cdomain,$cnum);
 6225:        if (!exists($returnhash{'con_lost'})) {
 6226: 	   my $username = $env{'user.name'}; # Defult username
 6227: 	   if(defined $args->{'user'}) {
 6228: 	       $username = $args->{'user'};
 6229: 	   }
 6230:            $returnhash{'home'}= $chome;
 6231: 	   $returnhash{'domain'} = $cdomain;
 6232: 	   $returnhash{'num'} = $cnum;
 6233:            if (!defined($returnhash{'type'})) {
 6234:                $returnhash{'type'} = 'Course';
 6235:            }
 6236:            while (my ($name,$value) = each %returnhash) {
 6237:                $envhash{'course.'.$normalid.'.'.$name}=$value;
 6238:            }
 6239:            $returnhash{'url'}=&clutter($returnhash{'url'});
 6240:            $returnhash{'fn'}=LONCAPA::tempdir() .
 6241: 	       $username.'_'.$cdomain.'_'.$cnum;
 6242:            $envhash{'course.'.$normalid.'.home'}=$chome;
 6243:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
 6244:            $envhash{'course.'.$normalid.'.num'}=$cnum;
 6245:        }
 6246:     }
 6247:     if (!$args->{'one_time'}) {
 6248: 	&appenv(\%envhash);
 6249:     }
 6250:     return %returnhash;
 6251: }
 6252: 
 6253: sub update_released_required {
 6254:     my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
 6255:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
 6256:         $cid = $env{'request.course.id'};
 6257:         $cdom = $env{'course.'.$cid.'.domain'};
 6258:         $cnum = $env{'course.'.$cid.'.num'};
 6259:         $chome = $env{'course.'.$cid.'.home'};
 6260:     }
 6261:     if ($needsrelease) {
 6262:         my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
 6263:         my $needsupdate;
 6264:         if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
 6265:             $needsupdate = 1;
 6266:         } else {
 6267:             my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
 6268:             my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
 6269:             if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
 6270:                 $needsupdate = 1;
 6271:             }
 6272:         }
 6273:         if ($needsupdate) {
 6274:             my %needshash = (
 6275:                              'internal.releaserequired' => $needsrelease,
 6276:                             );
 6277:             my $putresult = &put('environment',\%needshash,$cdom,$cnum);
 6278:             if ($putresult eq 'ok') {
 6279:                 &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
 6280:                 my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
 6281:                 if (ref($crsinfo{$cid}) eq 'HASH') {
 6282:                     $crsinfo{$cid}{'releaserequired'} = $needsrelease;
 6283:                     &courseidput($cdom,\%crsinfo,$chome,'notime');
 6284:                 }
 6285:             }
 6286:         }
 6287:     }
 6288:     return;
 6289: }
 6290: 
 6291: # -------------------------------------------------See if a user is privileged
 6292: 
 6293: sub privileged {
 6294:     my ($username,$domain,$possdomains,$possroles)=@_;
 6295:     my $now = time;
 6296:     my $roles;
 6297:     if (ref($possroles) eq 'ARRAY') {
 6298:         $roles = $possroles; 
 6299:     } else {
 6300:         $roles = ['dc','su'];
 6301:     }
 6302:     if (ref($possdomains) eq 'ARRAY') {
 6303:         my %privileged = &privileged_by_domain($possdomains,$roles);
 6304:         foreach my $dom (@{$possdomains}) {
 6305:             if (($username =~ /^$match_username$/) && ($domain =~ /^$match_domain$/) &&
 6306:                 (ref($privileged{$dom}) eq 'HASH')) {
 6307:                 foreach my $role (@{$roles}) {
 6308:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
 6309:                         if (exists($privileged{$dom}{$role}{$username.':'.$domain})) {
 6310:                             my ($end,$start) = split(/:/,$privileged{$dom}{$role}{$username.':'.$domain});
 6311:                             return 1 unless (($end && $end < $now) ||
 6312:                                              ($start && $start > $now));
 6313:                         }
 6314:                     }
 6315:                 }
 6316:             }
 6317:         }
 6318:     } else {
 6319:         my %rolesdump = &dump("roles", $domain, $username) or return 0;
 6320:         my $now = time;
 6321: 
 6322:         for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys(%rolesdump)}) {
 6323:             my ($trole, $tend, $tstart) = split(/_/, $role);
 6324:             if (grep(/^\Q$trole\E$/,@{$roles})) {
 6325:                 return 1 unless ($tend && $tend < $now) 
 6326:                         or ($tstart && $tstart > $now);
 6327:             }
 6328:         }
 6329:     }
 6330:     return 0;
 6331: }
 6332: 
 6333: sub privileged_by_domain {
 6334:     my ($domains,$roles) = @_;
 6335:     my %privileged = ();
 6336:     my $cachetime = 60*60*24;
 6337:     my $now = time;
 6338:     unless ((ref($domains) eq 'ARRAY') && (ref($roles) eq 'ARRAY')) {
 6339:         return %privileged;
 6340:     }
 6341:     foreach my $dom (@{$domains}) {
 6342:         next if (ref($privileged{$dom}) eq 'HASH');
 6343:         my $needroles;
 6344:         foreach my $role (@{$roles}) {
 6345:             my ($result,$cached)=&is_cached_new('priv_'.$role,$dom);
 6346:             if (defined($cached)) {
 6347:                 if (ref($result) eq 'HASH') {
 6348:                     $privileged{$dom}{$role} = $result;
 6349:                 }
 6350:             } else {
 6351:                 $needroles = 1;
 6352:             }
 6353:         }
 6354:         if ($needroles) {
 6355:             my %dompersonnel = &get_domain_roles($dom,$roles);
 6356:             $privileged{$dom} = {};
 6357:             foreach my $server (keys(%dompersonnel)) {
 6358:                 if (ref($dompersonnel{$server}) eq 'HASH') {
 6359:                     foreach my $item (keys(%{$dompersonnel{$server}})) {
 6360:                         my ($trole,$uname,$udom,$rest) = split(/:/,$item,4);
 6361:                         my ($end,$start) = split(/:/,$dompersonnel{$server}{$item});
 6362:                         next if ($end && $end < $now);
 6363:                         $privileged{$dom}{$trole}{$uname.':'.$udom} = 
 6364:                             $dompersonnel{$server}{$item};
 6365:                     }
 6366:                 }
 6367:             }
 6368:             if (ref($privileged{$dom}) eq 'HASH') {
 6369:                 foreach my $role (@{$roles}) {
 6370:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
 6371:                         &do_cache_new('priv_'.$role,$dom,$privileged{$dom}{$role},$cachetime);
 6372:                     } else {
 6373:                         my %hash = ();
 6374:                         &do_cache_new('priv_'.$role,$dom,\%hash,$cachetime);
 6375:                     }
 6376:                 }
 6377:             }
 6378:         }
 6379:     }
 6380:     return %privileged;
 6381: }
 6382: 
 6383: # -------------------------------------------------------- Get user privileges
 6384: 
 6385: sub rolesinit {
 6386:     my ($domain, $username) = @_;
 6387:     my %userroles = ('user.login.time' => time);
 6388:     my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
 6389: 
 6390:     # firstaccess and timerinterval are related to timed maps/resources. 
 6391:     # also, blocking can be triggered by an activating timer
 6392:     # it's saved in the user's %env.
 6393:     my %firstaccess = &dump('firstaccesstimes', $domain, $username);
 6394:     my %timerinterval = &dump('timerinterval', $domain, $username);
 6395:     my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
 6396:         %timerintchk, %timerintenv);
 6397: 
 6398:     foreach my $key (keys(%firstaccess)) {
 6399:         my ($cid, $rest) = split(/\0/, $key);
 6400:         $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
 6401:     }
 6402: 
 6403:     foreach my $key (keys(%timerinterval)) {
 6404:         my ($cid,$rest) = split(/\0/,$key);
 6405:         $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
 6406:     }
 6407: 
 6408:     my %allroles=();
 6409:     my %allgroups=();
 6410: 
 6411:     for my $area (grep { ! /^rolesdef_/ } keys(%rolesdump)) {
 6412:         my $role = $rolesdump{$area};
 6413:         $area =~ s/\_\w\w$//;
 6414: 
 6415:         my ($trole, $tend, $tstart, $group_privs);
 6416: 
 6417:         if ($role =~ /^cr/) {
 6418:         # Custom role, defined by a user 
 6419:         # e.g., user.role.cr/msu/smith/mynewrole
 6420:             if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
 6421:                 $trole = $1;
 6422:                 ($tend, $tstart) = split('_', $2);
 6423:             } else {
 6424:                 $trole = $role;
 6425:             }
 6426:         } elsif ($role =~ m|^gr/|) {
 6427:         # Role of member in a group, defined within a course/community
 6428:         # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
 6429:             ($trole, $tend, $tstart) = split(/_/, $role);
 6430:             next if $tstart eq '-1';
 6431:             ($trole, $group_privs) = split(/\//, $trole);
 6432:             $group_privs = &unescape($group_privs);
 6433:         } else {
 6434:         # Just a normal role, defined in roles.tab
 6435:             ($trole, $tend, $tstart) = split(/_/,$role);
 6436:         }
 6437: 
 6438:         my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
 6439:                  $username);
 6440:         @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
 6441: 
 6442:         # role expired or not available yet?
 6443:         $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or 
 6444:             ($tstart != 0 && $tstart > $userroles{'user.login.time'});
 6445: 
 6446:         next if $area eq '' or $trole eq '';
 6447: 
 6448:         my $spec = "$trole.$area";
 6449:         my ($tdummy, $tdomain, $trest) = split(/\//, $area);
 6450: 
 6451:         if ($trole =~ /^cr\//) {
 6452:         # Custom role, defined by a user
 6453:             &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
 6454:         } elsif ($trole eq 'gr') {
 6455:         # Role of a member in a group, defined within a course/community
 6456:             &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
 6457:             next;
 6458:         } else {
 6459:         # Normal role, defined in roles.tab
 6460:             &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
 6461:         }
 6462: 
 6463:         my $cid = $tdomain.'_'.$trest;
 6464:         unless ($firstaccchk{$cid}) {
 6465:             if (ref($coursetimerstarts{$cid}) eq 'HASH') {
 6466:                 foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
 6467:                     $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} = 
 6468:                         $coursetimerstarts{$cid}{$item}; 
 6469:                 }
 6470:             }
 6471:             $firstaccchk{$cid} = 1;
 6472:         }
 6473:         unless ($timerintchk{$cid}) {
 6474:             if (ref($coursetimerintervals{$cid}) eq 'HASH') {
 6475:                 foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
 6476:                     $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
 6477:                        $coursetimerintervals{$cid}{$item};
 6478:                 }
 6479:             }
 6480:             $timerintchk{$cid} = 1;
 6481:         }
 6482:     }
 6483: 
 6484:     @userroles{'user.author','user.adv','user.rar'} = &set_userprivs(\%userroles,
 6485:                                                           \%allroles, \%allgroups);
 6486:     $env{'user.adv'} = $userroles{'user.adv'};
 6487:     $env{'user.rar'} = $userroles{'user.rar'};
 6488: 
 6489:     return (\%userroles,\%firstaccenv,\%timerintenv);
 6490: }
 6491: 
 6492: sub set_arearole {
 6493:     my ($trole,$area,$tstart,$tend,$domain,$username,$nolog) = @_;
 6494:     unless ($nolog) {
 6495: # log the associated role with the area
 6496:         &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
 6497:     }
 6498:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
 6499: }
 6500: 
 6501: sub custom_roleprivs {
 6502:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
 6503:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
 6504:     my $homsvr = &homeserver($rauthor,$rdomain);
 6505:     if (&hostname($homsvr) ne '') {
 6506:         my ($rdummy,$roledef)=
 6507:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
 6508:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
 6509:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
 6510:             if (defined($syspriv)) {
 6511:                 if ($trest =~ /^$match_community$/) {
 6512:                     $syspriv =~ s/bre\&S//; 
 6513:                 }
 6514:                 $$allroles{'cm./'}.=':'.$syspriv;
 6515:                 $$allroles{$spec.'./'}.=':'.$syspriv;
 6516:             }
 6517:             if ($tdomain ne '') {
 6518:                 if (defined($dompriv)) {
 6519:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
 6520:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
 6521:                 }
 6522:                 if (($trest ne '') && (defined($coursepriv))) {
 6523:                     if ($trole =~ m{^cr/$tdomain/$tdomain\Q-domainconfig\E/([^/]+)$}) {
 6524:                         my $rolename = $1;
 6525:                         $coursepriv = &course_adhocrole_privs($rolename,$tdomain,$trest,$coursepriv);
 6526:                     }
 6527:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
 6528:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
 6529:                 }
 6530:             }
 6531:         }
 6532:     }
 6533: }
 6534: 
 6535: sub course_adhocrole_privs {
 6536:     my ($rolename,$cdom,$cnum,$coursepriv) = @_;
 6537:     my %overrides = &get('environment',["internal.adhocpriv.$rolename"],$cdom,$cnum);
 6538:     if ($overrides{"internal.adhocpriv.$rolename"}) {
 6539:         my (%currprivs,%storeprivs);
 6540:         foreach my $item (split(/:/,$coursepriv)) {
 6541:             my ($priv,$restrict) = split(/\&/,$item);
 6542:             $currprivs{$priv} = $restrict;
 6543:         }
 6544:         my (%possadd,%possremove,%full);
 6545:         foreach my $item (split(/\:/,$Apache::lonnet::pr{'cr:c'})) {
 6546:             my ($priv,$restrict)=split(/\&/,$item);
 6547:             $full{$priv} = $restrict;
 6548:         }
 6549:         foreach my $item (split(/,/,$overrides{"internal.adhocpriv.$rolename"})) {
 6550:              next if ($item eq '');
 6551:              my ($rule,$rest) = split(/=/,$item);
 6552:              next unless (($rule eq 'off') || ($rule eq 'on'));
 6553:              foreach my $priv (split(/:/,$rest)) {
 6554:                  if ($priv ne '') {
 6555:                      if ($rule eq 'off') {
 6556:                          $possremove{$priv} = 1;
 6557:                      } else {
 6558:                          $possadd{$priv} = 1;
 6559:                      }
 6560:                  }
 6561:              }
 6562:          }
 6563:          foreach my $priv (sort(keys(%full))) {
 6564:              if (exists($currprivs{$priv})) {
 6565:                  unless (exists($possremove{$priv})) {
 6566:                      $storeprivs{$priv} = $currprivs{$priv};
 6567:                  }
 6568:              } elsif (exists($possadd{$priv})) {
 6569:                  $storeprivs{$priv} = $full{$priv};
 6570:              }
 6571:          }
 6572:          $coursepriv = ':'.join(':',map { $_.'&'.$storeprivs{$_}; } sort(keys(%storeprivs)));
 6573:      }
 6574:      return $coursepriv;
 6575: }
 6576: 
 6577: sub group_roleprivs {
 6578:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
 6579:     my $access = 1;
 6580:     my $now = time;
 6581:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
 6582:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
 6583:     if ($access) {
 6584:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
 6585:         $$allgroups{$course}{$group} .=':'.$group_privs;
 6586:     }
 6587: }
 6588: 
 6589: sub standard_roleprivs {
 6590:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
 6591:     if (defined($pr{$trole.':s'})) {
 6592:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
 6593:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
 6594:     }
 6595:     if ($tdomain ne '') {
 6596:         if (defined($pr{$trole.':d'})) {
 6597:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 6598:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 6599:         }
 6600:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
 6601:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
 6602:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
 6603:         }
 6604:     }
 6605: }
 6606: 
 6607: sub set_userprivs {
 6608:     my ($userroles,$allroles,$allgroups,$groups_roles) = @_; 
 6609:     my $author=0;
 6610:     my $adv=0;
 6611:     my $rar=0;
 6612:     my %grouproles = ();
 6613:     if (keys(%{$allgroups}) > 0) {
 6614:         my @groupkeys; 
 6615:         foreach my $role (keys(%{$allroles})) {
 6616:             push(@groupkeys,$role);
 6617:         }
 6618:         if (ref($groups_roles) eq 'HASH') {
 6619:             foreach my $key (keys(%{$groups_roles})) {
 6620:                 unless (grep(/^\Q$key\E$/,@groupkeys)) {
 6621:                     push(@groupkeys,$key);
 6622:                 }
 6623:             }
 6624:         }
 6625:         if (@groupkeys > 0) {
 6626:             foreach my $role (@groupkeys) {
 6627:                 my ($trole,$area,$sec,$extendedarea);
 6628:                 if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
 6629:                     $trole = $1;
 6630:                     $area = $2;
 6631:                     $sec = $3;
 6632:                     $extendedarea = $area.$sec;
 6633:                     if (exists($$allgroups{$area})) {
 6634:                         foreach my $group (keys(%{$$allgroups{$area}})) {
 6635:                             my $spec = $trole.'.'.$extendedarea;
 6636:                             $grouproles{$spec.'.'.$area.'/'.$group} = 
 6637:                                                 $$allgroups{$area}{$group};
 6638:                         }
 6639:                     }
 6640:                 }
 6641:             }
 6642:         }
 6643:     }
 6644:     foreach my $group (keys(%grouproles)) {
 6645:         $$allroles{$group} = $grouproles{$group};
 6646:     }
 6647:     foreach my $role (keys(%{$allroles})) {
 6648:         my %thesepriv;
 6649:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
 6650:         foreach my $item (split(/:/,$$allroles{$role})) {
 6651:             if ($item ne '') {
 6652:                 my ($privilege,$restrictions)=split(/&/,$item);
 6653:                 if ($restrictions eq '') {
 6654:                     $thesepriv{$privilege}='F';
 6655:                 } elsif ($thesepriv{$privilege} ne 'F') {
 6656:                     $thesepriv{$privilege}.=$restrictions;
 6657:                 }
 6658:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
 6659:                 if ($thesepriv{'rar'} eq 'F') { $rar=1; }
 6660:             }
 6661:         }
 6662:         my $thesestr='';
 6663:         foreach my $priv (sort(keys(%thesepriv))) {
 6664: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
 6665: 	}
 6666:         $userroles->{'user.priv.'.$role} = $thesestr;
 6667:     }
 6668:     return ($author,$adv,$rar);
 6669: }
 6670: 
 6671: sub role_status {
 6672:     my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
 6673:     if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
 6674:         my ($one,$two) = split(m{\./},$rolekey,2);
 6675:         (undef,undef,$$role) = split(/\./,$one,3);
 6676:         unless (!defined($$role) || $$role eq '') {
 6677:             $$where = '/'.$two;
 6678:             $$trolecode=$$role.'.'.$$where;
 6679:             ($$tstart,$$tend)=split(/\./,$env{$rolekey});
 6680:             $$tstatus='is';
 6681:             if ($$tstart && $$tstart>$update) {
 6682:                 $$tstatus='future';
 6683:                 if ($$tstart<$now) {
 6684:                     if ($$tstart && $$tstart>$refresh) {
 6685:                         if (($$where ne '') && ($$role ne '')) {
 6686:                             my (%allroles,%allgroups,$group_privs,
 6687:                                 %groups_roles,@rolecodes);
 6688:                             my %userroles = (
 6689:                                 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
 6690:                             );
 6691:                             @rolecodes = ('cm'); 
 6692:                             my $spec=$$role.'.'.$$where;
 6693:                             my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
 6694:                             if ($$role =~ /^cr\//) {
 6695:                                 &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
 6696:                                 push(@rolecodes,'cr');
 6697:                             } elsif ($$role eq 'gr') {
 6698:                                 push(@rolecodes,$$role);
 6699:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
 6700:                                                     $env{'user.name'});
 6701:                                 my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
 6702:                                 (undef,my $group_privs) = split(/\//,$trole);
 6703:                                 $group_privs = &unescape($group_privs);
 6704:                                 &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
 6705:                                 my %course_roles = &get_my_roles($env{'user.name'},$env{'user.domain'},'userroles',['active'],['cc','co','in','ta','ep','ad','st','cr'],[$tdomain],1);
 6706:                                 &get_groups_roles($tdomain,$trest,
 6707:                                                   \%course_roles,\@rolecodes,
 6708:                                                   \%groups_roles);
 6709:                             } else {
 6710:                                 push(@rolecodes,$$role);
 6711:                                 &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
 6712:                             }
 6713:                             my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%allroles,\%allgroups,
 6714:                                                                    \%groups_roles);
 6715:                             &appenv(\%userroles,\@rolecodes);
 6716:                             &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
 6717:                         }
 6718:                     }
 6719:                     $$tstatus = 'is';
 6720:                 }
 6721:             }
 6722:             if ($$tend) {
 6723:                 if ($$tend<$update) {
 6724:                     $$tstatus='expired';
 6725:                 } elsif ($$tend<$now) {
 6726:                     $$tstatus='will_not';
 6727:                 }
 6728:             }
 6729:         }
 6730:     }
 6731: }
 6732: 
 6733: sub get_groups_roles {
 6734:     my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
 6735:     return unless((ref($cdom_courseroles) eq 'HASH') && 
 6736:                   (ref($rolecodes) eq 'ARRAY') && 
 6737:                   (ref($groups_roles) eq 'HASH')); 
 6738:     if (keys(%{$cdom_courseroles}) > 0) {
 6739:         my ($cnum) = ($rest =~ /^($match_courseid)/);
 6740:         if ($cdom ne '' && $cnum ne '') {
 6741:             foreach my $key (keys(%{$cdom_courseroles})) {
 6742:                 if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
 6743:                     my $crsrole = $1;
 6744:                     my $crssec = $2;
 6745:                     if ($crsrole =~ /^cr/) {
 6746:                         unless (grep(/^cr$/,@{$rolecodes})) {
 6747:                             push(@{$rolecodes},'cr');
 6748:                         }
 6749:                     } else {
 6750:                         unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
 6751:                             push(@{$rolecodes},$crsrole);
 6752:                         }
 6753:                     }
 6754:                     my $rolekey = "$crsrole./$cdom/$cnum";
 6755:                     if ($crssec ne '') {
 6756:                         $rolekey .= "/$crssec";
 6757:                     }
 6758:                     $rolekey .= './';
 6759:                     $groups_roles->{$rolekey} = $rolecodes;
 6760:                 }
 6761:             }
 6762:         }
 6763:     }
 6764:     return;
 6765: }
 6766: 
 6767: sub delete_env_groupprivs {
 6768:     my ($where,$courseroles,$possroles) = @_;
 6769:     return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
 6770:     my ($dummy,$udom,$uname,$group) = split(/\//,$where);
 6771:     unless (ref($courseroles->{$udom}) eq 'HASH') {
 6772:         %{$courseroles->{$udom}} =
 6773:             &get_my_roles('','','userroles',['active'],
 6774:                           $possroles,[$udom],1);
 6775:     }
 6776:     if (ref($courseroles->{$udom}) eq 'HASH') {
 6777:         foreach my $item (keys(%{$courseroles->{$udom}})) {
 6778:             my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
 6779:             my $area = '/'.$cdom.'/'.$cnum;
 6780:             my $privkey = "user.priv.$crsrole.$area";
 6781:             if ($crssec ne '') {
 6782:                 $privkey .= '/'.$crssec;
 6783:             }
 6784:             $privkey .= ".$area/$group";
 6785:             &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
 6786:         }
 6787:     }
 6788:     return;
 6789: }
 6790: 
 6791: sub check_adhoc_privs {
 6792:     my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller,$sec) = @_;
 6793:     my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
 6794:     if ($sec) {
 6795:         $cckey .= '/'.$sec;
 6796:     } 
 6797:     my $setprivs;
 6798:     if ($env{$cckey}) {
 6799:         my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
 6800:         &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
 6801:         unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
 6802:             &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
 6803:             $setprivs = 1;
 6804:         }
 6805:     } else {
 6806:         &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
 6807:         $setprivs = 1;
 6808:     }
 6809:     return $setprivs;
 6810: }
 6811: 
 6812: sub set_adhoc_privileges {
 6813: # role can be cc, ca, or cr/<dom>/<dom>-domainconfig/role
 6814:     my ($dcdom,$pickedcourse,$role,$caller,$sec) = @_;
 6815:     my $area = '/'.$dcdom.'/'.$pickedcourse;
 6816:     if ($sec ne '') {
 6817:         $area .= '/'.$sec;
 6818:     }
 6819:     my $spec = $role.'.'.$area;
 6820:     my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
 6821:                                   $env{'user.name'},1);
 6822:     my %rolehash = ();
 6823:     if ($role =~ m{^\Qcr/$dcdom/$dcdom\E\-domainconfig/(\w+)$}) {
 6824:         my $rolename = $1;
 6825:         &custom_roleprivs(\%rolehash,$role,$dcdom,$pickedcourse,$spec,$area);
 6826:         my %domdef = &get_domain_defaults($dcdom);
 6827:         if (ref($domdef{'adhocroles'}) eq 'HASH') {
 6828:             if (ref($domdef{'adhocroles'}{$rolename}) eq 'HASH') {
 6829:                 &appenv({'request.role.desc' => $domdef{'adhocroles'}{$rolename}{'desc'},});
 6830:             }
 6831:         }
 6832:     } else {
 6833:         &standard_roleprivs(\%rolehash,$role,$dcdom,$spec,$pickedcourse,$area);
 6834:     }
 6835:     my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%rolehash);
 6836:     &appenv(\%userroles,[$role,'cm']);
 6837:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
 6838:     unless (($caller eq 'constructaccess' && $env{'request.course.id'}) ||
 6839:             ($caller eq 'tiny')) {
 6840:         &appenv( {'request.role'        => $spec,
 6841:                   'request.role.domain' => $dcdom,
 6842:                   'request.course.sec'  => $sec,
 6843:                  }
 6844:                );
 6845:         my $tadv=0;
 6846:         if (&allowed('adv') eq 'F') { $tadv=1; }
 6847:         &appenv({'request.role.adv'    => $tadv});
 6848:     }
 6849: }
 6850: 
 6851: # --------------------------------------------------------------- get interface
 6852: 
 6853: sub get {
 6854:    my ($namespace,$storearr,$udomain,$uname)=@_;
 6855:    my $items='';
 6856:    foreach my $item (@$storearr) {
 6857:        $items.=&escape($item).'&';
 6858:    }
 6859:    $items=~s/\&$//;
 6860:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 6861:    if (!$uname) { $uname=$env{'user.name'}; }
 6862:    my $uhome=&homeserver($uname,$udomain);
 6863: 
 6864:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
 6865:    my @pairs=split(/\&/,$rep);
 6866:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
 6867:      return @pairs;
 6868:    }
 6869:    my %returnhash=();
 6870:    my $i=0;
 6871:    foreach my $item (@$storearr) {
 6872:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 6873:       $i++;
 6874:    }
 6875:    return %returnhash;
 6876: }
 6877: 
 6878: # --------------------------------------------------------------- del interface
 6879: 
 6880: sub del {
 6881:    my ($namespace,$storearr,$udomain,$uname)=@_;
 6882:    my $items='';
 6883:    foreach my $item (@$storearr) {
 6884:        $items.=&escape($item).'&';
 6885:    }
 6886: 
 6887:    $items=~s/\&$//;
 6888:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 6889:    if (!$uname) { $uname=$env{'user.name'}; }
 6890:    my $uhome=&homeserver($uname,$udomain);
 6891:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
 6892: }
 6893: 
 6894: # -------------------------------------------------------------- dump interface
 6895: 
 6896: sub unserialize {
 6897:     my ($rep, $escapedkeys) = @_;
 6898: 
 6899:     return {} if $rep =~ /^error/;
 6900: 
 6901:     my %returnhash=();
 6902: 	foreach my $item (split(/\&/,$rep)) {
 6903: 	    my ($key, $value) = split(/=/, $item, 2);
 6904: 	    $key = unescape($key) unless $escapedkeys;
 6905: 	    next if $key =~ /^error: 2 /;
 6906: 	    $returnhash{$key} = &thaw_unescape($value);
 6907: 	}
 6908:     #return %returnhash;
 6909:     return \%returnhash;
 6910: }        
 6911: 
 6912: # see Lond::dump_with_regexp
 6913: # if $escapedkeys hash keys won't get unescaped.
 6914: sub dump {
 6915:     my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys)=@_;
 6916:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 6917:     if (!$uname) { $uname=$env{'user.name'}; }
 6918:     my $uhome=&homeserver($uname,$udomain);
 6919: 
 6920:     if ($regexp) {
 6921:         $regexp=&escape($regexp);
 6922:     } else {
 6923:         $regexp='.';
 6924:     }
 6925:     if (grep { $_ eq $uhome } current_machine_ids()) {
 6926:         # user is hosted on this machine
 6927:         my $reply = LONCAPA::Lond::dump_with_regexp(join(":", ($udomain,
 6928:                     $uname, $namespace, $regexp, $range)), $perlvar{'lonVersion'});
 6929:         return %{unserialize($reply, $escapedkeys)};
 6930:     }
 6931:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
 6932:     my @pairs=split(/\&/,$rep);
 6933:     my %returnhash=();
 6934:     if (!($rep =~ /^error/ )) {
 6935: 	foreach my $item (@pairs) {
 6936: 	    my ($key,$value)=split(/=/,$item,2);
 6937:         $key = unescape($key) unless $escapedkeys;
 6938:         #$key = &unescape($key);
 6939: 	    next if ($key =~ /^error: 2 /);
 6940: 	    $returnhash{$key}=&thaw_unescape($value);
 6941: 	}
 6942:     }
 6943:     return %returnhash;
 6944: }
 6945: 
 6946: 
 6947: # --------------------------------------------------------- dumpstore interface
 6948: 
 6949: sub dumpstore {
 6950:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
 6951:    # same as dump but keys must be escaped. They may contain colon separated
 6952:    # lists of values that may themself contain colons (e.g. symbs).
 6953:    return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
 6954: }
 6955: 
 6956: # -------------------------------------------------------------- keys interface
 6957: 
 6958: sub getkeys {
 6959:    my ($namespace,$udomain,$uname)=@_;
 6960:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 6961:    if (!$uname) { $uname=$env{'user.name'}; }
 6962:    my $uhome=&homeserver($uname,$udomain);
 6963:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
 6964:    my @keyarray=();
 6965:    foreach my $key (split(/\&/,$rep)) {
 6966:       next if ($key =~ /^error: 2 /);
 6967:       push(@keyarray,&unescape($key));
 6968:    }
 6969:    return @keyarray;
 6970: }
 6971: 
 6972: # --------------------------------------------------------------- currentdump
 6973: sub currentdump {
 6974:    my ($courseid,$sdom,$sname)=@_;
 6975:    $courseid = $env{'request.course.id'} if (! defined($courseid));
 6976:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
 6977:    $sname    = $env{'user.name'}         if (! defined($sname));
 6978:    my $uhome = &homeserver($sname,$sdom);
 6979:    my $rep;
 6980: 
 6981:    if (grep { $_ eq $uhome } current_machine_ids()) {
 6982:        $rep = LONCAPA::Lond::dump_profile_database(join(":", ($sdom, $sname, 
 6983:                    $courseid)));
 6984:    } else {
 6985:        $rep = reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
 6986:    }
 6987: 
 6988:    return if ($rep =~ /^(error:|no_such_host)/);
 6989:    #
 6990:    my %returnhash=();
 6991:    #
 6992:    if ($rep eq 'unknown_cmd') {
 6993:        # an old lond will not know currentdump
 6994:        # Do a dump and make it look like a currentdump
 6995:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
 6996:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
 6997:        my %hash = @tmp;
 6998:        @tmp=();
 6999:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
 7000:    } else {
 7001:        my @pairs=split(/\&/,$rep);
 7002:        foreach my $pair (@pairs) {
 7003:            my ($key,$value)=split(/=/,$pair,2);
 7004:            my ($symb,$param) = split(/:/,$key);
 7005:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
 7006:                                                         &thaw_unescape($value);
 7007:        }
 7008:    }
 7009:    return %returnhash;
 7010: }
 7011: 
 7012: sub convert_dump_to_currentdump{
 7013:     my %hash = %{shift()};
 7014:     my %returnhash;
 7015:     # Code ripped from lond, essentially.  The only difference
 7016:     # here is the unescaping done by lonnet::dump().  Conceivably
 7017:     # we might run in to problems with parameter names =~ /^v\./
 7018:     while (my ($key,$value) = each(%hash)) {
 7019:         my ($v,$symb,$param) = split(/:/,$key);
 7020: 	$symb  = &unescape($symb);
 7021: 	$param = &unescape($param);
 7022:         next if ($v eq 'version' || $symb eq 'keys');
 7023:         next if (exists($returnhash{$symb}) &&
 7024:                  exists($returnhash{$symb}->{$param}) &&
 7025:                  $returnhash{$symb}->{'v.'.$param} > $v);
 7026:         $returnhash{$symb}->{$param}=$value;
 7027:         $returnhash{$symb}->{'v.'.$param}=$v;
 7028:     }
 7029:     #
 7030:     # Remove all of the keys in the hashes which keep track of
 7031:     # the version of the parameter.
 7032:     while (my ($symb,$param_hash) = each(%returnhash)) {
 7033:         # use a foreach because we are going to delete from the hash.
 7034:         foreach my $key (keys(%$param_hash)) {
 7035:             delete($param_hash->{$key}) if ($key =~ /^v\./);
 7036:         }
 7037:     }
 7038:     return \%returnhash;
 7039: }
 7040: 
 7041: # ------------------------------------------------------ critical inc interface
 7042: 
 7043: sub cinc {
 7044:     return &inc(@_,'critical');
 7045: }
 7046: 
 7047: # --------------------------------------------------------------- inc interface
 7048: 
 7049: sub inc {
 7050:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
 7051:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 7052:     if (!$uname) { $uname=$env{'user.name'}; }
 7053:     my $uhome=&homeserver($uname,$udomain);
 7054:     my $items='';
 7055:     if (! ref($store)) {
 7056:         # got a single value, so use that instead
 7057:         $items = &escape($store).'=&';
 7058:     } elsif (ref($store) eq 'SCALAR') {
 7059:         $items = &escape($$store).'=&';        
 7060:     } elsif (ref($store) eq 'ARRAY') {
 7061:         $items = join('=&',map {&escape($_);} @{$store});
 7062:     } elsif (ref($store) eq 'HASH') {
 7063:         while (my($key,$value) = each(%{$store})) {
 7064:             $items.= &escape($key).'='.&escape($value).'&';
 7065:         }
 7066:     }
 7067:     $items=~s/\&$//;
 7068:     if ($critical) {
 7069: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
 7070:     } else {
 7071: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
 7072:     }
 7073: }
 7074: 
 7075: # --------------------------------------------------------------- put interface
 7076: 
 7077: sub put {
 7078:    my ($namespace,$storehash,$udomain,$uname)=@_;
 7079:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 7080:    if (!$uname) { $uname=$env{'user.name'}; }
 7081:    my $uhome=&homeserver($uname,$udomain);
 7082:    my $items='';
 7083:    foreach my $item (keys(%$storehash)) {
 7084:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 7085:    }
 7086:    $items=~s/\&$//;
 7087:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 7088: }
 7089: 
 7090: # ------------------------------------------------------------ newput interface
 7091: 
 7092: sub newput {
 7093:    my ($namespace,$storehash,$udomain,$uname)=@_;
 7094:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 7095:    if (!$uname) { $uname=$env{'user.name'}; }
 7096:    my $uhome=&homeserver($uname,$udomain);
 7097:    my $items='';
 7098:    foreach my $key (keys(%$storehash)) {
 7099:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 7100:    }
 7101:    $items=~s/\&$//;
 7102:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
 7103: }
 7104: 
 7105: # ---------------------------------------------------------  putstore interface
 7106: 
 7107: sub putstore {
 7108:    my ($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog)=@_;
 7109:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 7110:    if (!$uname) { $uname=$env{'user.name'}; }
 7111:    my $uhome=&homeserver($uname,$udomain);
 7112:    my $items='';
 7113:    foreach my $key (keys(%$storehash)) {
 7114:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
 7115:    }
 7116:    $items=~s/\&$//;
 7117:    my $esc_symb=&escape($symb);
 7118:    my $esc_v=&escape($version);
 7119:    my $reply =
 7120:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
 7121: 	      $uhome);
 7122:    if (($tolog) && ($reply eq 'ok')) {
 7123:        my $namevalue='';
 7124:        foreach my $key (keys(%{$storehash})) {
 7125:            $namevalue.=&escape($key).'='.&freeze_escape($storehash->{$key}).'&';
 7126:        }
 7127:        $namevalue .= 'ip='.&escape($ENV{'REMOTE_ADDR'}).
 7128:                      '&host='.&escape($perlvar{'lonHostID'}).
 7129:                      '&version='.$esc_v.
 7130:                      '&by='.&escape($env{'user.name'}.':'.$env{'user.domain'});
 7131:        &Apache::lonnet::courselog($symb.':'.$uname.':'.$udomain.':PUTSTORE:'.$namevalue);
 7132:    }
 7133:    if ($reply eq 'unknown_cmd') {
 7134:        # gfall back to way things use to be done
 7135:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
 7136: 			    $uname);
 7137:    }
 7138:    return $reply;
 7139: }
 7140: 
 7141: sub old_putstore {
 7142:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
 7143:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 7144:     if (!$uname) { $uname=$env{'user.name'}; }
 7145:     my $uhome=&homeserver($uname,$udomain);
 7146:     my %newstorehash;
 7147:     foreach my $item (keys(%$storehash)) {
 7148: 	my $key = $version.':'.&escape($symb).':'.$item;
 7149: 	$newstorehash{$key} = $storehash->{$item};
 7150:     }
 7151:     my $items='';
 7152:     my %allitems = ();
 7153:     foreach my $item (keys(%newstorehash)) {
 7154: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
 7155: 	    my $key = $1.':keys:'.$2;
 7156: 	    $allitems{$key} .= $3.':';
 7157: 	}
 7158: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
 7159:     }
 7160:     foreach my $item (keys(%allitems)) {
 7161: 	$allitems{$item} =~ s/\:$//;
 7162: 	$items.= $item.'='.$allitems{$item}.'&';
 7163:     }
 7164:     $items=~s/\&$//;
 7165:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 7166: }
 7167: 
 7168: # ------------------------------------------------------ critical put interface
 7169: 
 7170: sub cput {
 7171:    my ($namespace,$storehash,$udomain,$uname)=@_;
 7172:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 7173:    if (!$uname) { $uname=$env{'user.name'}; }
 7174:    my $uhome=&homeserver($uname,$udomain);
 7175:    my $items='';
 7176:    foreach my $item (keys(%$storehash)) {
 7177:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 7178:    }
 7179:    $items=~s/\&$//;
 7180:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
 7181: }
 7182: 
 7183: # -------------------------------------------------------------- eget interface
 7184: 
 7185: sub eget {
 7186:    my ($namespace,$storearr,$udomain,$uname)=@_;
 7187:    my $items='';
 7188:    foreach my $item (@$storearr) {
 7189:        $items.=&escape($item).'&';
 7190:    }
 7191:    $items=~s/\&$//;
 7192:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 7193:    if (!$uname) { $uname=$env{'user.name'}; }
 7194:    my $uhome=&homeserver($uname,$udomain);
 7195:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
 7196:    my @pairs=split(/\&/,$rep);
 7197:    my %returnhash=();
 7198:    my $i=0;
 7199:    foreach my $item (@$storearr) {
 7200:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 7201:       $i++;
 7202:    }
 7203:    return %returnhash;
 7204: }
 7205: 
 7206: # ------------------------------------------------------------ tmpput interface
 7207: sub tmpput {
 7208:     my ($storehash,$server,$context)=@_;
 7209:     my $items='';
 7210:     foreach my $item (keys(%$storehash)) {
 7211: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 7212:     }
 7213:     $items=~s/\&$//;
 7214:     if (defined($context)) {
 7215:         $items .= ':'.&escape($context);
 7216:     }
 7217:     return &reply("tmpput:$items",$server);
 7218: }
 7219: 
 7220: # ------------------------------------------------------------ tmpget interface
 7221: sub tmpget {
 7222:     my ($token,$server)=@_;
 7223:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 7224:     my $rep=&reply("tmpget:$token",$server);
 7225:     my %returnhash;
 7226:     if ($rep =~ /^(con_lost|error|no_such_host)/i) {
 7227:         return %returnhash;
 7228:     }
 7229:     foreach my $item (split(/\&/,$rep)) {
 7230: 	my ($key,$value)=split(/=/,$item);
 7231: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
 7232:     }
 7233:     return %returnhash;
 7234: }
 7235: 
 7236: # ------------------------------------------------------------ tmpdel interface
 7237: sub tmpdel {
 7238:     my ($token,$server)=@_;
 7239:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 7240:     return &reply("tmpdel:$token",$server);
 7241: }
 7242: 
 7243: # ------------------------------------------------------------ get_timebased_id 
 7244: 
 7245: sub get_timebased_id {
 7246:     my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
 7247:         $maxtries) = @_;
 7248:     my ($newid,$error,$dellock);
 7249:     unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {  
 7250:         return ('','ok','invalid call to get suffix');
 7251:     }
 7252: 
 7253: # set defaults for any optional args for which values were not supplied
 7254:     if ($who eq '') {
 7255:         $who = $env{'user.name'}.':'.$env{'user.domain'};
 7256:     }
 7257:     if (!$locktries) {
 7258:         $locktries = 3;
 7259:     }
 7260:     if (!$maxtries) {
 7261:         $maxtries = 10;
 7262:     }
 7263:     
 7264:     if (($cdom eq '') || ($cnum eq '')) {
 7265:         if ($env{'request.course.id'}) {
 7266:             $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 7267:             $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 7268:         }
 7269:         if (($cdom eq '') || ($cnum eq '')) {
 7270:             return ('','ok','call to get suffix not in course context');
 7271:         }
 7272:     }
 7273: 
 7274: # construct locking item
 7275:     my $lockhash = {
 7276:                       $prefix."\0".'locked_'.$keyid => $who,
 7277:                    };
 7278:     my $tries = 0;
 7279: 
 7280: # attempt to get lock on nohist_$namespace file
 7281:     my $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
 7282:     while (($gotlock ne 'ok') && $tries <$locktries) {
 7283:         $tries ++;
 7284:         sleep 1;
 7285:         $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
 7286:     }
 7287: 
 7288: # attempt to get unique identifier, based on current timestamp
 7289:     if ($gotlock eq 'ok') {
 7290:         my %inuse = &Apache::lonnet::dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
 7291:         my $id = time;
 7292:         $newid = $id;
 7293:         if ($idtype eq 'addcode') {
 7294:             $newid .= &sixnum_code();
 7295:         }
 7296:         my $idtries = 0;
 7297:         while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
 7298:             if ($idtype eq 'concat') {
 7299:                 $newid = $id.$idtries;
 7300:             } elsif ($idtype eq 'addcode') {
 7301:                 $newid = $newid.&sixnum_code();
 7302:             } else {
 7303:                 $newid ++;
 7304:             }
 7305:             $idtries ++;
 7306:         }
 7307:         if (!exists($inuse{$prefix."\0".$newid})) {
 7308:             my %new_item =  (
 7309:                               $prefix."\0".$newid => $who,
 7310:                             );
 7311:             my $putresult = &Apache::lonnet::put('nohist_'.$namespace,\%new_item,
 7312:                                                  $cdom,$cnum);
 7313:             if ($putresult ne 'ok') {
 7314:                 undef($newid);
 7315:                 $error = 'error saving new item: '.$putresult;
 7316:             }
 7317:         } else {
 7318:              undef($newid);
 7319:              $error = ('error: no unique suffix available for the new item ');
 7320:         }
 7321: #  remove lock
 7322:         my @del_lock = ($prefix."\0".'locked_'.$keyid);
 7323:         $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
 7324:     } else {
 7325:         $error = "error: could not obtain lockfile\n";
 7326:         $dellock = 'ok';
 7327:         if (($prefix eq 'paste') && ($namespace eq 'courseeditor') && ($keyid eq 'num')) {
 7328:             $dellock = 'nolock';
 7329:         }
 7330:     }
 7331:     return ($newid,$dellock,$error);
 7332: }
 7333: 
 7334: sub sixnum_code {
 7335:     my $code;
 7336:     for (0..6) {
 7337:         $code .= int( rand(9) );
 7338:     }
 7339:     return $code;
 7340: }
 7341: 
 7342: # -------------------------------------------------- portfolio access checking
 7343: 
 7344: sub portfolio_access {
 7345:     my ($requrl,$clientip) = @_;
 7346:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
 7347:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group,$clientip);
 7348:     if ($result) {
 7349:         my %setters;
 7350:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 7351:             my ($startblock,$endblock) =
 7352:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
 7353:             if ($startblock && $endblock) {
 7354:                 return 'B';
 7355:             }
 7356:         } else {
 7357:             my ($startblock,$endblock) =
 7358:                 &Apache::loncommon::blockcheck(\%setters,'port');
 7359:             if ($startblock && $endblock) {
 7360:                 return 'B';
 7361:             }
 7362:         }
 7363:     }
 7364:     if ($result eq 'ok') {
 7365:        return 'F';
 7366:     } elsif ($result =~ /^[^:]+:guest_/) {
 7367:        return 'A';
 7368:     }
 7369:     return '';
 7370: }
 7371: 
 7372: sub get_portfolio_access {
 7373:     my ($udom,$unum,$file_name,$group,$clientip,$access_hash) = @_;
 7374: 
 7375:     if (!ref($access_hash)) {
 7376: 	my $current_perms = &get_portfile_permissions($udom,$unum);
 7377: 	my %access_controls = &get_access_controls($current_perms,$group,
 7378: 						   $file_name);
 7379: 	$access_hash = $access_controls{$file_name};
 7380:     }
 7381: 
 7382:     my ($public,$guest,@domains,@users,@courses,@groups,@ips);
 7383:     my $now = time;
 7384:     if (ref($access_hash) eq 'HASH') {
 7385:         foreach my $key (keys(%{$access_hash})) {
 7386:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
 7387:             if ($start > $now) {
 7388:                 next;
 7389:             }
 7390:             if ($end && $end<$now) {
 7391:                 next;
 7392:             }
 7393:             if ($scope eq 'public') {
 7394:                 $public = $key;
 7395:                 last;
 7396:             } elsif ($scope eq 'guest') {
 7397:                 $guest = $key;
 7398:             } elsif ($scope eq 'domains') {
 7399:                 push(@domains,$key);
 7400:             } elsif ($scope eq 'users') {
 7401:                 push(@users,$key);
 7402:             } elsif ($scope eq 'course') {
 7403:                 push(@courses,$key);
 7404:             } elsif ($scope eq 'group') {
 7405:                 push(@groups,$key);
 7406:             } elsif ($scope eq 'ip') {
 7407:                 push(@ips,$key);
 7408:             }
 7409:         }
 7410:         if ($public) {
 7411:             return 'ok';
 7412:         } elsif (@ips > 0) {
 7413:             my $allowed;
 7414:             foreach my $ipkey (@ips) {
 7415:                 if (ref($access_hash->{$ipkey}{'ip'}) eq 'ARRAY') {
 7416:                     if (&Apache::loncommon::check_ip_acc(join(',',@{$access_hash->{$ipkey}{'ip'}}),$clientip)) {
 7417:                         $allowed = 1;
 7418:                         last; 
 7419:                     }
 7420:                 }
 7421:             }
 7422:             if ($allowed) {
 7423:                 return 'ok';
 7424:             }
 7425:         }
 7426:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 7427:             if ($guest) {
 7428:                 return $guest;
 7429:             }
 7430:         } else {
 7431:             if (@domains > 0) {
 7432:                 foreach my $domkey (@domains) {
 7433:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
 7434:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
 7435:                             return 'ok';
 7436:                         }
 7437:                     }
 7438:                 }
 7439:             }
 7440:             if (@users > 0) {
 7441:                 foreach my $userkey (@users) {
 7442:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
 7443:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
 7444:                             if (ref($item) eq 'HASH') {
 7445:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
 7446:                                     ($item->{'udom'} eq $env{'user.domain'})) {
 7447:                                     return 'ok';
 7448:                                 }
 7449:                             }
 7450:                         }
 7451:                     } 
 7452:                 }
 7453:             }
 7454:             my %roleshash;
 7455:             my @courses_and_groups = @courses;
 7456:             push(@courses_and_groups,@groups); 
 7457:             if (@courses_and_groups > 0) {
 7458:                 my (%allgroups,%allroles); 
 7459:                 my ($start,$end,$role,$sec,$group);
 7460:                 foreach my $envkey (%env) {
 7461:                     if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
 7462:                         my $cid = $2.'_'.$3; 
 7463:                         if ($1 eq 'gr') {
 7464:                             $group = $4;
 7465:                             $allgroups{$cid}{$group} = $env{$envkey};
 7466:                         } else {
 7467:                             if ($4 eq '') {
 7468:                                 $sec = 'none';
 7469:                             } else {
 7470:                                 $sec = $4;
 7471:                             }
 7472:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
 7473:                         }
 7474:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
 7475:                         my $cid = $2.'_'.$3;
 7476:                         if ($4 eq '') {
 7477:                             $sec = 'none';
 7478:                         } else {
 7479:                             $sec = $4;
 7480:                         }
 7481:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
 7482:                     }
 7483:                 }
 7484:                 if (keys(%allroles) == 0) {
 7485:                     return;
 7486:                 }
 7487:                 foreach my $key (@courses_and_groups) {
 7488:                     my %content = %{$$access_hash{$key}};
 7489:                     my $cnum = $content{'number'};
 7490:                     my $cdom = $content{'domain'};
 7491:                     my $cid = $cdom.'_'.$cnum;
 7492:                     if (!exists($allroles{$cid})) {
 7493:                         next;
 7494:                     }    
 7495:                     foreach my $role_id (keys(%{$content{'roles'}})) {
 7496:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
 7497:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
 7498:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
 7499:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
 7500:                         foreach my $role (keys(%{$allroles{$cid}})) {
 7501:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
 7502:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
 7503:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
 7504:                                         if (grep/^all$/,@sections) {
 7505:                                             return 'ok';
 7506:                                         } else {
 7507:                                             if (grep/^$sec$/,@sections) {
 7508:                                                 return 'ok';
 7509:                                             }
 7510:                                         }
 7511:                                     }
 7512:                                 }
 7513:                                 if (keys(%{$allgroups{$cid}}) == 0) {
 7514:                                     if (grep/^none$/,@groups) {
 7515:                                         return 'ok';
 7516:                                     }
 7517:                                 } else {
 7518:                                     if (grep/^all$/,@groups) {
 7519:                                         return 'ok';
 7520:                                     } 
 7521:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
 7522:                                         if (grep/^$group$/,@groups) {
 7523:                                             return 'ok';
 7524:                                         }
 7525:                                     }
 7526:                                 } 
 7527:                             }
 7528:                         }
 7529:                     }
 7530:                 }
 7531:             }
 7532:             if ($guest) {
 7533:                 return $guest;
 7534:             }
 7535:         }
 7536:     }
 7537:     return;
 7538: }
 7539: 
 7540: sub course_group_datechecker {
 7541:     my ($dates,$now,$status) = @_;
 7542:     my ($start,$end) = split(/\./,$dates);
 7543:     if (!$start && !$end) {
 7544:         return 'ok';
 7545:     }
 7546:     if (grep/^active$/,@{$status}) {
 7547:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
 7548:             return 'ok';
 7549:         }
 7550:     }
 7551:     if (grep/^previous$/,@{$status}) {
 7552:         if ($end > $now ) {
 7553:             return 'ok';
 7554:         }
 7555:     }
 7556:     if (grep/^future$/,@{$status}) {
 7557:         if ($start > $now) {
 7558:             return 'ok';
 7559:         }
 7560:     }
 7561:     return; 
 7562: }
 7563: 
 7564: sub parse_portfolio_url {
 7565:     my ($url) = @_;
 7566: 
 7567:     my ($type,$udom,$unum,$group,$file_name);
 7568:     
 7569:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
 7570: 	$type = 1;
 7571:         $udom = $1;
 7572:         $unum = $2;
 7573:         $file_name = $3;
 7574:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
 7575: 	$type = 2;
 7576:         $udom = $1;
 7577:         $unum = $2;
 7578:         $group = $3;
 7579:         $file_name = $3.'/'.$4;
 7580:     }
 7581:     if (wantarray) {
 7582: 	return ($type,$udom,$unum,$file_name,$group);
 7583:     }
 7584:     return $type;
 7585: }
 7586: 
 7587: sub is_portfolio_url {
 7588:     my ($url) = @_;
 7589:     return scalar(&parse_portfolio_url($url));
 7590: }
 7591: 
 7592: sub is_portfolio_file {
 7593:     my ($file) = @_;
 7594:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
 7595:         return 1;
 7596:     }
 7597:     return;
 7598: }
 7599: 
 7600: sub usertools_access {
 7601:     my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
 7602:     my ($access,%tools);
 7603:     if ($context eq '') {
 7604:         $context = 'tools';
 7605:     }
 7606:     if ($context eq 'requestcourses') {
 7607:         %tools = (
 7608:                       official   => 1,
 7609:                       unofficial => 1,
 7610:                       community  => 1,
 7611:                       textbook   => 1,
 7612:                       placement  => 1,
 7613:                       lti        => 1,
 7614:                  );
 7615:     } elsif ($context eq 'requestauthor') {
 7616:         %tools = (
 7617:                       requestauthor => 1,
 7618:                  );
 7619:     } else {
 7620:         %tools = (
 7621:                       aboutme   => 1,
 7622:                       blog      => 1,
 7623:                       webdav    => 1,
 7624:                       portfolio => 1,
 7625:                  );
 7626:     }
 7627:     return if (!defined($tools{$tool}));
 7628: 
 7629:     if (($udom eq '') || ($uname eq '')) {
 7630:         $udom = $env{'user.domain'};
 7631:         $uname = $env{'user.name'};
 7632:     }
 7633: 
 7634:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 7635:         if ($action ne 'reload') {
 7636:             if ($context eq 'requestcourses') {
 7637:                 return $env{'environment.canrequest.'.$tool};
 7638:             } elsif ($context eq 'requestauthor') {
 7639:                 return $env{'environment.canrequest.author'};
 7640:             } else {
 7641:                 return $env{'environment.availabletools.'.$tool};
 7642:             }
 7643:         }
 7644:     }
 7645: 
 7646:     my ($toolstatus,$inststatus,$envkey);
 7647:     if ($context eq 'requestauthor') {
 7648:         $envkey = $context; 
 7649:     } else {
 7650:         $envkey = $context.'.'.$tool;
 7651:     }
 7652: 
 7653:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
 7654:          ($action ne 'reload')) {
 7655:         $toolstatus = $env{'environment.'.$envkey};
 7656:         $inststatus = $env{'environment.inststatus'};
 7657:     } else {
 7658:         if (ref($userenvref) eq 'HASH') {
 7659:             $toolstatus = $userenvref->{$envkey};
 7660:             $inststatus = $userenvref->{'inststatus'};
 7661:         } else {
 7662:             my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
 7663:             $toolstatus = $userenv{$envkey};
 7664:             $inststatus = $userenv{'inststatus'};
 7665:         }
 7666:     }
 7667: 
 7668:     if ($toolstatus ne '') {
 7669:         if ($toolstatus) {
 7670:             $access = 1;
 7671:         } else {
 7672:             $access = 0;
 7673:         }
 7674:         return $access;
 7675:     }
 7676: 
 7677:     my ($is_adv,%domdef);
 7678:     if (ref($is_advref) eq 'HASH') {
 7679:         $is_adv = $is_advref->{'is_adv'};
 7680:     } else {
 7681:         $is_adv = &is_advanced_user($udom,$uname);
 7682:     }
 7683:     if (ref($domdefref) eq 'HASH') {
 7684:         %domdef = %{$domdefref};
 7685:     } else {
 7686:         %domdef = &get_domain_defaults($udom);
 7687:     }
 7688:     if (ref($domdef{$tool}) eq 'HASH') {
 7689:         if ($is_adv) {
 7690:             if ($domdef{$tool}{'_LC_adv'} ne '') {
 7691:                 if ($domdef{$tool}{'_LC_adv'}) { 
 7692:                     $access = 1;
 7693:                 } else {
 7694:                     $access = 0;
 7695:                 }
 7696:                 return $access;
 7697:             }
 7698:         }
 7699:         if ($inststatus ne '') {
 7700:             my ($hasaccess,$hasnoaccess);
 7701:             foreach my $affiliation (split(/:/,$inststatus)) {
 7702:                 if ($domdef{$tool}{$affiliation} ne '') { 
 7703:                     if ($domdef{$tool}{$affiliation}) {
 7704:                         $hasaccess = 1;
 7705:                     } else {
 7706:                         $hasnoaccess = 1;
 7707:                     }
 7708:                 }
 7709:             }
 7710:             if ($hasaccess || $hasnoaccess) {
 7711:                 if ($hasaccess) {
 7712:                     $access = 1;
 7713:                 } elsif ($hasnoaccess) {
 7714:                     $access = 0; 
 7715:                 }
 7716:                 return $access;
 7717:             }
 7718:         } else {
 7719:             if ($domdef{$tool}{'default'} ne '') {
 7720:                 if ($domdef{$tool}{'default'}) {
 7721:                     $access = 1;
 7722:                 } elsif ($domdef{$tool}{'default'} == 0) {
 7723:                     $access = 0;
 7724:                 }
 7725:                 return $access;
 7726:             }
 7727:         }
 7728:     } else {
 7729:         if (($context eq 'tools') && ($tool ne 'webdav')) {
 7730:             $access = 1;
 7731:         } else {
 7732:             $access = 0;
 7733:         }
 7734:         return $access;
 7735:     }
 7736: }
 7737: 
 7738: sub is_course_owner {
 7739:     my ($cdom,$cnum,$udom,$uname) = @_;
 7740:     if (($udom eq '') || ($uname eq '')) {
 7741:         $udom = $env{'user.domain'};
 7742:         $uname = $env{'user.name'};
 7743:     }
 7744:     unless (($udom eq '') || ($uname eq '')) {
 7745:         if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
 7746:             if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
 7747:                 return 1;
 7748:             } else {
 7749:                 my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
 7750:                 if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
 7751:                     return 1;
 7752:                 }
 7753:             }
 7754:         }
 7755:     }
 7756:     return;
 7757: }
 7758: 
 7759: sub is_advanced_user {
 7760:     my ($udom,$uname) = @_;
 7761:     if ($udom ne '' && $uname ne '') {
 7762:         if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 7763:             if (wantarray) {
 7764:                 return ($env{'user.adv'},$env{'user.author'});
 7765:             } else {
 7766:                 return $env{'user.adv'};
 7767:             }
 7768:         }
 7769:     }
 7770:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
 7771:     my %allroles;
 7772:     my ($is_adv,$is_author);
 7773:     foreach my $role (keys(%roleshash)) {
 7774:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
 7775:         my $area = '/'.$tdomain.'/'.$trest;
 7776:         if ($sec ne '') {
 7777:             $area .= '/'.$sec;
 7778:         }
 7779:         if (($area ne '') && ($trole ne '')) {
 7780:             my $spec=$trole.'.'.$area;
 7781:             if ($trole =~ /^cr\//) {
 7782:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
 7783:             } elsif ($trole ne 'gr') {
 7784:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
 7785:             }
 7786:             if ($trole eq 'au') {
 7787:                 $is_author = 1;
 7788:             }
 7789:         }
 7790:     }
 7791:     foreach my $role (keys(%allroles)) {
 7792:         last if ($is_adv);
 7793:         foreach my $item (split(/:/,$allroles{$role})) {
 7794:             if ($item ne '') {
 7795:                 my ($privilege,$restrictions)=split(/&/,$item);
 7796:                 if ($privilege eq 'adv') {
 7797:                     $is_adv = 1;
 7798:                     last;
 7799:                 }
 7800:             }
 7801:         }
 7802:     }
 7803:     if (wantarray) {
 7804:         return ($is_adv,$is_author);
 7805:     }
 7806:     return $is_adv;
 7807: }
 7808: 
 7809: sub check_can_request {
 7810:     my ($dom,$can_request,$request_domains,$uname,$udom) = @_;
 7811:     my $canreq = 0;
 7812:     if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
 7813:         $uname = $env{'user.name'};
 7814:         $udom = $env{'user.domain'};
 7815:     }
 7816:     my ($types,$typename) = &Apache::loncommon::course_types();
 7817:     my @options = ('approval','validate','autolimit');
 7818:     my $optregex = join('|',@options);
 7819:     if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
 7820:         foreach my $type (@{$types}) {
 7821:             if (&usertools_access($uname,$udom,$type,undef,
 7822:                                   'requestcourses')) {
 7823:                 $canreq ++;
 7824:                 if (ref($request_domains) eq 'HASH') {
 7825:                     push(@{$request_domains->{$type}},$udom);
 7826:                 }
 7827:                 if ($dom eq $udom) {
 7828:                     $can_request->{$type} = 1;
 7829:                 }
 7830:             }
 7831:             if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '') &&
 7832:                 ($env{'environment.reqcrsotherdom.'.$type} ne '')) {
 7833:                 my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
 7834:                 if (@curr > 0) {
 7835:                     foreach my $item (@curr) {
 7836:                         if (ref($request_domains) eq 'HASH') {
 7837:                             my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
 7838:                             if ($otherdom ne '') {
 7839:                                 if (ref($request_domains->{$type}) eq 'ARRAY') {
 7840:                                     unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
 7841:                                         push(@{$request_domains->{$type}},$otherdom);
 7842:                                     }
 7843:                                 } else {
 7844:                                     push(@{$request_domains->{$type}},$otherdom);
 7845:                                 }
 7846:                             }
 7847:                         }
 7848:                     }
 7849:                     unless ($dom eq $env{'user.domain'}) {
 7850:                         $canreq ++;
 7851:                         if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
 7852:                             $can_request->{$type} = 1;
 7853:                         }
 7854:                     }
 7855:                 }
 7856:             }
 7857:         }
 7858:     }
 7859:     return $canreq;
 7860: }
 7861: 
 7862: # ---------------------------------------------- Custom access rule evaluation
 7863: 
 7864: sub customaccess {
 7865:     my ($priv,$uri)=@_;
 7866:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
 7867:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
 7868:     $udom = &LONCAPA::clean_domain($udom);
 7869:     $ucrs = &LONCAPA::clean_username($ucrs);
 7870:     my $access=0;
 7871:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
 7872: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
 7873: 	if ($type eq 'user') {
 7874: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
 7875: 		my ($tdom,$tuname)=split(m{/},$scope);
 7876: 		if ($tdom) {
 7877: 		    if ($tdom ne $env{'user.domain'}) { next; }
 7878: 		}
 7879: 		if ($tuname) {
 7880: 		    if ($tuname ne $env{'user.name'}) { next; }
 7881: 		}
 7882: 		$access=($effect eq 'allow');
 7883: 		last;
 7884: 	    }
 7885: 	} else {
 7886: 	    if ($role) {
 7887: 		if ($role ne $urole) { next; }
 7888: 	    }
 7889: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
 7890: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
 7891: 		if ($tdom) {
 7892: 		    if ($tdom ne $udom) { next; }
 7893: 		}
 7894: 		if ($tcrs) {
 7895: 		    if ($tcrs ne $ucrs) { next; }
 7896: 		}
 7897: 		if ($tsec) {
 7898: 		    if ($tsec ne $usec) { next; }
 7899: 		}
 7900: 		$access=($effect eq 'allow');
 7901: 		last;
 7902: 	    }
 7903: 	    if ($realm eq '' && $role eq '') {
 7904: 		$access=($effect eq 'allow');
 7905: 	    }
 7906: 	}
 7907:     }
 7908:     return $access;
 7909: }
 7910: 
 7911: # ------------------------------------------------- Check for a user privilege
 7912: 
 7913: sub allowed {
 7914:     my ($priv,$uri,$symb,$role,$clientip,$noblockcheck)=@_;
 7915:     my $ver_orguri=$uri;
 7916:     $uri=&deversion($uri);
 7917:     my $orguri=$uri;
 7918:     $uri=&declutter($uri);
 7919: 
 7920:     if ($priv eq 'evb') {
 7921: # Evade communication block restrictions for specified role in a course
 7922:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
 7923:             return $1;
 7924:         } else {
 7925:             return;
 7926:         }
 7927:     }
 7928: 
 7929:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
 7930: # Free bre access to adm and meta resources
 7931:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard|ext\.tool)$})) 
 7932: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
 7933: 	&& ($priv eq 'bre')) {
 7934: 	return 'F';
 7935:     }
 7936: 
 7937: # Free bre access to user's own portfolio contents
 7938:     my ($space,$domain,$name,@dir)=split('/',$uri);
 7939:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
 7940: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
 7941:         my %setters;
 7942:         my ($startblock,$endblock) = 
 7943:             &Apache::loncommon::blockcheck(\%setters,'port');
 7944:         if ($startblock && $endblock) {
 7945:             return 'B';
 7946:         } else {
 7947:             return 'F';
 7948:         }
 7949:     }
 7950: 
 7951: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
 7952:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
 7953:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
 7954:         if (exists($env{'request.course.id'})) {
 7955:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 7956:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 7957:             if (($domain eq $cdom) && ($name eq $cnum)) {
 7958:                 my $courseprivid=$env{'request.course.id'};
 7959:                 $courseprivid=~s/\_/\//;
 7960:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
 7961:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
 7962:                     return $1; 
 7963:                 } else {
 7964:                     if ($env{'request.course.sec'}) {
 7965:                         $courseprivid.='/'.$env{'request.course.sec'};
 7966:                     }
 7967:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
 7968:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
 7969:                         return $2;
 7970:                     }
 7971:                 }
 7972:             }
 7973:         }
 7974:     }
 7975: 
 7976: # Free bre to public access
 7977: 
 7978:     if ($priv eq 'bre') {
 7979:         my $copyright;
 7980:         unless ($uri =~ /ext\.tool/) {
 7981:             $copyright=&metadata($uri,'copyright');
 7982:         }
 7983: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
 7984:            return 'F'; 
 7985:         }
 7986:         if ($copyright eq 'priv') {
 7987:             $uri=~/([^\/]+)\/([^\/]+)\//;
 7988: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
 7989: 		return '';
 7990:             }
 7991:         }
 7992:         if ($copyright eq 'domain') {
 7993:             $uri=~/([^\/]+)\/([^\/]+)\//;
 7994: 	    unless (($env{'user.domain'} eq $1) ||
 7995:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
 7996: 		return '';
 7997:             }
 7998:         }
 7999:         if ($env{'request.role'}=~ /li\.\//) {
 8000:             # Library role, so allow browsing of resources in this domain.
 8001:             return 'F';
 8002:         }
 8003:         if ($copyright eq 'custom') {
 8004: 	    unless (&customaccess($priv,$uri)) { return ''; }
 8005:         }
 8006:     }
 8007:     # Domain coordinator is trying to create a course
 8008:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
 8009:         # uri is the requested domain in this case.
 8010:         # comparison to 'request.role.domain' shows if the user has selected
 8011:         # a role of dc for the domain in question.
 8012:         return 'F' if ($uri eq $env{'request.role.domain'});
 8013:     }
 8014: 
 8015:     my $thisallowed='';
 8016:     my $statecond=0;
 8017:     my $courseprivid='';
 8018: 
 8019:     my $ownaccess;
 8020:     # Community Coordinator or Assistant Co-author browsing resource space.
 8021:     if (($priv eq 'bro') && ($env{'user.author'})) {
 8022:         if ($uri eq '') {
 8023:             $ownaccess = 1;
 8024:         } else {
 8025:             if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
 8026:                 my $udom = $env{'user.domain'};
 8027:                 my $uname = $env{'user.name'};
 8028:                 if ($uri =~ m{^\Q$udom\E/?$}) {
 8029:                     $ownaccess = 1;
 8030:                 } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
 8031:                     unless ($uri =~ m{\.\./}) {
 8032:                         $ownaccess = 1;
 8033:                     }
 8034:                 } elsif (($udom ne 'public') && ($uname ne 'public')) {
 8035:                     my $now = time;
 8036:                     if ($uri =~ m{^([^/]+)/?$}) {
 8037:                         my $adom = $1;
 8038:                         foreach my $key (keys(%env)) {
 8039:                             if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
 8040:                                 my ($start,$end) = split('.',$env{$key});
 8041:                                 if (($now >= $start) && (!$end || $end < $now)) {
 8042:                                     $ownaccess = 1;
 8043:                                     last;
 8044:                                 }
 8045:                             }
 8046:                         }
 8047:                     } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
 8048:                         my $adom = $1;
 8049:                         my $aname = $2;
 8050:                         foreach my $role ('ca','aa') { 
 8051:                             if ($env{"user.role.$role./$adom/$aname"}) {
 8052:                                 my ($start,$end) =
 8053:                                     split('.',$env{"user.role.$role./$adom/$aname"});
 8054:                                 if (($now >= $start) && (!$end || $end < $now)) {
 8055:                                     $ownaccess = 1;
 8056:                                     last;
 8057:                                 }
 8058:                             }
 8059:                         }
 8060:                     }
 8061:                 }
 8062:             }
 8063:         }
 8064:     }
 8065: 
 8066: # Course
 8067: 
 8068:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
 8069:         unless (($priv eq 'bro') && (!$ownaccess)) {
 8070:             $thisallowed.=$1;
 8071:         }
 8072:     }
 8073: 
 8074: # Domain
 8075: 
 8076:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
 8077:        =~/\Q$priv\E\&([^\:]*)/) {
 8078:         unless (($priv eq 'bro') && (!$ownaccess)) {
 8079:             $thisallowed.=$1;
 8080:         }
 8081:     }
 8082: 
 8083: # User who is not author or co-author might still be able to edit
 8084: # resource of an author in the domain (e.g., if Domain Coordinator).
 8085:     if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
 8086:         (&allowed('mdc',$env{'request.course.id'}))) {
 8087:         if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
 8088:             $thisallowed.=$1;
 8089:         }
 8090:     }
 8091: 
 8092: # Course: uri itself is a course
 8093:     my $courseuri=$uri;
 8094:     $courseuri=~s/\_(\d)/\/$1/;
 8095:     $courseuri=~s/^([^\/])/\/$1/;
 8096: 
 8097:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
 8098:        =~/\Q$priv\E\&([^\:]*)/) {
 8099:         if ($priv eq 'mip') {
 8100:             my $rem = $1;
 8101:             if (($uri ne '') && ($env{'request.course.id'} eq $uri) &&
 8102:                 ($env{'course.'.$env{'request.course.id'}.'.internal.courseowner'} eq $env{'user.name'}.':'.$env{'user.domain'})) {
 8103:                 my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 8104:                 if ($cdom ne '') {
 8105:                     my %passwdconf = &get_passwdconf($cdom);
 8106:                     if (ref($passwdconf{'crsownerchg'}) eq 'HASH') {
 8107:                         if (ref($passwdconf{'crsownerchg'}{'by'}) eq 'ARRAY') {
 8108:                             if (@{$passwdconf{'crsownerchg'}{'by'}}) {
 8109:                                 my @inststatuses = split(':',$env{'environment.inststatus'});
 8110:                                 unless (@inststatuses) {
 8111:                                     @inststatuses = ('default');
 8112:                                 }
 8113:                                 foreach my $status (@inststatuses) {
 8114:                                     if (grep(/^\Q$status\E$/,@{$passwdconf{'crsownerchg'}{'by'}})) {
 8115:                                         $thisallowed.=$rem;
 8116:                                     }
 8117:                                 }
 8118:                             }
 8119:                         }
 8120:                     }
 8121:                 }
 8122:             }
 8123:         } else {
 8124:             unless (($priv eq 'bro') && (!$ownaccess)) {
 8125:                 $thisallowed.=$1;
 8126:             }
 8127:         }
 8128:     }
 8129: 
 8130: # URI is an uploaded document for this course, default permissions don't matter
 8131: # not allowing 'edit' access (editupload) to uploaded course docs
 8132:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
 8133: 	$thisallowed='';
 8134:         my ($match)=&is_on_map($uri);
 8135:         if ($match) {
 8136:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
 8137:                   =~/\Q$priv\E\&([^\:]*)/) {
 8138:                 my $value = $1;
 8139:                 my $deeplinkblock = &deeplink_check($priv,$symb,$uri);
 8140:                 if ($deeplinkblock) {
 8141:                     $thisallowed='D';
 8142:                 } elsif ($noblockcheck) {
 8143:                     $thisallowed.=$value;
 8144:                 } else {
 8145:                     my @blockers = &has_comm_blocking($priv,$symb,$uri);
 8146:                     if (@blockers > 0) {
 8147:                         $thisallowed = 'B';
 8148:                     } else {
 8149:                         $thisallowed.=$value;
 8150:                     }
 8151:                 }
 8152:             }
 8153:         } else {
 8154:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
 8155:             if ($refuri) {
 8156:                 if ($refuri =~ m|^/adm/|) {
 8157:                     $thisallowed='F';
 8158:                 } else {
 8159:                     $refuri=&declutter($refuri);
 8160:                     my ($match) = &is_on_map($refuri);
 8161:                     if ($match) {
 8162:                         my $deeplinkblock = &deeplink_check($priv,$symb,$refuri);
 8163:                         if ($deeplinkblock) {
 8164:                             $thisallowed='D';
 8165:                         } elsif ($noblockcheck) {
 8166:                             $thisallowed='F';
 8167:                         } else {
 8168:                             my @blockers = &has_comm_blocking($priv,$symb,$refuri);
 8169:                             if (@blockers > 0) {
 8170:                                 $thisallowed = 'B';
 8171:                             } else {
 8172:                                 $thisallowed='F';
 8173:                             }
 8174:                         }
 8175:                     }
 8176:                 }
 8177:             }
 8178:         }
 8179:     }
 8180: 
 8181:     if ($priv eq 'bre'
 8182: 	&& $thisallowed ne 'F' 
 8183: 	&& $thisallowed ne '2'
 8184: 	&& &is_portfolio_url($uri)) {
 8185: 	$thisallowed = &portfolio_access($uri,$clientip);
 8186:     }
 8187: 
 8188: # Full access at system, domain or course-wide level? Exit.
 8189:     if ($thisallowed=~/F/) {
 8190: 	return 'F';
 8191:     }
 8192: 
 8193: # If this is generating or modifying users, exit with special codes
 8194: 
 8195:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
 8196: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
 8197: 	    my ($audom,$auname)=split('/',$uri);
 8198: # no author name given, so this just checks on the general right to make a co-author in this domain
 8199: 	    unless ($auname) { return $thisallowed; }
 8200: # an author name is given, so we are about to actually make a co-author for a certain account
 8201: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
 8202: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
 8203: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
 8204: 	}
 8205: 	return $thisallowed;
 8206:     }
 8207: #
 8208: # Gathered so far: system, domain and course wide privileges
 8209: #
 8210: # Course: See if uri or referer is an individual resource that is part of 
 8211: # the course
 8212: 
 8213:     if ($env{'request.course.id'}) {
 8214: 
 8215: # If this is modifying password (internal auth) domains must match for user and user's role.
 8216: 
 8217:         if ($priv eq 'mip') {
 8218:             if ($env{'user.domain'} eq $env{'request.role.domain'}) {
 8219:                 return $thisallowed;
 8220:             } else {
 8221:                 return '';
 8222:             }
 8223:         }
 8224: 
 8225:        $courseprivid=$env{'request.course.id'};
 8226:        if ($env{'request.course.sec'}) {
 8227:           $courseprivid.='/'.$env{'request.course.sec'};
 8228:        }
 8229:        $courseprivid=~s/\_/\//;
 8230:        my $checkreferer=1;
 8231:        my ($match,$cond)=&is_on_map($uri);
 8232:        if ($match) {
 8233:            $statecond=$cond;
 8234:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 8235:                =~/\Q$priv\E\&([^\:]*)/) {
 8236:                my $value = $1;
 8237:                if ($priv eq 'bre') {
 8238:                    if ($noblockcheck) {
 8239:                        $thisallowed.=$value;
 8240:                    } else {
 8241:                        my @blockers = &has_comm_blocking($priv,$symb,$uri);
 8242:                        if (@blockers > 0) {
 8243:                            $thisallowed = 'B';
 8244:                        } else {
 8245:                            $thisallowed.=$value;
 8246:                        }
 8247:                    }
 8248:                } else {
 8249:                    $thisallowed.=$value;
 8250:                }
 8251:                $checkreferer=0;
 8252:            }
 8253:        }
 8254:        
 8255:        if ($checkreferer) {
 8256: 	  my $refuri=$env{'httpref.'.$orguri};
 8257:             unless ($refuri) {
 8258:                 foreach my $key (keys(%env)) {
 8259: 		    if ($key=~/^httpref\..*\*/) {
 8260: 			my $pattern=$key;
 8261:                         $pattern=~s/^httpref\.\/res\///;
 8262:                         $pattern=~s/\*/\[\^\/\]\+/g;
 8263:                         $pattern=~s/\//\\\//g;
 8264:                         if ($orguri=~/$pattern/) {
 8265: 			    $refuri=$env{$key};
 8266:                         }
 8267:                     }
 8268:                 }
 8269:             }
 8270: 
 8271:          if ($refuri) { 
 8272: 	  $refuri=&declutter($refuri);
 8273:           my ($match,$cond)=&is_on_map($refuri);
 8274:             if ($match) {
 8275:               my $refstatecond=$cond;
 8276:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 8277:                   =~/\Q$priv\E\&([^\:]*)/) {
 8278:                   my $value = $1;
 8279:                   if ($priv eq 'bre') {
 8280:                       my $deeplinkblock = &deeplink_check($priv,$symb,$refuri);
 8281:                       if ($deeplinkblock) {
 8282:                           $thisallowed = 'D';
 8283:                       } elsif ($noblockcheck) {
 8284:                           $thisallowed.=$value;
 8285:                       } else {
 8286:                           my @blockers = &has_comm_blocking($priv,$symb,$refuri);
 8287:                           if (@blockers > 0) {
 8288:                               $thisallowed = 'B';
 8289:                           } else {
 8290:                               $thisallowed.=$value;
 8291:                           }
 8292:                       }
 8293:                   } else {
 8294:                       $thisallowed.=$value;
 8295:                   }
 8296:                   $uri=$refuri;
 8297:                   $statecond=$refstatecond;
 8298:               }
 8299:           }
 8300:         }
 8301:        }
 8302:    }
 8303: 
 8304: #
 8305: # Gathered now: all privileges that could apply, and condition number
 8306: # 
 8307: #
 8308: # Full or no access?
 8309: #
 8310: 
 8311:     if ($thisallowed=~/F/) {
 8312: 	return 'F';
 8313:     }
 8314: 
 8315:     unless ($thisallowed) {
 8316:         return '';
 8317:     }
 8318: 
 8319: # Restrictions exist, deal with them
 8320: #
 8321: #   C:according to course preferences
 8322: #   R:according to resource settings
 8323: #   L:unless locked
 8324: #   X:according to user session state
 8325: #
 8326: 
 8327: # Possibly locked functionality, check all courses
 8328: # Locks might take effect only after 10 minutes cache expiration for other
 8329: # courses, and 2 minutes for current course
 8330: 
 8331:     my $envkey;
 8332:     if ($thisallowed=~/L/) {
 8333:         foreach $envkey (keys(%env)) {
 8334:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
 8335:                my $courseid=$2;
 8336:                my $roleid=$1.'.'.$2;
 8337:                $courseid=~s/^\///;
 8338:                my $expiretime=600;
 8339:                if ($env{'request.role'} eq $roleid) {
 8340: 		  $expiretime=120;
 8341:                }
 8342: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
 8343:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
 8344:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
 8345: 		   &coursedescription($courseid,{'freshen_cache' => 1});
 8346:                }
 8347:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
 8348:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
 8349: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
 8350:                        &log($env{'user.domain'},$env{'user.name'},
 8351:                             $env{'user.home'},
 8352:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
 8353:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 8354:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 8355: 		       return '';
 8356:                    }
 8357:                }
 8358:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
 8359:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
 8360: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
 8361:                        &log($env{'user.domain'},$env{'user.name'},
 8362:                             $env{'user.home'},
 8363:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
 8364:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 8365:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 8366: 		       return '';
 8367:                    }
 8368:                }
 8369: 	   }
 8370:        }
 8371:     }
 8372:    
 8373: #
 8374: # Rest of the restrictions depend on selected course
 8375: #
 8376: 
 8377:     unless ($env{'request.course.id'}) {
 8378: 	if ($thisallowed eq 'A') {
 8379: 	    return 'A';
 8380:         } elsif ($thisallowed eq 'B') {
 8381:             return 'B';
 8382: 	} else {
 8383: 	    return '1';
 8384: 	}
 8385:     }
 8386: 
 8387: #
 8388: # Now user is definitely in a course
 8389: #
 8390: 
 8391: 
 8392: # Course preferences
 8393: 
 8394:    if ($thisallowed=~/C/) {
 8395:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 8396:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
 8397:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
 8398: 	   =~/\Q$rolecode\E/) {
 8399: 	   if (($priv ne 'pch') && ($priv ne 'plc') && ($priv ne 'pac')) {
 8400: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 8401: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
 8402: 			$env{'request.course.id'});
 8403: 	   }
 8404:            return '';
 8405:        }
 8406: 
 8407:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
 8408: 	   =~/\Q$unamedom\E/) {
 8409: 	   if (($priv ne 'pch') && ($priv ne 'plc') && ($priv ne 'pac')) {
 8410: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
 8411: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
 8412: 			$env{'request.course.id'});
 8413: 	   }
 8414:            return '';
 8415:        }
 8416:    }
 8417: 
 8418: # Resource preferences
 8419: 
 8420:    if ($thisallowed=~/R/) {
 8421:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 8422:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
 8423: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
 8424: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 8425: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
 8426: 	   }
 8427: 	   return '';
 8428:        }
 8429:    }
 8430: 
 8431: # Restricted by state or randomout?
 8432: 
 8433:    if ($thisallowed=~/X/) {
 8434:       if ($env{'acc.randomout'}) {
 8435: 	 if (!$symb) { $symb=&symbread($uri,1); }
 8436:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
 8437:             return ''; 
 8438:          }
 8439:       }
 8440:       if (&condval($statecond)) {
 8441: 	 return '2';
 8442:       } else {
 8443:          return '';
 8444:       }
 8445:    }
 8446: 
 8447:     if ($thisallowed eq 'A') {
 8448: 	return 'A';
 8449:     } elsif ($thisallowed eq 'B') {
 8450:         return 'B';
 8451:     } elsif ($thisallowed eq 'D') {
 8452:         return 'D';
 8453:     }
 8454:    return 'F';
 8455: }
 8456: 
 8457: # ------------------------------------------- Check construction space access
 8458: 
 8459: sub constructaccess {
 8460:     my ($url,$setpriv)=@_;
 8461: 
 8462: # We do not allow editing of previous versions of files
 8463:     if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
 8464: 
 8465: # Get username and domain from URL
 8466:     my ($ownername,$ownerdomain,$ownerhome);
 8467: 
 8468:     ($ownerdomain,$ownername) =
 8469:         ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)(?:/daxepage|/daxeopen)?/priv/($match_domain)/($match_username)(?:/|$)});
 8470: 
 8471: # The URL does not really point to any authorspace, forget it
 8472:     unless (($ownername) && ($ownerdomain)) { return ''; }
 8473: 
 8474: # Now we need to see if the user has access to the authorspace of
 8475: # $ownername at $ownerdomain
 8476: 
 8477:     if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
 8478: # Real author for this?
 8479:        $ownerhome = $env{'user.home'};
 8480:        if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
 8481:           return ($ownername,$ownerdomain,$ownerhome);
 8482:        }
 8483:     } else {
 8484: # Co-author for this?
 8485:         if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
 8486:             exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
 8487:             $ownerhome = &homeserver($ownername,$ownerdomain);
 8488:             return ($ownername,$ownerdomain,$ownerhome);
 8489:         }
 8490:         if ($env{'request.course.id'}) {
 8491:             if (($ownername eq $env{'course.'.$env{'request.course.id'}.'.num'}) &&
 8492:                 ($ownerdomain eq $env{'course.'.$env{'request.course.id'}.'.domain'})) {
 8493:                 if (&allowed('mdc',$env{'request.course.id'})) {
 8494:                     $ownerhome = $env{'course.'.$env{'request.course.id'}.'.home'};
 8495:                     return ($ownername,$ownerdomain,$ownerhome);
 8496:                 }
 8497:             }
 8498:         }
 8499:     }
 8500: 
 8501: # We don't have any access right now. If we are not possibly going to do anything about this,
 8502: # we might as well leave
 8503:    unless ($setpriv) { return ''; }
 8504: 
 8505: # Backdoor access?
 8506:     my $allowed=&allowed('eco',$ownerdomain);
 8507: # Nope
 8508:     unless ($allowed) { return ''; }
 8509: # Looks like we may have access, but could be locked by the owner of the construction space
 8510:     if ($allowed eq 'U') {
 8511:         my %blocked=&get('environment',['domcoord.author'],
 8512:                          $ownerdomain,$ownername);
 8513: # Is blocked by owner
 8514:         if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
 8515:     }
 8516:     if (($allowed eq 'F') || ($allowed eq 'U')) {
 8517: # Grant temporary access
 8518:         my $then=$env{'user.login.time'};
 8519:         my $update=$env{'user.update.time'};
 8520:         if (!$update) { $update = $then; }
 8521:         my $refresh=$env{'user.refresh.time'};
 8522:         if (!$refresh) { $refresh = $update; }
 8523:         my $now = time;
 8524:         &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
 8525:                            $now,'ca','constructaccess');
 8526:         $ownerhome = &homeserver($ownername,$ownerdomain);
 8527:         return($ownername,$ownerdomain,$ownerhome);
 8528:     }
 8529: # No business here
 8530:     return '';
 8531: }
 8532: 
 8533: # ----------------------------------------------------------- Content Blocking
 8534: 
 8535: {
 8536: # Caches for faster Course Contents display where content blocking
 8537: # is in operation (i.e., interval param set) for timed quiz.
 8538: #
 8539: # User for whom data are being temporarily cached.
 8540: my $cacheduser='';
 8541: # Cached blockers for this user (a hash of blocking items). 
 8542: my %cachedblockers=();
 8543: # When the data were last cached.
 8544: my $cachedlast='';
 8545: 
 8546: sub load_all_blockers {
 8547:     my ($uname,$udom,$blocks)=@_;
 8548:     if (($uname ne '') && ($udom ne '')) { 
 8549:         if (($cacheduser eq $uname.':'.$udom) &&
 8550:             (abs($cachedlast-time)<5)) {
 8551:             return;
 8552:         }
 8553:     }
 8554:     $cachedlast=time;
 8555:     $cacheduser=$uname.':'.$udom;
 8556:     %cachedblockers = &get_commblock_resources($blocks);
 8557: }
 8558: 
 8559: sub get_comm_blocks {
 8560:     my ($cdom,$cnum) = @_;
 8561:     if ($cdom eq '' || $cnum eq '') {
 8562:         return unless ($env{'request.course.id'});
 8563:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 8564:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 8565:     }
 8566:     my %commblocks;
 8567:     my $hashid=$cdom.'_'.$cnum;
 8568:     my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
 8569:     if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
 8570:         %commblocks = %{$blocksref};
 8571:     } else {
 8572:         %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
 8573:         my $cachetime = 600;
 8574:         &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
 8575:     }
 8576:     return %commblocks;
 8577: }
 8578: 
 8579: sub get_commblock_resources {
 8580:     my ($blocks) = @_;
 8581:     my %blockers = ();
 8582:     return %blockers unless ($env{'request.course.id'});
 8583:     return %blockers if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
 8584:     my %commblocks;
 8585:     if (ref($blocks) eq 'HASH') {
 8586:         %commblocks = %{$blocks};
 8587:     } else {
 8588:         %commblocks = &get_comm_blocks();
 8589:     }
 8590:     return %blockers unless (keys(%commblocks) > 0); 
 8591:     my $navmap = Apache::lonnavmaps::navmap->new();
 8592:     return %blockers unless (ref($navmap));
 8593:     my $now = time;
 8594:     foreach my $block (keys(%commblocks)) {
 8595:         if ($block =~ /^(\d+)____(\d+)$/) {
 8596:             my ($start,$end) = ($1,$2);
 8597:             if ($start <= $now && $end >= $now) {
 8598:                 if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
 8599:                     if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
 8600:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
 8601:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
 8602:                                 $blockers{$block}{maps} = $commblocks{$block}{'blocks'}{'docs'}{'maps'}; 
 8603:                             }
 8604:                         }
 8605:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
 8606:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
 8607:                                 $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
 8608:                             }
 8609:                         }
 8610:                     }
 8611:                 }
 8612:             }
 8613:         } elsif ($block =~ /^firstaccess____(.+)$/) {
 8614:             my $item = $1;
 8615:             my @to_test;
 8616:             if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
 8617:                 if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
 8618:                     my @interval;
 8619:                     my $type = 'map';
 8620:                     if ($item eq 'course') {
 8621:                         $type = 'course';
 8622:                         @interval=&EXT("resource.0.interval");
 8623:                     } else {
 8624:                         if ($item =~ /___\d+___/) {
 8625:                             $type = 'resource';
 8626:                             @interval=&EXT("resource.0.interval",$item);
 8627:                             if (ref($navmap)) {                        
 8628:                                 my $res = $navmap->getBySymb($item); 
 8629:                                 push(@to_test,$res);
 8630:                             }
 8631:                         } else {
 8632:                             my $mapsymb = &symbread($item,1);
 8633:                             if ($mapsymb) {
 8634:                                 if (ref($navmap)) {
 8635:                                     my $mapres = $navmap->getBySymb($mapsymb);
 8636:                                     @to_test = $mapres->retrieveResources($mapres,undef,0,0,0,1);
 8637:                                     foreach my $res (@to_test) {
 8638:                                         my $symb = $res->symb();
 8639:                                         next if ($symb eq $mapsymb);
 8640:                                         if ($symb ne '') {
 8641:                                             @interval=&EXT("resource.0.interval",$symb);
 8642:                                             if ($interval[1] eq 'map') {
 8643:                                                 last;
 8644:                                             }
 8645:                                         }
 8646:                                     }
 8647:                                 }
 8648:                             }
 8649:                         }
 8650:                     }
 8651:                     if ($interval[0] =~ /^(\d+)/) {
 8652:                         my $timelimit = $1; 
 8653:                         my $first_access;
 8654:                         if ($type eq 'resource') {
 8655:                             $first_access=&get_first_access($interval[1],$item);
 8656:                         } elsif ($type eq 'map') {
 8657:                             $first_access=&get_first_access($interval[1],undef,$item);
 8658:                         } else {
 8659:                             $first_access=&get_first_access($interval[1]);
 8660:                         }
 8661:                         if ($first_access) {
 8662:                             my $timesup = $first_access+$timelimit;
 8663:                             if ($timesup > $now) {
 8664:                                 my $activeblock;
 8665:                                 foreach my $res (@to_test) {
 8666:                                     if ($res->answerable()) {
 8667:                                         $activeblock = 1;
 8668:                                         last;
 8669:                                     }
 8670:                                 }
 8671:                                 if ($activeblock) {
 8672:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
 8673:                                          if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
 8674:                                              $blockers{$block}{'maps'} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
 8675:                                          }
 8676:                                     }
 8677:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
 8678:                                         if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
 8679:                                             $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
 8680:                                         }
 8681:                                     }
 8682:                                 }
 8683:                             }
 8684:                         }
 8685:                     }
 8686:                 }
 8687:             }
 8688:         }
 8689:     }
 8690:     return %blockers;
 8691: }
 8692: 
 8693: sub has_comm_blocking {
 8694:     my ($priv,$symb,$uri,$blocks) = @_;
 8695:     my @blockers;
 8696:     return unless ($env{'request.course.id'});
 8697:     return unless ($priv eq 'bre');
 8698:     return if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
 8699:     return if ($env{'request.state'} eq 'construct');
 8700:     &load_all_blockers($env{'user.name'},$env{'user.domain'},$blocks);
 8701:     return unless (keys(%cachedblockers) > 0);
 8702:     my (%possibles,@symbs);
 8703:     if (!$symb) {
 8704:         $symb = &symbread($uri,1,1,1,\%possibles);
 8705:     }
 8706:     if ($symb) {
 8707:         @symbs = ($symb);
 8708:     } elsif (keys(%possibles)) { 
 8709:         @symbs = keys(%possibles);
 8710:     }
 8711:     my $noblock;
 8712:     foreach my $symb (@symbs) {
 8713:         last if ($noblock);
 8714:         my ($map,$resid,$resurl)=&decode_symb($symb);
 8715:         foreach my $block (keys(%cachedblockers)) {
 8716:             if ($block =~ /^firstaccess____(.+)$/) {
 8717:                 my $item = $1;
 8718:                 if (($item eq $map) || ($item eq $symb)) {
 8719:                     $noblock = 1;
 8720:                     last;
 8721:                 }
 8722:             }
 8723:             if (ref($cachedblockers{$block}) eq 'HASH') {
 8724:                 if (ref($cachedblockers{$block}{'resources'}) eq 'HASH') {
 8725:                     if ($cachedblockers{$block}{'resources'}{$symb}) {
 8726:                         unless (grep(/^\Q$block\E$/,@blockers)) {
 8727:                             push(@blockers,$block);
 8728:                         }
 8729:                     }
 8730:                 }
 8731:             }
 8732:             if (ref($cachedblockers{$block}{'maps'}) eq 'HASH') {
 8733:                 if ($cachedblockers{$block}{'maps'}{$map}) {
 8734:                     unless (grep(/^\Q$block\E$/,@blockers)) {
 8735:                         push(@blockers,$block);
 8736:                     }
 8737:                 }
 8738:             }
 8739:         }
 8740:     }
 8741:     return if ($noblock);
 8742:     return @blockers;
 8743: }
 8744: }
 8745: 
 8746: sub deeplink_check {
 8747:     my ($priv,$symb,$uri) = @_;
 8748:     return unless ($env{'request.course.id'});
 8749:     return unless ($priv eq 'bre');
 8750:     return if ($env{'request.state'} eq 'construct');
 8751:     return if ($env{'request.role.adv'});
 8752:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 8753:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 8754:     my (%possibles,@symbs);
 8755:     if (!$symb) {
 8756:         $symb = &symbread($uri,1,1,1,\%possibles);
 8757:     }
 8758:     if ($symb) {
 8759:         @symbs = ($symb);
 8760:     } elsif (keys(%possibles)) {
 8761:         @symbs = keys(%possibles);
 8762:     }
 8763: 
 8764:     my ($login,$switchrole,$allow);
 8765:     if ($env{'request.deeplink.login'} =~ m{^\Q/tiny/$cdom/\E(\w+)$}) {
 8766:         my $key = $1;
 8767:         my $tinyurl;
 8768:         my ($result,$cached)=&Apache::lonnet::is_cached_new('tiny',$cdom."\0".$key);
 8769:         if (defined($cached)) {
 8770:              $tinyurl = $result;
 8771:         } else {
 8772:              my $configuname = &Apache::lonnet::get_domainconfiguser($cdom);
 8773:              my %currtiny = &Apache::lonnet::get('tiny',[$key],$cdom,$configuname);
 8774:              if ($currtiny{$key} ne '') {
 8775:                  $tinyurl = $currtiny{$key};
 8776:                  &Apache::lonnet::do_cache_new('tiny',$cdom."\0".$key,$currtiny{$key},600);
 8777:              }
 8778:         }
 8779:         if ($tinyurl ne '') {
 8780:             my ($cnumreq,$posslogin) = split(/\&/,$tinyurl);
 8781:             if ($cnumreq eq $cnum) {
 8782:                 $login = $posslogin;
 8783:             } else {
 8784:                 $switchrole = 1;
 8785:             }
 8786:         }
 8787:     }
 8788:     foreach my $symb (@symbs) {
 8789:         last if ($allow);
 8790:         my $deeplink = &EXT("resource.0.deeplink",$symb);
 8791:         if ($deeplink eq '') {
 8792:             $allow = 1;
 8793:         } else {
 8794:             my ($listed,$scope,$access) = split(/,/,$deeplink);
 8795:             if ($access eq 'any') {
 8796:                 $allow = 1;
 8797:             } elsif ($login) {
 8798:                 if ($access eq 'only') {
 8799:                     if ($scope eq 'res') {
 8800:                         if ($symb eq $login) {
 8801:                             $allow = 1;
 8802:                         }
 8803:                     } elsif ($scope eq 'map') {
 8804: #FIXME Compare map for $env{'request.deeplink.login'} with map for $symb
 8805:                     } elsif ($scope eq 'rec') {
 8806: #FIXME Recurse up for $env{'request.deeplink.login'} with map for $symb
 8807:                     }
 8808:                 } else {
 8809:                     my ($acctype,$item) = split(/:/,$access);
 8810:                     if (($acctype eq 'lti') && ($env{'user.linkprotector'})) {
 8811:                         if (grep(/^\Q$item\E$/,split(/,/,$env{'user.linkprotector'}))) {
 8812:                             my %tinyurls = &get('tiny',[$symb],$cdom,$cnum);
 8813:                             if (grep(/\Q$tinyurls{$symb}\E$/,split(/,/,$env{'user.linkproturis'}))) {
 8814:                                 $allow = 1;
 8815:                             }
 8816:                         }
 8817:                     } elsif (($acctype eq 'key') && ($env{'user.deeplinkkey'})) {
 8818:                         if (grep(/^\Q$item\E$/,split(/,/,$env{'user.deeplinkkey'}))) {
 8819:                             my %tinyurls = &get('tiny',[$symb],$cdom,$cnum);
 8820:                             if (grep(/\Q$tinyurls{$symb}\E$/,split(/,/,$env{'user.keyedlinkuri'}))) {
 8821:                                 $allow = 1;
 8822:                             }
 8823:                         }
 8824:                     }
 8825:                 }
 8826:             }
 8827:         }
 8828:     }
 8829:     return if ($allow);
 8830:     return 1;
 8831: }
 8832: 
 8833: # -------------------------------- Deversion and split uri into path an filename   
 8834: 
 8835: #
 8836: #   Removes the version from a URI and
 8837: #   splits it in to its filename and path to the filename.
 8838: #   Seems like File::Basename could have done this more clearly.
 8839: #   Parameters:
 8840: #      $uri   - input URI
 8841: #   Returns:
 8842: #     Two element list consisting of 
 8843: #     $pathname  - the URI up to and excluding the trailing /
 8844: #     $filename  - The part of the URI following the last /
 8845: #  NOTE:
 8846: #    Another realization of this is simply:
 8847: #    use File::Basename;
 8848: #    ...
 8849: #    $uri = shift;
 8850: #    $filename = basename($uri);
 8851: #    $path     = dirname($uri);
 8852: #    return ($filename, $path);
 8853: #
 8854: #     The implementation below is probably faster however.
 8855: #
 8856: sub split_uri_for_cond {
 8857:     my $uri=&deversion(&declutter(shift));
 8858:     my @uriparts=split(/\//,$uri);
 8859:     my $filename=pop(@uriparts);
 8860:     my $pathname=join('/',@uriparts);
 8861:     return ($pathname,$filename);
 8862: }
 8863: # --------------------------------------------------- Is a resource on the map?
 8864: 
 8865: sub is_on_map {
 8866:     my ($pathname,$filename) = &split_uri_for_cond(shift);
 8867:     #Trying to find the conditional for the file
 8868:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
 8869: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
 8870:     if ($match) {
 8871: 	return (1,$1);
 8872:     } else {
 8873: 	return (0,0);
 8874:     }
 8875: }
 8876: 
 8877: # --------------------------------------------------------- Get symb from alias
 8878: 
 8879: sub get_symb_from_alias {
 8880:     my $symb=shift;
 8881:     my ($map,$resid,$url)=&decode_symb($symb);
 8882: # Already is a symb
 8883:     if ($url) { return $symb; }
 8884: # Must be an alias
 8885:     my $aliassymb='';
 8886:     my %bighash;
 8887:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 8888:                             &GDBM_READER(),0640)) {
 8889:         my $rid=$bighash{'mapalias_'.$symb};
 8890: 	if ($rid) {
 8891: 	    my ($mapid,$resid)=split(/\./,$rid);
 8892: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
 8893: 				    $resid,$bighash{'src_'.$rid});
 8894: 	}
 8895:         untie %bighash;
 8896:     }
 8897:     return $aliassymb;
 8898: }
 8899: 
 8900: # ----------------------------------------------------------------- Define Role
 8901: 
 8902: sub definerole {
 8903:   if (allowed('mcr','/')) {
 8904:     my ($rolename,$sysrole,$domrole,$courole,$uname,$udom)=@_;
 8905:     foreach my $role (split(':',$sysrole)) {
 8906: 	my ($crole,$cqual)=split(/\&/,$role);
 8907:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
 8908:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
 8909: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 8910:                return "refused:s:$crole&$cqual"; 
 8911:             }
 8912:         }
 8913:     }
 8914:     foreach my $role (split(':',$domrole)) {
 8915: 	my ($crole,$cqual)=split(/\&/,$role);
 8916:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
 8917:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
 8918: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
 8919:                return "refused:d:$crole&$cqual"; 
 8920:             }
 8921:         }
 8922:     }
 8923:     foreach my $role (split(':',$courole)) {
 8924: 	my ($crole,$cqual)=split(/\&/,$role);
 8925:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
 8926:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
 8927: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 8928:                return "refused:c:$crole&$cqual"; 
 8929:             }
 8930:         }
 8931:     }
 8932:     my $uhome;
 8933:     if (($uname ne '') && ($udom ne '')) {
 8934:         $uhome = &homeserver($uname,$udom);
 8935:         return $uhome if ($uhome eq 'no_host');
 8936:     } else {
 8937:         $uname = $env{'user.name'};
 8938:         $udom = $env{'user.domain'};
 8939:         $uhome = $env{'user.home'};
 8940:     }
 8941:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
 8942:                 "$udom:$uname:rolesdef_$rolename=".
 8943:                 escape($sysrole.'_'.$domrole.'_'.$courole);
 8944:     return reply($command,$uhome);
 8945:   } else {
 8946:     return 'refused';
 8947:   }
 8948: }
 8949: 
 8950: # ---------------- Make a metadata query against the network of library servers
 8951: 
 8952: sub metadata_query {
 8953:     my ($query,$custom,$customshow,$server_array,$domains_hash)=@_;
 8954:     my %rhash;
 8955:     my %libserv = &all_library();
 8956:     my @server_list = (defined($server_array) ? @$server_array
 8957:                                               : keys(%libserv) );
 8958:     for my $server (@server_list) {
 8959:         my $domains = ''; 
 8960:         if (ref($domains_hash) eq 'HASH') {
 8961:             $domains = $domains_hash->{$server}; 
 8962:         }
 8963: 	unless ($custom or $customshow) {
 8964: 	    my $reply=&reply("querysend:".&escape($query).':::'.&escape($domains),$server);
 8965: 	    $rhash{$server}=$reply;
 8966: 	}
 8967: 	else {
 8968: 	    my $reply=&reply("querysend:".&escape($query).':'.
 8969: 			     &escape($custom).':'.&escape($customshow).':'.&escape($domains),
 8970: 			     $server);
 8971: 	    $rhash{$server}=$reply;
 8972: 	}
 8973:     }
 8974:     return \%rhash;
 8975: }
 8976: 
 8977: # ----------------------------------------- Send log queries and wait for reply
 8978: 
 8979: sub log_query {
 8980:     my ($uname,$udom,$query,%filters)=@_;
 8981:     my $uhome=&homeserver($uname,$udom);
 8982:     if ($uhome eq 'no_host') { return 'error: no_host'; }
 8983:     my $uhost=&hostname($uhome);
 8984:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
 8985:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
 8986:                        $uhome);
 8987:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
 8988:     return get_query_reply($queryid);
 8989: }
 8990: 
 8991: # -------------------------- Update MySQL table for portfolio file
 8992: 
 8993: sub update_portfolio_table {
 8994:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
 8995:     if ($group ne '') {
 8996:         $file_name =~s /^\Q$group\E//;
 8997:     }
 8998:     my $homeserver = &homeserver($uname,$udom);
 8999:     my $queryid=
 9000:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
 9001:                ':'.&escape($file_name).':'.$action,$homeserver);
 9002:     my $reply = &get_query_reply($queryid);
 9003:     return $reply;
 9004: }
 9005: 
 9006: # -------------------------- Update MySQL allusers table
 9007: 
 9008: sub update_allusers_table {
 9009:     my ($uname,$udom,$names) = @_;
 9010:     my $homeserver = &homeserver($uname,$udom);
 9011:     my $queryid=
 9012:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
 9013:                'lastname='.&escape($names->{'lastname'}).'%%'.
 9014:                'firstname='.&escape($names->{'firstname'}).'%%'.
 9015:                'middlename='.&escape($names->{'middlename'}).'%%'.
 9016:                'generation='.&escape($names->{'generation'}).'%%'.
 9017:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
 9018:                'id='.&escape($names->{'id'}),$homeserver);
 9019:     return;
 9020: }
 9021: 
 9022: # ------- Request retrieval of institutional classlists for course(s)
 9023: 
 9024: sub fetch_enrollment_query {
 9025:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
 9026:     my ($homeserver,$sleep,$loopmax);
 9027:     my $maxtries = 1;
 9028:     if ($context eq 'automated') {
 9029:         $homeserver = $perlvar{'lonHostID'};
 9030:         $sleep = 2;
 9031:         $loopmax = 100;
 9032:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
 9033:     } else {
 9034:         $homeserver = &homeserver($cnum,$dom);
 9035:     }
 9036:     my $host=&hostname($homeserver);
 9037:     my $cmd = '';
 9038:     foreach my $affiliate (keys(%{$affiliatesref})) {
 9039:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
 9040:     }
 9041:     $cmd =~ s/%%$//;
 9042:     $cmd = &escape($cmd);
 9043:     my $query = 'fetchenrollment';
 9044:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
 9045:     unless ($queryid=~/^\Q$host\E\_/) { 
 9046:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
 9047:         return 'error: '.$queryid;
 9048:     }
 9049:     my $reply = &get_query_reply($queryid,$sleep,$loopmax);
 9050:     my $tries = 1;
 9051:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 9052:         $reply = &get_query_reply($queryid,$sleep,$loopmax);
 9053:         $tries ++;
 9054:     }
 9055:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 9056:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 9057:     } else {
 9058:         my @responses = split(/:/,$reply);
 9059:         if (grep { $_ eq $homeserver } &current_machine_ids()) {
 9060:             foreach my $line (@responses) {
 9061:                 my ($key,$value) = split(/=/,$line,2);
 9062:                 $$replyref{$key} = $value;
 9063:             }
 9064:         } else {
 9065:             my $pathname = LONCAPA::tempdir();
 9066:             foreach my $line (@responses) {
 9067:                 my ($key,$value) = split(/=/,$line);
 9068:                 $$replyref{$key} = $value;
 9069:                 if ($value > 0) {
 9070:                     foreach my $item (@{$$affiliatesref{$key}}) {
 9071:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
 9072:                         my $destname = $pathname.'/'.$filename;
 9073:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
 9074:                         if ($xml_classlist =~ /^error/) {
 9075:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
 9076:                         } else {
 9077:                             if ( open(FILE,">",$destname) ) {
 9078:                                 print FILE &unescape($xml_classlist);
 9079:                                 close(FILE);
 9080:                             } else {
 9081:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
 9082:                             }
 9083:                         }
 9084:                     }
 9085:                 }
 9086:             }
 9087:         }
 9088:         return 'ok';
 9089:     }
 9090:     return 'error';
 9091: }
 9092: 
 9093: sub get_query_reply {
 9094:     my ($queryid,$sleep,$loopmax) = @_;;
 9095:     if (($sleep eq '') || ($sleep !~ /^\d+\.?\d*$/)) {
 9096:         $sleep = 0.2;
 9097:     }
 9098:     if (($loopmax eq '') || ($loopmax =~ /\D/)) {
 9099:         $loopmax = 100;
 9100:     }
 9101:     my $replyfile=LONCAPA::tempdir().$queryid;
 9102:     my $reply='';
 9103:     for (1..$loopmax) {
 9104: 	sleep($sleep);
 9105:         if (-e $replyfile.'.end') {
 9106: 	    if (open(my $fh,"<",$replyfile)) {
 9107: 		$reply = join('',<$fh>);
 9108: 		close($fh);
 9109: 	   } else { return 'error: reply_file_error'; }
 9110:            return &unescape($reply);
 9111: 	}
 9112:     }
 9113:     return 'timeout:'.$queryid;
 9114: }
 9115: 
 9116: sub courselog_query {
 9117: #
 9118: # possible filters:
 9119: # url: url or symb
 9120: # username
 9121: # domain
 9122: # action: view, submit, grade
 9123: # start: timestamp
 9124: # end: timestamp
 9125: #
 9126:     my (%filters)=@_;
 9127:     unless ($env{'request.course.id'}) { return 'no_course'; }
 9128:     if ($filters{'url'}) {
 9129: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
 9130:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
 9131:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
 9132:     }
 9133:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 9134:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 9135:     return &log_query($cname,$cdom,'courselog',%filters);
 9136: }
 9137: 
 9138: sub userlog_query {
 9139: #
 9140: # possible filters:
 9141: # action: log check role
 9142: # start: timestamp
 9143: # end: timestamp
 9144: #
 9145:     my ($uname,$udom,%filters)=@_;
 9146:     return &log_query($uname,$udom,'userlog',%filters);
 9147: }
 9148: 
 9149: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
 9150: 
 9151: sub auto_run {
 9152:     my ($cnum,$cdom) = @_;
 9153:     my $response = 0;
 9154:     my $settings;
 9155:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
 9156:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
 9157:         $settings = $domconfig{'autoenroll'};
 9158:         if ($settings->{'run'} eq '1') {
 9159:             $response = 1;
 9160:         }
 9161:     } else {
 9162:         my $homeserver;
 9163:         if (&is_course($cdom,$cnum)) {
 9164:             $homeserver = &homeserver($cnum,$cdom);
 9165:         } else {
 9166:             $homeserver = &domain($cdom,'primary');
 9167:         }
 9168:         if ($homeserver ne 'no_host') {
 9169:             $response = &reply('autorun:'.$cdom,$homeserver);
 9170:         }
 9171:     }
 9172:     return $response;
 9173: }
 9174: 
 9175: sub auto_get_sections {
 9176:     my ($cnum,$cdom,$inst_coursecode) = @_;
 9177:     my $homeserver;
 9178:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) { 
 9179:         $homeserver = &homeserver($cnum,$cdom);
 9180:     }
 9181:     if (!defined($homeserver)) { 
 9182:         if ($cdom =~ /^$match_domain$/) {
 9183:             $homeserver = &domain($cdom,'primary');
 9184:         }
 9185:     }
 9186:     my @secs;
 9187:     if (defined($homeserver)) {
 9188:         my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
 9189:         unless ($response eq 'refused') {
 9190:             @secs = split(/:/,$response);
 9191:         }
 9192:     }
 9193:     return @secs;
 9194: }
 9195: 
 9196: sub auto_new_course {
 9197:     my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
 9198:     my $homeserver = &homeserver($cnum,$cdom);
 9199:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
 9200:     return $response;
 9201: }
 9202: 
 9203: sub auto_validate_courseID {
 9204:     my ($cnum,$cdom,$inst_course_id) = @_;
 9205:     my $homeserver = &homeserver($cnum,$cdom);
 9206:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
 9207:     return $response;
 9208: }
 9209: 
 9210: sub auto_validate_instcode {
 9211:     my ($cnum,$cdom,$instcode,$owner) = @_;
 9212:     my ($homeserver,$response);
 9213:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
 9214:         $homeserver = &homeserver($cnum,$cdom);
 9215:     }
 9216:     if (!defined($homeserver)) {
 9217:         if ($cdom =~ /^$match_domain$/) {
 9218:             $homeserver = &domain($cdom,'primary');
 9219:         }
 9220:     }
 9221:     $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
 9222:                         &escape($instcode).':'.&escape($owner),$homeserver));
 9223:     my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
 9224:     return ($outcome,$description,$defaultcredits);
 9225: }
 9226: 
 9227: sub auto_create_password {
 9228:     my ($cnum,$cdom,$authparam,$udom) = @_;
 9229:     my ($homeserver,$response);
 9230:     my $create_passwd = 0;
 9231:     my $authchk = '';
 9232:     if ($udom =~ /^$match_domain$/) {
 9233:         $homeserver = &domain($udom,'primary');
 9234:     }
 9235:     if ($homeserver eq '') {
 9236:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
 9237:             $homeserver = &homeserver($cnum,$cdom);
 9238:         }
 9239:     }
 9240:     if ($homeserver eq '') {
 9241:         $authchk = 'nodomain';
 9242:     } else {
 9243:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
 9244:         if ($response eq 'refused') {
 9245:             $authchk = 'refused';
 9246:         } else {
 9247:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
 9248:         }
 9249:     }
 9250:     return ($authparam,$create_passwd,$authchk);
 9251: }
 9252: 
 9253: sub auto_photo_permission {
 9254:     my ($cnum,$cdom,$students) = @_;
 9255:     my $homeserver = &homeserver($cnum,$cdom);
 9256:     my ($outcome,$perm_reqd,$conditions) = 
 9257: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
 9258:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 9259: 	return (undef,undef);
 9260:     }
 9261:     return ($outcome,$perm_reqd,$conditions);
 9262: }
 9263: 
 9264: sub auto_checkphotos {
 9265:     my ($uname,$udom,$pid) = @_;
 9266:     my $homeserver = &homeserver($uname,$udom);
 9267:     my ($result,$resulttype);
 9268:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
 9269: 				   &escape($uname).':'.&escape($pid),
 9270: 				   $homeserver));
 9271:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 9272: 	return (undef,undef);
 9273:     }
 9274:     if ($outcome) {
 9275:         ($result,$resulttype) = split(/:/,$outcome);
 9276:     } 
 9277:     return ($result,$resulttype);
 9278: }
 9279: 
 9280: sub auto_photochoice {
 9281:     my ($cnum,$cdom) = @_;
 9282:     my $homeserver = &homeserver($cnum,$cdom);
 9283:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
 9284: 						       &escape($cdom),
 9285: 						       $homeserver)));
 9286:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 9287: 	return (undef,undef);
 9288:     }
 9289:     return ($update,$comment);
 9290: }
 9291: 
 9292: sub auto_photoupdate {
 9293:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
 9294:     my $homeserver = &homeserver($cnum,$dom);
 9295:     my $host=&hostname($homeserver);
 9296:     my $cmd = '';
 9297:     my $maxtries = 1;
 9298:     foreach my $affiliate (keys(%{$affiliatesref})) {
 9299:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
 9300:     }
 9301:     $cmd =~ s/%%$//;
 9302:     $cmd = &escape($cmd);
 9303:     my $query = 'institutionalphotos';
 9304:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
 9305:     unless ($queryid=~/^\Q$host\E\_/) {
 9306:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
 9307:         return 'error: '.$queryid;
 9308:     }
 9309:     my $reply = &get_query_reply($queryid);
 9310:     my $tries = 1;
 9311:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 9312:         $reply = &get_query_reply($queryid);
 9313:         $tries ++;
 9314:     }
 9315:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 9316:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 9317:     } else {
 9318:         my @responses = split(/:/,$reply);
 9319:         my $outcome = shift(@responses); 
 9320:         foreach my $item (@responses) {
 9321:             my ($key,$value) = split(/=/,$item);
 9322:             $$photo{$key} = $value;
 9323:         }
 9324:         return $outcome;
 9325:     }
 9326:     return 'error';
 9327: }
 9328: 
 9329: sub auto_instcode_format {
 9330:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
 9331: 	$cat_order) = @_;
 9332:     my $courses = '';
 9333:     my @homeservers;
 9334:     if ($caller eq 'global') {
 9335: 	my %servers = &get_servers($codedom,'library');
 9336: 	foreach my $tryserver (keys(%servers)) {
 9337: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 9338: 		push(@homeservers,$tryserver);
 9339: 	    }
 9340:         }
 9341:     } elsif ($caller eq 'requests') {
 9342:         if ($codedom =~ /^$match_domain$/) {
 9343:             my $chome = &domain($codedom,'primary');
 9344:             unless ($chome eq 'no_host') {
 9345:                 push(@homeservers,$chome);
 9346:             }
 9347:         }
 9348:     } else {
 9349:         push(@homeservers,&homeserver($caller,$codedom));
 9350:     }
 9351:     foreach my $code (keys(%{$instcodes})) {
 9352:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
 9353:     }
 9354:     chop($courses);
 9355:     my $ok_response = 0;
 9356:     my $response;
 9357:     while (@homeservers > 0 && $ok_response == 0) {
 9358:         my $server = shift(@homeservers); 
 9359:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
 9360:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
 9361:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
 9362: 		split(/:/,$response);
 9363:             %{$codes} = (%{$codes},&str2hash($codes_str));
 9364:             push(@{$codetitles},&str2array($codetitles_str));
 9365:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
 9366:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
 9367:             $ok_response = 1;
 9368:         }
 9369:     }
 9370:     if ($ok_response) {
 9371:         return 'ok';
 9372:     } else {
 9373:         return $response;
 9374:     }
 9375: }
 9376: 
 9377: sub auto_instcode_defaults {
 9378:     my ($domain,$returnhash,$code_order) = @_;
 9379:     my @homeservers;
 9380: 
 9381:     my %servers = &get_servers($domain,'library');
 9382:     foreach my $tryserver (keys(%servers)) {
 9383: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 9384: 	    push(@homeservers,$tryserver);
 9385: 	}
 9386:     }
 9387: 
 9388:     my $response;
 9389:     foreach my $server (@homeservers) {
 9390:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
 9391:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
 9392: 	
 9393: 	foreach my $pair (split(/\&/,$response)) {
 9394: 	    my ($name,$value)=split(/\=/,$pair);
 9395: 	    if ($name eq 'code_order') {
 9396: 		@{$code_order} = split(/\&/,&unescape($value));
 9397: 	    } else {
 9398: 		$returnhash->{&unescape($name)}=&unescape($value);
 9399: 	    }
 9400: 	}
 9401: 	return 'ok';
 9402:     }
 9403: 
 9404:     return $response;
 9405: }
 9406: 
 9407: sub auto_possible_instcodes {
 9408:     my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
 9409:     unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') && 
 9410:             (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
 9411:         return;
 9412:     }
 9413:     my (@homeservers,$uhome);
 9414:     if (defined(&domain($domain,'primary'))) {
 9415:         $uhome=&domain($domain,'primary');
 9416:         push(@homeservers,&domain($domain,'primary'));
 9417:     } else {
 9418:         my %servers = &get_servers($domain,'library');
 9419:         foreach my $tryserver (keys(%servers)) {
 9420:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 9421:                 push(@homeservers,$tryserver);
 9422:             }
 9423:         }
 9424:     }
 9425:     my $response;
 9426:     foreach my $server (@homeservers) {
 9427:         $response=&reply('autopossibleinstcodes:'.$domain,$server);
 9428:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
 9429:         my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) = 
 9430:             split(':',$response);
 9431:         @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
 9432:         @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
 9433:         foreach my $item (split('&',$cat_title)) {   
 9434:             my ($name,$value)=split('=',$item);
 9435:             $cat_titles->{&unescape($name)}=&thaw_unescape($value);
 9436:         }
 9437:         foreach my $item (split('&',$cat_order)) {
 9438:             my ($name,$value)=split('=',$item);
 9439:             $cat_orders->{&unescape($name)}=&thaw_unescape($value);
 9440:         }
 9441:         return 'ok';
 9442:     }
 9443:     return $response;
 9444: }
 9445: 
 9446: sub auto_courserequest_checks {
 9447:     my ($dom) = @_;
 9448:     my ($homeserver,%validations);
 9449:     if ($dom =~ /^$match_domain$/) {
 9450:         $homeserver = &domain($dom,'primary');
 9451:     }
 9452:     unless ($homeserver eq 'no_host') {
 9453:         my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
 9454:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
 9455:             my @items = split(/&/,$response);
 9456:             foreach my $item (@items) {
 9457:                 my ($key,$value) = split('=',$item);
 9458:                 $validations{&unescape($key)} = &thaw_unescape($value);
 9459:             }
 9460:         }
 9461:     }
 9462:     return %validations; 
 9463: }
 9464: 
 9465: sub auto_courserequest_validation {
 9466:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist,$custominfo) = @_;
 9467:     my ($homeserver,$response);
 9468:     if ($dom =~ /^$match_domain$/) {
 9469:         $homeserver = &domain($dom,'primary');
 9470:     }
 9471:     unless ($homeserver eq 'no_host') {
 9472:         my $customdata;
 9473:         if (ref($custominfo) eq 'HASH') {
 9474:             $customdata = &freeze_escape($custominfo);
 9475:         }
 9476:         $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
 9477:                                     ':'.&escape($crstype).':'.&escape($inststatuslist).
 9478:                                     ':'.&escape($instcode).':'.&escape($instseclist).':'.
 9479:                                     $customdata,$homeserver));
 9480:     }
 9481:     return $response;
 9482: }
 9483: 
 9484: sub auto_validate_class_sec {
 9485:     my ($cdom,$cnum,$owners,$inst_class) = @_;
 9486:     my $homeserver = &homeserver($cnum,$cdom);
 9487:     my $ownerlist;
 9488:     if (ref($owners) eq 'ARRAY') {
 9489:         $ownerlist = join(',',@{$owners});
 9490:     } else {
 9491:         $ownerlist = $owners;
 9492:     }
 9493:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
 9494:                         &escape($ownerlist).':'.$cdom,$homeserver);
 9495:     return $response;
 9496: }
 9497: 
 9498: sub auto_validate_instclasses {
 9499:     my ($cdom,$cnum,$owners,$classesref) = @_;
 9500:     my ($homeserver,%validations);
 9501:     $homeserver = &homeserver($cnum,$cdom);
 9502:     unless ($homeserver eq 'no_host') {
 9503:         my $ownerlist;
 9504:         if (ref($owners) eq 'ARRAY') {
 9505:             $ownerlist = join(',',@{$owners});
 9506:         } else {
 9507:             $ownerlist = $owners;
 9508:         }
 9509:         if (ref($classesref) eq 'HASH') {
 9510:             my $classes = &freeze_escape($classesref);
 9511:             my $response=&reply('autovalidateinstclasses:'.&escape($ownerlist).
 9512:                                 ':'.$cdom.':'.$classes,$homeserver);
 9513:             unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
 9514:                 my @items = split(/&/,$response);
 9515:                 foreach my $item (@items) {
 9516:                     my ($key,$value) = split('=',$item);
 9517:                     $validations{&unescape($key)} = &thaw_unescape($value);
 9518:                 }
 9519:             }
 9520:         }
 9521:     }
 9522:     return %validations;
 9523: }
 9524: 
 9525: sub auto_crsreq_update {
 9526:     my ($cdom,$cnum,$crstype,$action,$ownername,$ownerdomain,$fullname,$title,
 9527:         $code,$accessstart,$accessend,$inbound) = @_;
 9528:     my ($homeserver,%crsreqresponse);
 9529:     if ($cdom =~ /^$match_domain$/) {
 9530:         $homeserver = &domain($cdom,'primary');
 9531:     }
 9532:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
 9533:         my $info;
 9534:         if (ref($inbound) eq 'HASH') {
 9535:             $info = &freeze_escape($inbound);
 9536:         }
 9537:         my $response=&reply('autocrsrequpdate:'.$cdom.':'.$cnum.':'.&escape($crstype).
 9538:                             ':'.&escape($action).':'.&escape($ownername).':'.
 9539:                             &escape($ownerdomain).':'.&escape($fullname).':'.
 9540:                             &escape($title).':'.&escape($code).':'.
 9541:                             &escape($accessstart).':'.&escape($accessend).':'.$info,
 9542:                             $homeserver);
 9543:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
 9544:             my @items = split(/&/,$response);
 9545:             foreach my $item (@items) {
 9546:                 my ($key,$value) = split('=',$item);
 9547:                 $crsreqresponse{&unescape($key)} = &thaw_unescape($value);
 9548:             }
 9549:         }
 9550:     }
 9551:     return \%crsreqresponse;
 9552: }
 9553: 
 9554: sub auto_export_grades {
 9555:     my ($cdom,$cnum,$inforef,$gradesref) = @_;
 9556:     my ($homeserver,%exportresponse);
 9557:     if ($cdom =~ /^$match_domain$/) {
 9558:         $homeserver = &domain($cdom,'primary');
 9559:     }
 9560:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
 9561:         my $info;
 9562:         if (ref($inforef) eq 'HASH') {
 9563:             $info = &freeze_escape($inforef);
 9564:         }
 9565:         if (ref($gradesref) eq 'HASH') {
 9566:             my $grades = &freeze_escape($gradesref);
 9567:             my $response=&reply('encrypt:autoexportgrades:'.$cdom.':'.$cnum.':'.
 9568:                                 $info.':'.$grades,$homeserver);
 9569:             unless ($response =~ /(con_lost|error|no_such_host|refused|unknown_command)/) {
 9570:                 my @items = split(/&/,$response);
 9571:                 foreach my $item (@items) {
 9572:                     my ($key,$value) = split('=',$item);
 9573:                     $exportresponse{&unescape($key)} = &thaw_unescape($value);
 9574:                 }
 9575:             }
 9576:         }
 9577:     }
 9578:     return \%exportresponse;
 9579: }
 9580: 
 9581: sub check_instcode_cloning {
 9582:     my ($codedefaults,$code_order,$cloner,$clonefromcode,$clonetocode) = @_;
 9583:     unless ((ref($codedefaults) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
 9584:         return;
 9585:     }
 9586:     my $canclone;
 9587:     if (@{$code_order} > 0) {
 9588:         my $instcoderegexp ='^';
 9589:         my @clonecodes = split(/\&/,$cloner);
 9590:         foreach my $item (@{$code_order}) {
 9591:             if (grep(/^\Q$item\E=/,@clonecodes)) {
 9592:                 foreach my $pair (@clonecodes) {
 9593:                     my ($key,$val) = split(/\=/,$pair,2);
 9594:                     $val = &unescape($val);
 9595:                     if ($key eq $item) {
 9596:                         $instcoderegexp .= '('.$val.')';
 9597:                         last;
 9598:                     }
 9599:                 }
 9600:             } else {
 9601:                 $instcoderegexp .= $codedefaults->{$item};
 9602:             }
 9603:         }
 9604:         $instcoderegexp .= '$';
 9605:         my (@from,@to);
 9606:         eval {
 9607:                (@from) = ($clonefromcode =~ /$instcoderegexp/);
 9608:                (@to) = ($clonetocode =~ /$instcoderegexp/);
 9609:         };
 9610:         if ((@from > 0) && (@to > 0)) {
 9611:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
 9612:             if (!@diffs) {
 9613:                 $canclone = 1;
 9614:             }
 9615:         }
 9616:     }
 9617:     return $canclone;
 9618: }
 9619: 
 9620: sub default_instcode_cloning {
 9621:     my ($clonedom,$domdefclone,$clonefromcode,$clonetocode,$codedefaultsref,$codeorderref) = @_;
 9622:     my (%codedefaults,@code_order,$canclone);
 9623:     if ((ref($codedefaultsref) eq 'HASH') && (ref($codeorderref) eq 'ARRAY')) {
 9624:         %codedefaults = %{$codedefaultsref};
 9625:         @code_order = @{$codeorderref};
 9626:     } elsif ($clonedom) {
 9627:         &auto_instcode_defaults($clonedom,\%codedefaults,\@code_order);
 9628:     }
 9629:     if (($domdefclone) && (@code_order)) {
 9630:         my @clonecodes = split(/\+/,$domdefclone);
 9631:         my $instcoderegexp ='^';
 9632:         foreach my $item (@code_order) {
 9633:             if (grep(/^\Q$item\E$/,@clonecodes)) {
 9634:                 $instcoderegexp .= '('.$codedefaults{$item}.')';
 9635:             } else {
 9636:                 $instcoderegexp .= $codedefaults{$item};
 9637:             }
 9638:         }
 9639:         $instcoderegexp .= '$';
 9640:         my (@from,@to);
 9641:         eval {
 9642:             (@from) = ($clonefromcode =~ /$instcoderegexp/);
 9643:             (@to) = ($clonetocode =~ /$instcoderegexp/);
 9644:         };
 9645:         if ((@from > 0) && (@to > 0)) {
 9646:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
 9647:             if (!@diffs) {
 9648:                 $canclone = 1;
 9649:             }
 9650:         }
 9651:     }
 9652:     return $canclone;
 9653: }
 9654: 
 9655: # ------------------------------------------------------- Course Group routines
 9656: 
 9657: sub get_coursegroups {
 9658:     my ($cdom,$cnum,$group,$namespace) = @_;
 9659:     return(&dump($namespace,$cdom,$cnum,$group));
 9660: }
 9661: 
 9662: sub modify_coursegroup {
 9663:     my ($cdom,$cnum,$groupsettings) = @_;
 9664:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
 9665: }
 9666: 
 9667: sub toggle_coursegroup_status {
 9668:     my ($cdom,$cnum,$group,$action) = @_;
 9669:     my ($from_namespace,$to_namespace);
 9670:     if ($action eq 'delete') {
 9671:         $from_namespace = 'coursegroups';
 9672:         $to_namespace = 'deleted_groups';
 9673:     } else {
 9674:         $from_namespace = 'deleted_groups';
 9675:         $to_namespace = 'coursegroups';
 9676:     }
 9677:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
 9678:     if (my $tmp = &error(%curr_group)) {
 9679:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
 9680:         return ('read error',$tmp);
 9681:     } else {
 9682:         my %savedsettings = %curr_group; 
 9683:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
 9684:         my $deloutcome;
 9685:         if ($result eq 'ok') {
 9686:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
 9687:         } else {
 9688:             return ('write error',$result);
 9689:         }
 9690:         if ($deloutcome eq 'ok') {
 9691:             return 'ok';
 9692:         } else {
 9693:             return ('delete error',$deloutcome);
 9694:         }
 9695:     }
 9696: }
 9697: 
 9698: sub modify_group_roles {
 9699:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
 9700:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
 9701:     my $role = 'gr/'.&escape($userprivs);
 9702:     my ($uname,$udom) = split(/:/,$user);
 9703:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
 9704:     if ($result eq 'ok') {
 9705:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
 9706:     }
 9707:     return $result;
 9708: }
 9709: 
 9710: sub modify_coursegroup_membership {
 9711:     my ($cdom,$cnum,$membership) = @_;
 9712:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
 9713:     return $result;
 9714: }
 9715: 
 9716: sub get_active_groups {
 9717:     my ($udom,$uname,$cdom,$cnum) = @_;
 9718:     my $now = time;
 9719:     my %groups = ();
 9720:     foreach my $key (keys(%env)) {
 9721:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
 9722:             my ($start,$end) = split(/\./,$env{$key});
 9723:             if (($end!=0) && ($end<$now)) { next; }
 9724:             if (($start!=0) && ($start>$now)) { next; }
 9725:             if ($1 eq $cdom && $2 eq $cnum) {
 9726:                 $groups{$3} = $env{$key} ;
 9727:             }
 9728:         }
 9729:     }
 9730:     return %groups;
 9731: }
 9732: 
 9733: sub get_group_membership {
 9734:     my ($cdom,$cnum,$group) = @_;
 9735:     return(&dump('groupmembership',$cdom,$cnum,$group));
 9736: }
 9737: 
 9738: sub get_users_groups {
 9739:     my ($udom,$uname,$courseid) = @_;
 9740:     my @usersgroups;
 9741:     my $cachetime=1800;
 9742: 
 9743:     my $hashid="$udom:$uname:$courseid";
 9744:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
 9745:     if (defined($cached)) {
 9746:         @usersgroups = split(/:/,$grouplist);
 9747:     } else {  
 9748:         $grouplist = '';
 9749:         my $courseurl = &courseid_to_courseurl($courseid);
 9750:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
 9751:         my $access_end = $env{'course.'.$courseid.
 9752:                               '.default_enrollment_end_date'};
 9753:         my $now = time;
 9754:         foreach my $key (keys(%roleshash)) {
 9755:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
 9756:                 my $group = $1;
 9757:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
 9758:                     my $start = $2;
 9759:                     my $end = $1;
 9760:                     if ($start == -1) { next; } # deleted from group
 9761:                     if (($start!=0) && ($start>$now)) { next; }
 9762:                     if (($end!=0) && ($end<$now)) {
 9763:                         if ($access_end && $access_end < $now) {
 9764:                             if ($access_end - $end < 86400) {
 9765:                                 push(@usersgroups,$group);
 9766:                             }
 9767:                         }
 9768:                         next;
 9769:                     }
 9770:                     push(@usersgroups,$group);
 9771:                 }
 9772:             }
 9773:         }
 9774:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
 9775:         $grouplist = join(':',@usersgroups);
 9776:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
 9777:     }
 9778:     return @usersgroups;
 9779: }
 9780: 
 9781: sub devalidate_getgroups_cache {
 9782:     my ($udom,$uname,$cdom,$cnum)=@_;
 9783:     my $courseid = $cdom.'_'.$cnum;
 9784: 
 9785:     my $hashid="$udom:$uname:$courseid";
 9786:     &devalidate_cache_new('getgroups',$hashid);
 9787: }
 9788: 
 9789: # ------------------------------------------------------------------ Plain Text
 9790: 
 9791: sub plaintext {
 9792:     my ($short,$type,$cid,$forcedefault) = @_;
 9793:     if ($short =~ m{^cr/}) {
 9794: 	return (split('/',$short))[-1];
 9795:     }
 9796:     if (!defined($cid)) {
 9797:         $cid = $env{'request.course.id'};
 9798:     }
 9799:     my %rolenames = (
 9800:                       Course    => 'std',
 9801:                       Community => 'alt1',
 9802:                       Placement => 'std',
 9803:                     );
 9804:     if ($cid ne '') {
 9805:         if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
 9806:             unless ($forcedefault) {
 9807:                 my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
 9808:                 &Apache::lonlocal::mt_escape(\$roletext);
 9809:                 return &Apache::lonlocal::mt($roletext);
 9810:             }
 9811:         }
 9812:     }
 9813:     if ((defined($type)) && (defined($rolenames{$type})) &&
 9814:         (defined($rolenames{$type})) && 
 9815:         (defined($prp{$short}{$rolenames{$type}}))) {
 9816:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
 9817:     } elsif ($cid ne '') {
 9818:         my $crstype = $env{'course.'.$cid.'.type'};
 9819:         if (($crstype ne '') && (defined($rolenames{$crstype})) &&
 9820:             (defined($prp{$short}{$rolenames{$crstype}}))) {
 9821:             return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
 9822:         }
 9823:     }
 9824:     return &Apache::lonlocal::mt($prp{$short}{'std'});
 9825: }
 9826: 
 9827: # ----------------------------------------------------------------- Assign Role
 9828: 
 9829: sub assignrole {
 9830:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
 9831:         $context)=@_;
 9832:     my $mrole;
 9833:     if ($role =~ /^cr\//) {
 9834:         my $cwosec=$url;
 9835:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
 9836: 	unless (&allowed('ccr',$cwosec)) {
 9837:            my $refused = 1;
 9838:            if ($context eq 'requestcourses') {
 9839:                if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
 9840:                    if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
 9841:                        if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
 9842:                            my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
 9843:                            my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
 9844:                            if ($crsenv{'internal.courseowner'} eq
 9845:                                $env{'user.name'}.':'.$env{'user.domain'}) {
 9846:                                $refused = '';
 9847:                            }
 9848:                        }
 9849:                    }
 9850:                }
 9851:            }
 9852:            if ($refused) {
 9853:                &logthis('Refused custom assignrole: '.
 9854:                         $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
 9855:                         ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
 9856:                return 'refused';
 9857:            }
 9858:         }
 9859:         $mrole='cr';
 9860:     } elsif ($role =~ /^gr\//) {
 9861:         my $cwogrp=$url;
 9862:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
 9863:         unless (&allowed('mdg',$cwogrp)) {
 9864:             &logthis('Refused group assignrole: '.
 9865:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
 9866:                     $env{'user.name'}.' at '.$env{'user.domain'});
 9867:             return 'refused';
 9868:         }
 9869:         $mrole='gr';
 9870:     } else {
 9871:         my $cwosec=$url;
 9872:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
 9873:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
 9874:             my $refused;
 9875:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
 9876:                 if (!(&allowed('c'.$role,$url))) {
 9877:                     $refused = 1;
 9878:                 }
 9879:             } else {
 9880:                 $refused = 1;
 9881:             }
 9882:             if ($refused) {
 9883:                 my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
 9884:                 if (!$selfenroll && (($context eq 'course') || ($context eq 'ltienroll' && $env{'request.lti.login'}))) {
 9885:                     my %crsenv;
 9886:                     if ($role eq 'cc' || $role eq 'co') {
 9887:                         %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
 9888:                         if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
 9889:                             if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
 9890:                                 if ($crsenv{'internal.courseowner'} eq 
 9891:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
 9892:                                     $refused = '';
 9893:                                 }
 9894:                             }
 9895:                         } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) { 
 9896:                             if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
 9897:                                 if ($crsenv{'internal.courseowner'} eq 
 9898:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
 9899:                                     $refused = '';
 9900:                                 }
 9901:                             }
 9902:                         }
 9903:                     }
 9904:                 } elsif (($selfenroll == 1) && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 9905:                     if ($role eq 'st') {
 9906:                         $refused = '';
 9907:                     } elsif (($context eq 'ltienroll') && ($env{'request.lti.login'})) {
 9908:                         $refused = '';
 9909:                     }
 9910:                 } elsif ($context eq 'requestcourses') {
 9911:                     my @possroles = ('st','ta','ep','in','cc','co');
 9912:                     if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
 9913:                         my $wrongcc;
 9914:                         if ($cnum =~ /^$match_community$/) {
 9915:                             $wrongcc = 1 if ($role eq 'cc');
 9916:                         } else {
 9917:                             $wrongcc = 1 if ($role eq 'co');
 9918:                         }
 9919:                         unless ($wrongcc) {
 9920:                             my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
 9921:                             if ($crsenv{'internal.courseowner'} eq 
 9922:                                  $env{'user.name'}.':'.$env{'user.domain'}) {
 9923:                                 $refused = '';
 9924:                             }
 9925:                         }
 9926:                     }
 9927:                 } elsif ($context eq 'requestauthor') {
 9928:                     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) && 
 9929:                         ($url eq '/'.$udom.'/') && ($role eq 'au')) {
 9930:                         if ($env{'environment.requestauthor'} eq 'automatic') {
 9931:                             $refused = '';
 9932:                         } else {
 9933:                             my %domdefaults = &get_domain_defaults($udom);
 9934:                             if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
 9935:                                 my $checkbystatus;
 9936:                                 if ($env{'user.adv'}) { 
 9937:                                     my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
 9938:                                     if ($disposition eq 'automatic') {
 9939:                                         $refused = '';
 9940:                                     } elsif ($disposition eq '') {
 9941:                                         $checkbystatus = 1;
 9942:                                     } 
 9943:                                 } else {
 9944:                                     $checkbystatus = 1;
 9945:                                 }
 9946:                                 if ($checkbystatus) {
 9947:                                     if ($env{'environment.inststatus'}) {
 9948:                                         my @inststatuses = split(/,/,$env{'environment.inststatus'});
 9949:                                         foreach my $type (@inststatuses) {
 9950:                                             if (($type ne '') &&
 9951:                                                 ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
 9952:                                                 $refused = '';
 9953:                                             }
 9954:                                         }
 9955:                                     } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
 9956:                                         $refused = '';
 9957:                                     }
 9958:                                 }
 9959:                             }
 9960:                         }
 9961:                     }
 9962:                 }
 9963:                 if ($refused) {
 9964:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
 9965:                              ' '.$role.' '.$end.' '.$start.' by '.
 9966: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
 9967:                     return 'refused';
 9968:                 }
 9969:             }
 9970:         } elsif ($role eq 'au') {
 9971:             if ($url ne '/'.$udom.'/') {
 9972:                 &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
 9973:                          ' to assign author role for '.$uname.':'.$udom.
 9974:                          ' in domain: '.$url.' refused (wrong domain).');
 9975:                 return 'refused';
 9976:             }
 9977:         }
 9978:         $mrole=$role;
 9979:     }
 9980:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
 9981:                 "$udom:$uname:$url".'_'."$mrole=$role";
 9982:     if ($end) { $command.='_'.$end; }
 9983:     if ($start) {
 9984: 	if ($end) { 
 9985:            $command.='_'.$start; 
 9986:         } else {
 9987:            $command.='_0_'.$start;
 9988:         }
 9989:     }
 9990:     my $origstart = $start;
 9991:     my $origend = $end;
 9992:     my $delflag;
 9993: # actually delete
 9994:     if ($deleteflag) {
 9995: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
 9996: # modify command to delete the role
 9997:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
 9998:                 "$udom:$uname:$url".'_'."$mrole";
 9999: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
10000: # set start and finish to negative values for userrolelog
10001:            $start=-1;
10002:            $end=-1;
10003:            $delflag = 1;
10004:         }
10005:     }
10006: # send command
10007:     my $answer=&reply($command,&homeserver($uname,$udom));
10008: # log new user role if status is ok
10009:     if ($answer eq 'ok') {
10010: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
10011:         if (($role eq 'cc') || ($role eq 'in') ||
10012:             ($role eq 'ep') || ($role eq 'ad') ||
10013:             ($role eq 'ta') || ($role eq 'st') ||
10014:             ($role=~/^cr/) || ($role eq 'gr') ||
10015:             ($role eq 'co')) {
10016: # for course roles, perform group memberships changes triggered by role change.
10017:             unless ($role =~ /^gr/) {
10018:                 &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
10019:                                                  $origstart,$selfenroll,$context);
10020:             }
10021:             &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
10022:                            $selfenroll,$context);
10023:         } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
10024:                  ($role eq 'au') || ($role eq 'dc') || ($role eq 'dh') ||
10025:                  ($role eq 'da')) {
10026:             &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
10027:                            $context);
10028:         } elsif (($role eq 'ca') || ($role eq 'aa')) {
10029:             &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
10030:                              $context); 
10031:         }
10032:         if ($role eq 'cc') {
10033:             &autoupdate_coowners($url,$end,$start,$uname,$udom);
10034:         }
10035:     }
10036:     return $answer;
10037: }
10038: 
10039: sub autoupdate_coowners {
10040:     my ($url,$end,$start,$uname,$udom) = @_;
10041:     my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
10042:     if (($cdom ne '') && ($cnum ne '')) {
10043:         my $now = time;
10044:         my %domdesign = &Apache::loncommon::get_domainconf($cdom);
10045:         if ($domdesign{$cdom.'.autoassign.co-owners'}) {
10046:             my %coursehash = &coursedescription($cdom.'_'.$cnum);
10047:             my $instcode = $coursehash{'internal.coursecode'};
10048:             if ($instcode ne '') {
10049:                 if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
10050:                     unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
10051:                         my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
10052:                         my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
10053:                         if ($result eq 'valid') {
10054:                             if ($coursehash{'internal.co-owners'}) {
10055:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
10056:                                     push(@newcoowners,$coowner);
10057:                                 }
10058:                                 unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
10059:                                     push(@newcoowners,$uname.':'.$udom);
10060:                                 }
10061:                                 @newcoowners = sort(@newcoowners);
10062:                             } else {
10063:                                 push(@newcoowners,$uname.':'.$udom);
10064:                             }
10065:                         } else {
10066:                             if ($coursehash{'internal.co-owners'}) {
10067:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
10068:                                     unless ($coowner eq $uname.':'.$udom) {
10069:                                         push(@newcoowners,$coowner);
10070:                                     }
10071:                                 }
10072:                                 unless (@newcoowners > 0) {
10073:                                     $delcoowners = 1;
10074:                                     $coowners = '';
10075:                                 }
10076:                             }
10077:                         }
10078:                         if (@newcoowners || $delcoowners) {
10079:                             &store_coowners($cdom,$cnum,$coursehash{'home'},
10080:                                             $delcoowners,@newcoowners);
10081:                         }
10082:                     }
10083:                 }
10084:             }
10085:         }
10086:     }
10087: }
10088: 
10089: sub store_coowners {
10090:     my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
10091:     my $cid = $cdom.'_'.$cnum;
10092:     my ($coowners,$delresult,$putresult);
10093:     if (@newcoowners) {
10094:         $coowners = join(',',@newcoowners);
10095:         my %coownershash = (
10096:                             'internal.co-owners' => $coowners,
10097:                            );
10098:         $putresult = &put('environment',\%coownershash,$cdom,$cnum);
10099:         if ($putresult eq 'ok') {
10100:             if ($env{'course.'.$cid.'.num'} eq $cnum) {
10101:                 &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
10102:             }
10103:         }
10104:     }
10105:     if ($delcoowners) {
10106:         $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
10107:         if ($delresult eq 'ok') {
10108:             if ($env{'course.'.$cid.'.internal.co-owners'}) {
10109:                 &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
10110:             }
10111:         }
10112:     }
10113:     if (($putresult eq 'ok') || ($delresult eq 'ok')) {
10114:         my %crsinfo =
10115:             &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
10116:         if (ref($crsinfo{$cid}) eq 'HASH') {
10117:             $crsinfo{$cid}{'co-owners'} = \@newcoowners;
10118:             my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
10119:         }
10120:     }
10121: }
10122: 
10123: # -------------------------------------------------- Modify user authentication
10124: # Overrides without validation
10125: 
10126: sub modifyuserauth {
10127:     my ($udom,$uname,$umode,$upass)=@_;
10128:     my $uhome=&homeserver($uname,$udom);
10129:     my $allowed;
10130:     if (&allowed('mau',$udom)) {
10131:         $allowed = 1;
10132:     } elsif (($umode eq 'internal') && ($udom eq $env{'user.domain'}) &&
10133:              ($env{'request.course.id'}) && (&allowed('mip',$env{'request.course.id'})) &&
10134:              (!$env{'course.'.$env{'request.course.id'}.'.internal.nopasswdchg'})) {
10135:         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
10136:         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
10137:         if (($cdom ne '') && ($cnum ne '')) {
10138:             my $is_owner = &is_course_owner($cdom,$cnum);
10139:             if ($is_owner) {
10140:                 $allowed = 1;
10141:             }
10142:         }
10143:     }
10144:     unless ($allowed) { return 'refused'; }
10145:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
10146:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
10147:              ' in domain '.$env{'request.role.domain'});  
10148:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
10149: 		     &escape($upass),$uhome);
10150:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
10151:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
10152:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
10153:     &log($udom,,$uname,$uhome,
10154:         'Authentication changed by '.$env{'user.domain'}.', '.
10155:                                      $env{'user.name'}.', '.$umode.
10156:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
10157:     unless ($reply eq 'ok') {
10158:         &logthis('Authentication mode error: '.$reply);
10159: 	return 'error: '.$reply;
10160:     }   
10161:     return 'ok';
10162: }
10163: 
10164: # --------------------------------------------------------------- Modify a user
10165: 
10166: sub modifyuser {
10167:     my ($udom,    $uname, $uid,
10168:         $umode,   $upass, $first,
10169:         $middle,  $last,  $gene,
10170:         $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
10171:     $udom= &LONCAPA::clean_domain($udom);
10172:     $uname=&LONCAPA::clean_username($uname);
10173:     my $showcandelete = 'none';
10174:     if (ref($candelete) eq 'ARRAY') {
10175:         if (@{$candelete} > 0) {
10176:             $showcandelete = join(', ',@{$candelete});
10177:         }
10178:     }
10179:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
10180:              $umode.', '.$first.', '.$middle.', '.
10181: 	     $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
10182:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
10183:                                      ' desiredhome not specified'). 
10184:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
10185:              ' in domain '.$env{'request.role.domain'});
10186:     my $uhome=&homeserver($uname,$udom,'true');
10187:     my $newuser;
10188:     if ($uhome eq 'no_host') {
10189:         $newuser = 1;
10190:         unless (($umode && ($upass ne '')) || ($umode eq 'localauth') ||
10191:                 ($umode eq 'lti')) {
10192:             return 'error: more information needed to create new user';
10193:         }
10194:     }
10195: # ----------------------------------------------------------------- Create User
10196:     if (($uhome eq 'no_host') && 
10197: 	(($umode && $upass) || ($umode eq 'localauth') || ($umode eq 'lti'))) {
10198:         my $unhome='';
10199:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
10200:             $unhome = $desiredhome;
10201: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
10202: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
10203:         } else { # load balancing routine for determining $unhome
10204:             my $loadm=10000000;
10205: 	    my %servers = &get_servers($udom,'library');
10206: 	    foreach my $tryserver (keys(%servers)) {
10207: 		my $answer=reply('load',$tryserver);
10208: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
10209: 		    $loadm=$answer;
10210: 		    $unhome=$tryserver;
10211: 		}
10212: 	    }
10213:         }
10214:         if (($unhome eq '') || ($unhome eq 'no_host')) {
10215: 	    return 'error: unable to find a home server for '.$uname.
10216:                    ' in domain '.$udom;
10217:         }
10218:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
10219:                          &escape($upass),$unhome);
10220: 	unless ($reply eq 'ok') {
10221:             return 'error: '.$reply;
10222:         }   
10223:         $uhome=&homeserver($uname,$udom,'true');
10224:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
10225: 	    return 'error: unable verify users home machine.';
10226:         }
10227:     }   # End of creation of new user
10228: # ---------------------------------------------------------------------- Add ID
10229:     if ($uid) {
10230:        $uid=~tr/A-Z/a-z/;
10231:        my %uidhash=&idrget($udom,$uname);
10232:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
10233:          && (!$forceid)) {
10234: 	  unless ($uid eq $uidhash{$uname}) {
10235: 	      return 'error: user id "'.$uid.'" does not match '.
10236:                   'current user id "'.$uidhash{$uname}.'".';
10237:           }
10238:        } else {
10239: 	  &idput($udom,{$uname => $uid},$uhome,'ids');
10240:        }
10241:     }
10242: # -------------------------------------------------------------- Add names, etc
10243:     my @tmp=&get('environment',
10244: 		   ['firstname','middlename','lastname','generation','id',
10245:                     'permanentemail','inststatus'],
10246: 		   $udom,$uname);
10247:     my (%names,%oldnames);
10248:     if ($tmp[0] =~ m/^error:.*/) { 
10249:         %names=(); 
10250:     } else {
10251:         %names = @tmp;
10252:         %oldnames = %names;
10253:     }
10254: #
10255: # If name, email and/or uid are blank (e.g., because an uploaded file
10256: # of users did not contain them), do not overwrite existing values
10257: # unless field is in $candelete array ref.  
10258: #
10259: 
10260:     my @fields = ('firstname','middlename','lastname','generation',
10261:                   'permanentemail','id');
10262:     my %newvalues;
10263:     if (ref($candelete) eq 'ARRAY') {
10264:         foreach my $field (@fields) {
10265:             if (grep(/^\Q$field\E$/,@{$candelete})) {
10266:                 if ($field eq 'firstname') {
10267:                     $names{$field} = $first;
10268:                 } elsif ($field eq 'middlename') {
10269:                     $names{$field} = $middle;
10270:                 } elsif ($field eq 'lastname') {
10271:                     $names{$field} = $last;
10272:                 } elsif ($field eq 'generation') { 
10273:                     $names{$field} = $gene;
10274:                 } elsif ($field eq 'permanentemail') {
10275:                     $names{$field} = $email;
10276:                 } elsif ($field eq 'id') {
10277:                     $names{$field}  = $uid;
10278:                 }
10279:             }
10280:         }
10281:     }
10282:     if ($first)  { $names{'firstname'}  = $first; }
10283:     if (defined($middle)) { $names{'middlename'} = $middle; }
10284:     if ($last)   { $names{'lastname'}   = $last; }
10285:     if (defined($gene))   { $names{'generation'} = $gene; }
10286:     if ($email) {
10287:        $email=~s/[^\w\@\.\-\,]//gs;
10288:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
10289:     }
10290:     if ($uid) { $names{'id'}  = $uid; }
10291:     if (defined($inststatus)) {
10292:         $names{'inststatus'} = '';
10293:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
10294:         if (ref($usertypes) eq 'HASH') {
10295:             my @okstatuses; 
10296:             foreach my $item (split(/:/,$inststatus)) {
10297:                 if (defined($usertypes->{$item})) {
10298:                     push(@okstatuses,$item);  
10299:                 }
10300:             }
10301:             if (@okstatuses) {
10302:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
10303:             }
10304:         }
10305:     }
10306:     my $logmsg = $udom.', '.$uname.', '.$uid.', '.
10307:                  $umode.', '.$first.', '.$middle.', '.
10308:                  $last.', '.$gene.', '.$email.', '.$inststatus;
10309:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
10310:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
10311:     } else {
10312:         $logmsg .= ' during self creation';
10313:     }
10314:     my $changed;
10315:     if ($newuser) {
10316:         $changed = 1;
10317:     } else {
10318:         foreach my $field (@fields) {
10319:             if ($names{$field} ne $oldnames{$field}) {
10320:                 $changed = 1;
10321:                 last;
10322:             }
10323:         }
10324:     }
10325:     unless ($changed) {
10326:         $logmsg = 'No changes in user information needed for: '.$logmsg;
10327:         &logthis($logmsg);
10328:         return 'ok';
10329:     }
10330:     my $reply = &put('environment', \%names, $udom,$uname);
10331:     if ($reply ne 'ok') { 
10332:         return 'error: '.$reply;
10333:     }
10334:     if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
10335:         &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
10336:     }
10337:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
10338:     &devalidate_cache_new('namescache',$uname.':'.$udom);
10339:     $logmsg = 'Success modifying user '.$logmsg;
10340:     &logthis($logmsg);
10341:     return 'ok';
10342: }
10343: 
10344: # -------------------------------------------------------------- Modify student
10345: 
10346: sub modifystudent {
10347:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
10348:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
10349:         $selfenroll,$context,$inststatus,$credits,$instsec)=@_;
10350:     if (!$cid) {
10351: 	unless ($cid=$env{'request.course.id'}) {
10352: 	    return 'not_in_class';
10353: 	}
10354:     }
10355: # --------------------------------------------------------------- Make the user
10356:     my $reply=&modifyuser
10357: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
10358:          $desiredhome,$email,$inststatus);
10359:     unless ($reply eq 'ok') { return $reply; }
10360:     # This will cause &modify_student_enrollment to get the uid from the
10361:     # student's environment
10362:     $uid = undef if (!$forceid);
10363:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
10364:                                         $gene,$usec,$end,$start,$type,$locktype,
10365:                                         $cid,$selfenroll,$context,$credits,$instsec);
10366:     return $reply;
10367: }
10368: 
10369: sub modify_student_enrollment {
10370:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,
10371:         $locktype,$cid,$selfenroll,$context,$credits,$instsec) = @_;
10372:     my ($cdom,$cnum,$chome);
10373:     if (!$cid) {
10374: 	unless ($cid=$env{'request.course.id'}) {
10375: 	    return 'not_in_class';
10376: 	}
10377: 	$cdom=$env{'course.'.$cid.'.domain'};
10378: 	$cnum=$env{'course.'.$cid.'.num'};
10379:     } else {
10380: 	($cdom,$cnum)=split(/_/,$cid);
10381:     }
10382:     $chome=$env{'course.'.$cid.'.home'};
10383:     if (!$chome) {
10384: 	$chome=&homeserver($cnum,$cdom);
10385:     }
10386:     if (!$chome) { return 'unknown_course'; }
10387:     # Make sure the user exists
10388:     my $uhome=&homeserver($uname,$udom);
10389:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
10390: 	return 'error: no such user';
10391:     }
10392:     # Get student data if we were not given enough information
10393:     if (!defined($first)  || $first  eq '' || 
10394:         !defined($last)   || $last   eq '' || 
10395:         !defined($uid)    || $uid    eq '' || 
10396:         !defined($middle) || $middle eq '' || 
10397:         !defined($gene)   || $gene   eq '') {
10398:         # They did not supply us with enough data to enroll the student, so
10399:         # we need to pick up more information.
10400:         my %tmp = &get('environment',
10401:                        ['firstname','middlename','lastname', 'generation','id']
10402:                        ,$udom,$uname);
10403: 
10404:         #foreach my $key (keys(%tmp)) {
10405:         #    &logthis("key $key = ".$tmp{$key});
10406:         #}
10407:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
10408:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
10409:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
10410:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
10411:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
10412:     }
10413:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
10414:     my $user = "$uname:$udom";
10415:     my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
10416:     my $reply=cput('classlist',
10417: 		   {$user => 
10418: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits,$instsec) },
10419: 		   $cdom,$cnum);
10420:     if (($reply eq 'ok') || ($reply eq 'delayed')) {
10421:         &devalidate_getsection_cache($udom,$uname,$cid);
10422:     } else { 
10423: 	return 'error: '.$reply;
10424:     }
10425:     # Add student role to user
10426:     my $uurl='/'.$cid;
10427:     $uurl=~s/\_/\//g;
10428:     if ($usec) {
10429: 	$uurl.='/'.$usec;
10430:     }
10431:     my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
10432:                              $selfenroll,$context);
10433:     if ($result ne 'ok') {
10434:         if ($old_entry{$user} ne '') {
10435:             $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
10436:         } else {
10437:             $reply = &del('classlist',[$user],$cdom,$cnum);
10438:         }
10439:     }
10440:     return $result; 
10441: }
10442: 
10443: sub format_name {
10444:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
10445:     my $name;
10446:     if ($first ne 'lastname') {
10447: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
10448:     } else {
10449: 	if ($lastname=~/\S/) {
10450: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
10451: 	    $name=~s/\s+,/,/;
10452: 	} else {
10453: 	    $name.= $firstname.' '.$middlename.' '.$generation;
10454: 	}
10455:     }
10456:     $name=~s/^\s+//;
10457:     $name=~s/\s+$//;
10458:     $name=~s/\s+/ /g;
10459:     return $name;
10460: }
10461: 
10462: # ------------------------------------------------- Write to course preferences
10463: 
10464: sub writecoursepref {
10465:     my ($courseid,%prefs)=@_;
10466:     $courseid=~s/^\///;
10467:     $courseid=~s/\_/\//g;
10468:     my ($cdomain,$cnum)=split(/\//,$courseid);
10469:     my $chome=homeserver($cnum,$cdomain);
10470:     if (($chome eq '') || ($chome eq 'no_host')) { 
10471: 	return 'error: no such course';
10472:     }
10473:     my $cstring='';
10474:     foreach my $pref (keys(%prefs)) {
10475: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
10476:     }
10477:     $cstring=~s/\&$//;
10478:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
10479: }
10480: 
10481: # ---------------------------------------------------------- Make/modify course
10482: 
10483: sub createcourse {
10484:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
10485:         $course_owner,$crstype,$cnum,$context,$category)=@_;
10486:     $url=&declutter($url);
10487:     my $cid='';
10488:     if ($context eq 'requestcourses') {
10489:         my $can_create = 0;
10490:         my ($ownername,$ownerdom) = split(':',$course_owner);
10491:         if ($udom eq $ownerdom) {
10492:             if (&usertools_access($ownername,$ownerdom,$category,undef,
10493:                                   $context)) {
10494:                 $can_create = 1;
10495:             }
10496:         } else {
10497:             my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
10498:                                            $category);
10499:             if ($userenv{'reqcrsotherdom.'.$category} ne '') {
10500:                 my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
10501:                 if (@curr > 0) {
10502:                     my @options = qw(approval validate autolimit);
10503:                     my $optregex = join('|',@options);
10504:                     if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
10505:                         $can_create = 1;
10506:                     }
10507:                 }
10508:             }
10509:         }
10510:         if ($can_create) {
10511:             unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
10512:                 unless (&allowed('ccc',$udom)) {
10513:                     return 'refused'; 
10514:                 }
10515:             }
10516:         } else {
10517:             return 'refused';
10518:         }
10519:     } elsif (!&allowed('ccc',$udom)) {
10520:         return 'refused';
10521:     }
10522: # --------------------------------------------------------------- Get Unique ID
10523:     my $uname;
10524:     if ($cnum =~ /^$match_courseid$/) {
10525:         my $chome=&homeserver($cnum,$udom,'true');
10526:         if (($chome eq '') || ($chome eq 'no_host')) {
10527:             $uname = $cnum;
10528:         } else {
10529:             $uname = &generate_coursenum($udom,$crstype);
10530:         }
10531:     } else {
10532:         $uname = &generate_coursenum($udom,$crstype);
10533:     }
10534:     return $uname if ($uname =~ /^error/);
10535: # -------------------------------------------------- Check supplied server name
10536:     if (!defined($course_server)) {
10537:         if (defined(&domain($udom,'primary'))) {
10538:             $course_server = &domain($udom,'primary');
10539:         } else {
10540:             $course_server = $env{'user.home'}; 
10541:         }
10542:     }
10543:     my %host_servers =
10544:         &Apache::lonnet::get_servers($udom,'library');
10545:     unless ($host_servers{$course_server}) {
10546:         return 'error: invalid home server for course: '.$course_server;
10547:     }
10548: # ------------------------------------------------------------- Make the course
10549:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
10550:                       $course_server);
10551:     unless ($reply eq 'ok') { return 'error: '.$reply; }
10552:     my $uhome=&homeserver($uname,$udom,'true');
10553:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
10554: 	return 'error: no such course';
10555:     }
10556: # ----------------------------------------------------------------- Course made
10557: # log existence
10558:     my $now = time;
10559:     my $newcourse = {
10560:                     $udom.'_'.$uname => {
10561:                                      description => $description,
10562:                                      inst_code   => $inst_code,
10563:                                      owner       => $course_owner,
10564:                                      type        => $crstype,
10565:                                      creator     => $env{'user.name'}.':'.
10566:                                                     $env{'user.domain'},
10567:                                      created     => $now,
10568:                                      context     => $context,
10569:                                                 },
10570:                     };
10571:     &courseidput($udom,$newcourse,$uhome,'notime');
10572: # set toplevel url
10573:     my $topurl=$url;
10574:     unless ($nonstandard) {
10575: # ------------------------------------------ For standard courses, make top url
10576:         my $mapurl=&clutter($url);
10577:         if ($mapurl eq '/res/') { $mapurl=''; }
10578:         $env{'form.initmap'}=(<<ENDINITMAP);
10579: <map>
10580: <resource id="1" type="start"></resource>
10581: <resource id="2" src="$mapurl"></resource>
10582: <resource id="3" type="finish"></resource>
10583: <link index="1" from="1" to="2"></link>
10584: <link index="2" from="2" to="3"></link>
10585: </map>
10586: ENDINITMAP
10587:         $topurl=&declutter(
10588:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
10589:                           );
10590:     }
10591: # ----------------------------------------------------------- Write preferences
10592:     &writecoursepref($udom.'_'.$uname,
10593:                      ('description'              => $description,
10594:                       'url'                      => $topurl,
10595:                       'internal.creator'         => $env{'user.name'}.':'.
10596:                                                     $env{'user.domain'},
10597:                       'internal.created'         => $now,
10598:                       'internal.creationcontext' => $context)
10599:                     );
10600:     return '/'.$udom.'/'.$uname;
10601: }
10602: 
10603: # ------------------------------------------------------------------- Create ID
10604: sub generate_coursenum {
10605:     my ($udom,$crstype) = @_;
10606:     my $domdesc = &domain($udom);
10607:     return 'error: invalid domain' if ($domdesc eq '');
10608:     my $first;
10609:     if ($crstype eq 'Community') {
10610:         $first = '0';
10611:     } else {
10612:         $first = int(1+rand(9)); 
10613:     } 
10614:     my $uname=$first.
10615:         ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
10616:         substr($$.time,0,5).unpack("H8",pack("I32",time)).
10617:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
10618: # ----------------------------------------------- Make sure that does not exist
10619:     my $uhome=&homeserver($uname,$udom,'true');
10620:     unless (($uhome eq '') || ($uhome eq 'no_host')) {
10621:         if ($crstype eq 'Community') {
10622:             $first = '0';
10623:         } else {
10624:             $first = int(1+rand(9));
10625:         }
10626:         $uname=$first.
10627:                ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
10628:                substr($$.time,0,5).unpack("H8",pack("I32",time)).
10629:                unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
10630:         $uhome=&homeserver($uname,$udom,'true');
10631:         unless (($uhome eq '') || ($uhome eq 'no_host')) {
10632:             return 'error: unable to generate unique course-ID';
10633:         }
10634:     }
10635:     return $uname;
10636: }
10637: 
10638: sub is_course {
10639:     my ($cdom, $cnum) = scalar(@_) == 1 ? 
10640:          ($_[0] =~ /^($match_domain)_($match_courseid)$/)  :  @_;
10641: 
10642:     return unless (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/));
10643:     my $uhome=&homeserver($cnum,$cdom);
10644:     my $iscourse;
10645:     if (grep { $_ eq $uhome } current_machine_ids()) {
10646:         $iscourse = &LONCAPA::Lond::is_course($cdom,$cnum);
10647:     } else {
10648:         my $hashid = $cdom.':'.$cnum;
10649:         ($iscourse,my $cached) = &is_cached_new('iscourse',$hashid);
10650:         unless (defined($cached)) {
10651:             my %courses = &courseiddump($cdom, '.', 1, '.', '.',
10652:                                         $cnum,undef,undef,'.');
10653:             $iscourse = 0;
10654:             if (exists($courses{$cdom.'_'.$cnum})) {
10655:                 $iscourse = 1;
10656:             }
10657:             &do_cache_new('iscourse',$hashid,$iscourse,3600);
10658:         }
10659:     }
10660:     return unless ($iscourse);
10661:     return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
10662: }
10663: 
10664: sub store_userdata {
10665:     my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
10666:     my $result;
10667:     if ($datakey ne '') {
10668:         if (ref($storehash) eq 'HASH') {
10669:             if ($udom eq '' || $uname eq '') {
10670:                 $udom = $env{'user.domain'};
10671:                 $uname = $env{'user.name'};
10672:             }
10673:             my $uhome=&homeserver($uname,$udom);
10674:             if (($uhome eq '') || ($uhome eq 'no_host')) {
10675:                 $result = 'error: no_host';
10676:             } else {
10677:                 $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
10678:                 $storehash->{'host'} = $perlvar{'lonHostID'};
10679: 
10680:                 my $namevalue='';
10681:                 foreach my $key (keys(%{$storehash})) {
10682:                     $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
10683:                 }
10684:                 $namevalue=~s/\&$//;
10685:                 unless ($namespace eq 'courserequests') {
10686:                     $datakey = &escape($datakey);
10687:                 }
10688:                 $result =  &reply("store:$udom:$uname:$namespace:$datakey:".
10689:                                   $namevalue,$uhome);
10690:             }
10691:         } else {
10692:             $result = 'error: data to store was not a hash reference'; 
10693:         }
10694:     } else {
10695:         $result= 'error: invalid requestkey'; 
10696:     }
10697:     return $result;
10698: }
10699: 
10700: # ---------------------------------------------------------- Assign Custom Role
10701: 
10702: sub assigncustomrole {
10703:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
10704:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
10705:                        $end,$start,$deleteflag,$selfenroll,$context);
10706: }
10707: 
10708: # ----------------------------------------------------------------- Revoke Role
10709: 
10710: sub revokerole {
10711:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
10712:     my $now=time;
10713:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
10714: }
10715: 
10716: # ---------------------------------------------------------- Revoke Custom Role
10717: 
10718: sub revokecustomrole {
10719:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
10720:     my $now=time;
10721:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
10722:            $deleteflag,$selfenroll,$context);
10723: }
10724: 
10725: # ------------------------------------------------------------ Disk usage
10726: sub diskusage {
10727:     my ($udom,$uname,$directorypath,$getpropath)=@_;
10728:     $directorypath =~ s/\/$//;
10729:     my $listing=&reply('du2:'.&escape($directorypath).':'
10730:                        .&escape($getpropath).':'.&escape($uname).':'
10731:                        .&escape($udom),homeserver($uname,$udom));
10732:     if ($listing eq 'unknown_cmd') {
10733:         if ($getpropath) {
10734:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
10735:         }
10736:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
10737:     }
10738:     return $listing;
10739: }
10740: 
10741: sub is_locked {
10742:     my ($file_name, $domain, $user, $which) = @_;
10743:     my @check;
10744:     my $is_locked;
10745:     push (@check,$file_name);
10746:     my %locked = &get('file_permissions',\@check,
10747: 		      $env{'user.domain'},$env{'user.name'});
10748:     my ($tmp)=keys(%locked);
10749:     if ($tmp=~/^error:/) { undef(%locked); }
10750:     
10751:     if (ref($locked{$file_name}) eq 'ARRAY') {
10752:         $is_locked = 'false';
10753:         foreach my $entry (@{$locked{$file_name}}) {
10754:            if (ref($entry) eq 'ARRAY') {
10755:                $is_locked = 'true';
10756:                if (ref($which) eq 'ARRAY') {
10757:                    push(@{$which},$entry);
10758:                } else {
10759:                    last;
10760:                }
10761:            }
10762:        }
10763:     } else {
10764:         $is_locked = 'false';
10765:     }
10766:     return $is_locked;
10767: }
10768: 
10769: sub declutter_portfile {
10770:     my ($file) = @_;
10771:     $file =~ s{^(/portfolio/|portfolio/)}{/};
10772:     return $file;
10773: }
10774: 
10775: # ------------------------------------------------------------- Mark as Read Only
10776: 
10777: sub mark_as_readonly {
10778:     my ($domain,$user,$files,$what) = @_;
10779:     my %current_permissions = &dump('file_permissions',$domain,$user);
10780:     my ($tmp)=keys(%current_permissions);
10781:     if ($tmp=~/^error:/) { undef(%current_permissions); }
10782:     foreach my $file (@{$files}) {
10783: 	$file = &declutter_portfile($file);
10784:         push(@{$current_permissions{$file}},$what);
10785:     }
10786:     &put('file_permissions',\%current_permissions,$domain,$user);
10787:     return;
10788: }
10789: 
10790: # ------------------------------------------------------------Save Selected Files
10791: 
10792: sub save_selected_files {
10793:     my ($user, $path, @files) = @_;
10794:     my $filename = $user."savedfiles";
10795:     my @other_files = &files_not_in_path($user, $path);
10796:     open (OUT,'>',LONCAPA::tempdir().$filename);
10797:     foreach my $file (@files) {
10798:         print (OUT $env{'form.currentpath'}.$file."\n");
10799:     }
10800:     foreach my $file (@other_files) {
10801:         print (OUT $file."\n");
10802:     }
10803:     close (OUT);
10804:     return 'ok';
10805: }
10806: 
10807: sub clear_selected_files {
10808:     my ($user) = @_;
10809:     my $filename = $user."savedfiles";
10810:     open (OUT,'>',LONCAPA::tempdir().$filename);
10811:     print (OUT undef);
10812:     close (OUT);
10813:     return ("ok");    
10814: }
10815: 
10816: sub files_in_path {
10817:     my ($user, $path) = @_;
10818:     my $filename = $user."savedfiles";
10819:     my %return_files;
10820:     open (IN,'<',LONCAPA::tempdir().$filename);
10821:     while (my $line_in = <IN>) {
10822:         chomp ($line_in);
10823:         my @paths_and_file = split (m!/!, $line_in);
10824:         my $file_part = pop (@paths_and_file);
10825:         my $path_part = join ('/', @paths_and_file);
10826:         $path_part.='/';
10827:         my $path_and_file = $path_part.$file_part;
10828:         if ($path_part eq $path) {
10829:             $return_files{$file_part}= 'selected';
10830:         }
10831:     }
10832:     close (IN);
10833:     return (\%return_files);
10834: }
10835: 
10836: # called in portfolio select mode, to show files selected NOT in current directory
10837: sub files_not_in_path {
10838:     my ($user, $path) = @_;
10839:     my $filename = $user."savedfiles";
10840:     my @return_files;
10841:     my $path_part;
10842:     open(IN, '<',LONCAPA::tempdir().$filename);
10843:     while (my $line = <IN>) {
10844:         #ok, I know it's clunky, but I want it to work
10845:         my @paths_and_file = split(m|/|, $line);
10846:         my $file_part = pop(@paths_and_file);
10847:         chomp($file_part);
10848:         my $path_part = join('/', @paths_and_file);
10849:         $path_part .= '/';
10850:         my $path_and_file = $path_part.$file_part;
10851:         if ($path_part ne $path) {
10852:             push(@return_files, ($path_and_file));
10853:         }
10854:     }
10855:     close(OUT);
10856:     return (@return_files);
10857: }
10858: 
10859: #------------------------------Submitted/Handedback Portfolio Files Versioning
10860:  
10861: sub portfiles_versioning {
10862:     my ($symb,$domain,$stu_name,$portfiles,$versioned_portfiles) = @_;
10863:     my $portfolio_root = '/userfiles/portfolio';
10864:     return unless ((ref($portfiles) eq 'ARRAY') && (ref($versioned_portfiles) eq 'ARRAY'));
10865:     foreach my $file (@{$portfiles}) {
10866:         &unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
10867:         my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
10868:         my ($answer_name,$answer_ver,$answer_ext) = &file_name_version_ext($answer_file);
10869:         my $getpropath = 1;
10870:         my ($dir_list,$listerror) = &dirlist($portfolio_root.$directory,$domain,
10871:                                              $stu_name,$getpropath);
10872:         my $version = &get_next_version($answer_name,$answer_ext,$dir_list);
10873:         my $new_answer = 
10874:             &version_selected_portfile($domain,$stu_name,$directory,$answer_file,$version);
10875:         if ($new_answer ne 'problem getting file') {
10876:             push(@{$versioned_portfiles}, $directory.$new_answer);
10877:             &mark_as_readonly($domain,$stu_name,[$directory.$new_answer],
10878:                               [$symb,$env{'request.course.id'},'graded']);
10879:         }
10880:     }
10881: }
10882: 
10883: sub get_next_version {
10884:     my ($answer_name, $answer_ext, $dir_list) = @_;
10885:     my $version;
10886:     if (ref($dir_list) eq 'ARRAY') {
10887:         foreach my $row (@{$dir_list}) {
10888:             my ($file) = split(/\&/,$row,2);
10889:             my ($file_name,$file_version,$file_ext) =
10890:                 &file_name_version_ext($file);
10891:             if (($file_name eq $answer_name) &&
10892:                 ($file_ext eq $answer_ext)) {
10893:                      # gets here if filename and extension match,
10894:                      # regardless of version
10895:                 if ($file_version ne '') {
10896:                     # a versioned file is found  so save it for later
10897:                     if ($file_version > $version) {
10898:                         $version = $file_version;
10899:                     }
10900:                 }
10901:             }
10902:         }
10903:     }
10904:     $version ++;
10905:     return($version);
10906: }
10907: 
10908: sub version_selected_portfile {
10909:     my ($domain,$stu_name,$directory,$file_name,$version) = @_;
10910:     my ($answer_name,$answer_ver,$answer_ext) =
10911:         &file_name_version_ext($file_name);
10912:     my $new_answer;
10913:     $env{'form.copy'} =
10914:         &getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
10915:     if($env{'form.copy'} eq '-1') {
10916:         $new_answer = 'problem getting file';
10917:     } else {
10918:         $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
10919:         my $copy_result = 
10920:             &finishuserfileupload($stu_name,$domain,'copy',
10921:                                   '/portfolio'.$directory.$new_answer);
10922:     }
10923:     undef($env{'form.copy'});
10924:     return ($new_answer);
10925: }
10926: 
10927: sub file_name_version_ext {
10928:     my ($file)=@_;
10929:     my @file_parts = split(/\./, $file);
10930:     my ($name,$version,$ext);
10931:     if (@file_parts > 1) {
10932:         $ext=pop(@file_parts);
10933:         if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
10934:             $version=pop(@file_parts);
10935:         }
10936:         $name=join('.',@file_parts);
10937:     } else {
10938:         $name=join('.',@file_parts);
10939:     }
10940:     return($name,$version,$ext);
10941: }
10942: 
10943: #----------------------------------------------Get portfolio file permissions
10944: 
10945: sub get_portfile_permissions {
10946:     my ($domain,$user) = @_;
10947:     my %current_permissions = &dump('file_permissions',$domain,$user);
10948:     my ($tmp)=keys(%current_permissions);
10949:     if ($tmp=~/^error:/) { undef(%current_permissions); }
10950:     return \%current_permissions;
10951: }
10952: 
10953: #---------------------------------------------Get portfolio file access controls
10954: 
10955: sub get_access_controls {
10956:     my ($current_permissions,$group,$file) = @_;
10957:     my %access;
10958:     my $real_file = $file;
10959:     $file =~ s/\.meta$//;
10960:     if (defined($file)) {
10961:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
10962:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
10963:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
10964:             }
10965:         }
10966:     } else {
10967:         foreach my $key (keys(%{$current_permissions})) {
10968:             if ($key =~ /\0accesscontrol$/) {
10969:                 if (defined($group)) {
10970:                     if ($key !~ m-^\Q$group\E/-) {
10971:                         next;
10972:                     }
10973:                 }
10974:                 my ($fullpath) = split(/\0/,$key);
10975:                 if (ref($$current_permissions{$key}) eq 'HASH') {
10976:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
10977:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
10978:                     }
10979:                 }
10980:             }
10981:         }
10982:     }
10983:     return %access;
10984: }
10985: 
10986: sub modify_access_controls {
10987:     my ($file_name,$changes,$domain,$user)=@_;
10988:     my ($outcome,$deloutcome);
10989:     my %store_permissions;
10990:     my %new_values;
10991:     my %new_control;
10992:     my %translation;
10993:     my @deletions = ();
10994:     my $now = time;
10995:     if (exists($$changes{'activate'})) {
10996:         if (ref($$changes{'activate'}) eq 'HASH') {
10997:             my @newitems = sort(keys(%{$$changes{'activate'}}));
10998:             my $numnew = scalar(@newitems);
10999:             for (my $i=0; $i<$numnew; $i++) {
11000:                 my $newkey = $newitems[$i];
11001:                 my $newid = &Apache::loncommon::get_cgi_id();
11002:                 if ($newkey =~ /^\d+:/) { 
11003:                     $newkey =~ s/^(\d+)/$newid/;
11004:                     $translation{$1} = $newid;
11005:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
11006:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
11007:                     $translation{$1} = $newid;
11008:                 }
11009:                 $new_values{$file_name."\0".$newkey} = 
11010:                                           $$changes{'activate'}{$newitems[$i]};
11011:                 $new_control{$newkey} = $now;
11012:             }
11013:         }
11014:     }
11015:     my %todelete;
11016:     my %changed_items;
11017:     foreach my $action ('delete','update') {
11018:         if (exists($$changes{$action})) {
11019:             if (ref($$changes{$action}) eq 'HASH') {
11020:                 foreach my $key (keys(%{$$changes{$action}})) {
11021:                     my ($itemnum) = ($key =~ /^([^:]+):/);
11022:                     if ($action eq 'delete') { 
11023:                         $todelete{$itemnum} = 1;
11024:                     } else {
11025:                         $changed_items{$itemnum} = $key;
11026:                     }
11027:                 }
11028:             }
11029:         }
11030:     }
11031:     # get lock on access controls for file.
11032:     my $lockhash = {
11033:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
11034:                                                        ':'.$env{'user.domain'},
11035:                    }; 
11036:     my $tries = 0;
11037:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
11038:    
11039:     while (($gotlock ne 'ok') && $tries < 10) {
11040:         $tries ++;
11041:         sleep(0.1);
11042:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
11043:     }
11044:     if ($gotlock eq 'ok') {
11045:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
11046:         my ($tmp)=keys(%curr_permissions);
11047:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
11048:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
11049:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
11050:             if (ref($curr_controls) eq 'HASH') {
11051:                 foreach my $control_item (keys(%{$curr_controls})) {
11052:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
11053:                     if (defined($todelete{$itemnum})) {
11054:                         push(@deletions,$file_name."\0".$control_item);
11055:                     } else {
11056:                         if (defined($changed_items{$itemnum})) {
11057:                             $new_control{$changed_items{$itemnum}} = $now;
11058:                             push(@deletions,$file_name."\0".$control_item);
11059:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
11060:                         } else {
11061:                             $new_control{$control_item} = $$curr_controls{$control_item};
11062:                         }
11063:                     }
11064:                 }
11065:             }
11066:         }
11067:         my ($group);
11068:         if (&is_course($domain,$user)) {
11069:             ($group,my $file) = split(/\//,$file_name,2);
11070:         }
11071:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
11072:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
11073:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
11074:         #  remove lock
11075:         my @del_lock = ($file_name."\0".'locked_access_records');
11076:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
11077:         my $sqlresult =
11078:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
11079:                                     $group);
11080:     } else {
11081:         $outcome = "error: could not obtain lockfile\n";  
11082:     }
11083:     return ($outcome,$deloutcome,\%new_values,\%translation);
11084: }
11085: 
11086: sub make_public_indefinitely {
11087:     my (@requrl) = @_;
11088:     return &automated_portfile_access('public',\@requrl);
11089: }
11090: 
11091: sub automated_portfile_access {
11092:     my ($accesstype,$addsref,$delsref,$info) = @_;
11093:     unless (($accesstype eq 'public') || ($accesstype eq 'ip')) {
11094:         return 'invalid';
11095:     }
11096:     my %urls;
11097:     if (ref($addsref) eq 'ARRAY') {
11098:         foreach my $requrl (@{$addsref}) {
11099:             if (&is_portfolio_url($requrl)) {
11100:                 unless (exists($urls{$requrl})) {
11101:                     $urls{$requrl} = 'add';
11102:                 }
11103:             }
11104:         }
11105:     }
11106:     if (ref($delsref) eq 'ARRAY') {
11107:         foreach my $requrl (@{$delsref}) { 
11108:             if (&is_portfolio_url($requrl)) {
11109:                 unless (exists($urls{$requrl})) {
11110:                     $urls{$requrl} = 'delete'; 
11111:                 }
11112:             }
11113:         }
11114:     }
11115:     unless (keys(%urls)) {
11116:         return 'invalid';
11117:     }
11118:     my $ip;
11119:     if ($accesstype eq 'ip') {
11120:         if (ref($info) eq 'HASH') {
11121:             if ($info->{'ip'} ne '') {
11122:                 $ip = $info->{'ip'};
11123:             }
11124:         }
11125:         if ($ip eq '') {
11126:             return 'invalid';
11127:         }
11128:     }
11129:     my $errors;
11130:     my $now = time;
11131:     my %current_perms;
11132:     foreach my $requrl (sort(keys(%urls))) {
11133:         my $action;
11134:         if ($urls{$requrl} eq 'add') {
11135:             $action = 'activate';
11136:         } else {
11137:             $action = 'none';
11138:         }
11139:         my $aclnum = 0;
11140:         my (undef,$udom,$unum,$file_name,$group) =
11141:             &parse_portfolio_url($requrl);
11142:         unless (exists($current_perms{$unum.':'.$udom})) {
11143:             $current_perms{$unum.':'.$udom} = &get_portfile_permissions($udom,$unum);
11144:         }
11145:         my %access_controls = &get_access_controls($current_perms{$unum.':'.$udom},
11146:                                                    $group,$file_name);
11147:         foreach my $key (keys(%{$access_controls{$file_name}})) {
11148:             my ($num,$scope,$end,$start) = 
11149:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
11150:             if ($scope eq $accesstype) {
11151:                 if (($start <= $now) && ($end == 0)) {
11152:                     if ($accesstype eq 'ip') {
11153:                         if (ref($access_controls{$file_name}{$key}) eq 'HASH') {
11154:                             if (ref($access_controls{$file_name}{$key}{'ip'}) eq 'ARRAY') {
11155:                                 if (grep(/^\Q$ip\E$/,@{$access_controls{$file_name}{$key}{'ip'}})) {
11156:                                     if ($urls{$requrl} eq 'add') {
11157:                                         $action = 'none';
11158:                                         last;
11159:                                     } else {
11160:                                         $action = 'delete';
11161:                                         $aclnum = $num;
11162:                                         last;
11163:                                     }
11164:                                 }
11165:                             }
11166:                         }
11167:                     } elsif ($accesstype eq 'public') {
11168:                         if ($urls{$requrl} eq 'add') {
11169:                             $action = 'none';
11170:                             last;
11171:                         } else {
11172:                             $action = 'delete';
11173:                             $aclnum = $num;
11174:                             last;
11175:                         }
11176:                     }
11177:                 } elsif ($accesstype eq 'public') {
11178:                     $action = 'update';
11179:                     $aclnum = $num;
11180:                     last;
11181:                 }
11182:             }
11183:         }
11184:         if ($action eq 'none') {
11185:             next;
11186:         } else {
11187:             my %changes;
11188:             my $newend = 0;
11189:             my $newstart = $now;
11190:             my $newkey = $aclnum.':'.$accesstype.'_'.$newend.'_'.$newstart;
11191:             $changes{$action}{$newkey} = {
11192:                 type => $accesstype,
11193:                 time => {
11194:                     start => $newstart,
11195:                     end   => $newend,
11196:                 },
11197:             };
11198:             if ($accesstype eq 'ip') {
11199:                 $changes{$action}{$newkey}{'ip'} = [$ip];
11200:             }
11201:             my ($outcome,$deloutcome,$new_values,$translation) =
11202:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
11203:             unless ($outcome eq 'ok') {
11204:                 $errors .= $outcome.' ';
11205:             }
11206:         }
11207:     }
11208:     if ($errors) {
11209:         $errors =~ s/\s$//;
11210:         return $errors;
11211:     } else {
11212:         return 'ok';
11213:     }
11214: }
11215: 
11216: #------------------------------------------------------Get Marked as Read Only
11217: 
11218: sub get_marked_as_readonly {
11219:     my ($domain,$user,$what,$group) = @_;
11220:     my $current_permissions = &get_portfile_permissions($domain,$user);
11221:     my @readonly_files;
11222:     my $cmp1=$what;
11223:     if (ref($what)) { $cmp1=join('',@{$what}) };
11224:     while (my ($file_name,$value) = each(%{$current_permissions})) {
11225:         if (defined($group)) {
11226:             if ($file_name !~ m-^\Q$group\E/-) {
11227:                 next;
11228:             }
11229:         }
11230:         if (ref($value) eq "ARRAY"){
11231:             foreach my $stored_what (@{$value}) {
11232:                 my $cmp2=$stored_what;
11233:                 if (ref($stored_what) eq 'ARRAY') {
11234:                     $cmp2=join('',@{$stored_what});
11235:                 }
11236:                 if ($cmp1 eq $cmp2) {
11237:                     push(@readonly_files, $file_name);
11238:                     last;
11239:                 } elsif (!defined($what)) {
11240:                     push(@readonly_files, $file_name);
11241:                     last;
11242:                 }
11243:             }
11244:         }
11245:     }
11246:     return @readonly_files;
11247: }
11248: #-----------------------------------------------------------Get Marked as Read Only Hash
11249: 
11250: sub get_marked_as_readonly_hash {
11251:     my ($current_permissions,$group,$what) = @_;
11252:     my %readonly_files;
11253:     while (my ($file_name,$value) = each(%{$current_permissions})) {
11254:         if (defined($group)) {
11255:             if ($file_name !~ m-^\Q$group\E/-) {
11256:                 next;
11257:             }
11258:         }
11259:         if (ref($value) eq "ARRAY"){
11260:             foreach my $stored_what (@{$value}) {
11261:                 if (ref($stored_what) eq 'ARRAY') {
11262:                     foreach my $lock_descriptor(@{$stored_what}) {
11263:                         if ($lock_descriptor eq 'graded') {
11264:                             $readonly_files{$file_name} = 'graded';
11265:                         } elsif ($lock_descriptor eq 'handback') {
11266:                             $readonly_files{$file_name} = 'handback';
11267:                         } else {
11268:                             if (!exists($readonly_files{$file_name})) {
11269:                                 $readonly_files{$file_name} = 'locked';
11270:                             }
11271:                         }
11272:                     }
11273:                 } 
11274:             }
11275:         } 
11276:     }
11277:     return %readonly_files;
11278: }
11279: # ------------------------------------------------------------ Unmark as Read Only
11280: 
11281: sub unmark_as_readonly {
11282:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
11283:     # for portfolio submissions, $what contains [$symb,$crsid] 
11284:     my ($domain,$user,$what,$file_name,$group) = @_;
11285:     $file_name = &declutter_portfile($file_name);
11286:     my $symb_crs = $what;
11287:     if (ref($what)) { $symb_crs=join('',@$what); }
11288:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
11289:     my ($tmp)=keys(%current_permissions);
11290:     if ($tmp=~/^error:/) { undef(%current_permissions); }
11291:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
11292:     foreach my $file (@readonly_files) {
11293: 	my $clean_file = &declutter_portfile($file);
11294: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
11295: 	my $current_locks = $current_permissions{$file};
11296:         my @new_locks;
11297:         my @del_keys;
11298:         if (ref($current_locks) eq "ARRAY"){
11299:             foreach my $locker (@{$current_locks}) {
11300:                 my $compare=$locker;
11301:                 if (ref($locker) eq 'ARRAY') {
11302:                     $compare=join('',@{$locker});
11303:                     if ($compare ne $symb_crs) {
11304:                         push(@new_locks, $locker);
11305:                     }
11306:                 }
11307:             }
11308:             if (scalar(@new_locks) > 0) {
11309:                 $current_permissions{$file} = \@new_locks;
11310:             } else {
11311:                 push(@del_keys, $file);
11312:                 &del('file_permissions',\@del_keys, $domain, $user);
11313:                 delete($current_permissions{$file});
11314:             }
11315:         }
11316:     }
11317:     &put('file_permissions',\%current_permissions,$domain,$user);
11318:     return;
11319: }
11320: 
11321: # ------------------------------------------------------------ Directory lister
11322: 
11323: sub dirlist {
11324:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
11325:     $uri=~s/^\///;
11326:     $uri=~s/\/$//;
11327:     my ($udom, $uname);
11328:     if ($getuserdir) {
11329:         $udom = $userdomain;
11330:         $uname = $username;
11331:     } else {
11332:         (undef,$udom,$uname)=split(/\//,$uri);
11333:         if(defined($userdomain)) {
11334:             $udom = $userdomain;
11335:         }
11336:         if(defined($username)) {
11337:             $uname = $username;
11338:         }
11339:     }
11340:     my ($dirRoot,$listing,@listing_results);
11341: 
11342:     $dirRoot = $perlvar{'lonDocRoot'};
11343:     if (defined($getpropath)) {
11344:         $dirRoot = &propath($udom,$uname);
11345:         $dirRoot =~ s/\/$//;
11346:     } elsif (defined($getuserdir)) {
11347:         my $subdir=$uname.'__';
11348:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
11349:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
11350:                    ."/$udom/$subdir/$uname";
11351:     } elsif (defined($alternateRoot)) {
11352:         $dirRoot = $alternateRoot;
11353:     }
11354: 
11355:     if($udom) {
11356:         if($uname) {
11357:             my $uhome = &homeserver($uname,$udom);
11358:             if ($uhome eq 'no_host') {
11359:                 return ([],'no_host');
11360:             }
11361:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
11362:                               .$getuserdir.':'.&escape($dirRoot)
11363:                               .':'.&escape($uname).':'.&escape($udom),$uhome);
11364:             if ($listing eq 'unknown_cmd') {
11365:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
11366:             } else {
11367:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
11368:             }
11369:             if ($listing eq 'unknown_cmd') {
11370:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
11371:                 @listing_results = split(/:/,$listing);
11372:             } else {
11373:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
11374:             }
11375:             if (($listing eq 'no_such_host') || ($listing eq 'con_lost') || 
11376:                 ($listing eq 'rejected') || ($listing eq 'refused') ||
11377:                 ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
11378:                 return ([],$listing);
11379:             } else {
11380:                 return (\@listing_results);
11381:             }
11382:         } elsif(!$alternateRoot) {
11383:             my (%allusers,%listerror);
11384: 	    my %servers = &get_servers($udom,'library');
11385:  	    foreach my $tryserver (keys(%servers)) {
11386:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
11387:                                   &escape($udom),$tryserver);
11388:                 if ($listing eq 'unknown_cmd') {
11389: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
11390: 				      $udom, $tryserver);
11391:                 } else {
11392:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
11393:                 }
11394: 		if ($listing eq 'unknown_cmd') {
11395: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
11396: 				      $udom, $tryserver);
11397: 		    @listing_results = split(/:/,$listing);
11398: 		} else {
11399: 		    @listing_results =
11400: 			map { &unescape($_); } split(/:/,$listing);
11401: 		}
11402:                 if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
11403:                     ($listing eq 'rejected') || ($listing eq 'refused') ||
11404:                     ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
11405:                     $listerror{$tryserver} = $listing;
11406:                 } else {
11407: 		    foreach my $line (@listing_results) {
11408: 			my ($entry) = split(/&/,$line,2);
11409: 			$allusers{$entry} = 1;
11410: 		    }
11411: 		}
11412:             }
11413:             my @alluserslist=();
11414:             foreach my $user (sort(keys(%allusers))) {
11415:                 push(@alluserslist,$user.'&user');
11416:             }
11417: 
11418:             if (!%listerror) {
11419:                 # no errors
11420:                 return (\@alluserslist);
11421:             } elsif (scalar(keys(%servers)) == 1) {
11422:                 # one library server, one error 
11423:                 my ($key) = keys(%listerror);
11424:                 return (\@alluserslist, $listerror{$key});
11425:             } elsif ( grep { $_ eq 'con_lost' } values(%listerror) ) {
11426:                 # con_lost indicates that we might miss data from at least one
11427:                 # library server
11428:                 return (\@alluserslist, 'con_lost');
11429:             } else {
11430:                 # multiple library servers and no con_lost -> data should be
11431:                 # complete. 
11432:                 return (\@alluserslist);
11433:             }
11434: 
11435:         } else {
11436:             return ([],'missing username');
11437:         }
11438:     } elsif(!defined($getpropath)) {
11439:         my $path = $perlvar{'lonDocRoot'}.'/res/'; 
11440:         my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
11441:         return (\@all_domains);
11442:     } else {
11443:         return ([],'missing domain');
11444:     }
11445: }
11446: 
11447: # --------------------------------------------- GetFileTimestamp
11448: # This function utilizes dirlist and returns the date stamp for
11449: # when it was last modified.  It will also return an error of -1
11450: # if an error occurs
11451: 
11452: sub GetFileTimestamp {
11453:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
11454:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
11455:     $studentName   = &LONCAPA::clean_username($studentName);
11456:     my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
11457:                                     undef,$getuserdir);
11458:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
11459:         return -1;
11460:     }
11461:     if (ref($fileref) eq 'ARRAY') {
11462:         my @stats = split('&',$fileref->[0]);
11463:         # @stats contains first the filename, then the stat output
11464:         return $stats[10]; # so this is 10 instead of 9.
11465:     } else {
11466:         return -1;
11467:     }
11468: }
11469: 
11470: sub stat_file {
11471:     my ($uri) = @_;
11472:     $uri = &clutter_with_no_wrapper($uri);
11473: 
11474:     my ($udom,$uname,$file);
11475:     if ($uri =~ m-^/(uploaded|editupload)/-) {
11476: 	($udom,$uname,$file) =
11477: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
11478: 	$file = 'userfiles/'.$file;
11479:     }
11480:     if ($uri =~ m-^/res/-) {
11481: 	($udom,$uname) = 
11482: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
11483: 	$file = $uri;
11484:     }
11485: 
11486:     if (!$udom || !$uname || !$file) {
11487: 	# unable to handle the uri
11488: 	return ();
11489:     }
11490:     my $getpropath;
11491:     if ($file =~ /^userfiles\//) {
11492:         $getpropath = 1;
11493:     }
11494:     my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
11495:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
11496:         return ();
11497:     } else {
11498:         if (ref($listref) eq 'ARRAY') {
11499:             my @stats = split('&',$listref->[0]);
11500: 	    shift(@stats); #filename is first
11501: 	    return @stats;
11502:         }
11503:     }
11504:     return ();
11505: }
11506: 
11507: # --------------------------------------------------------- recursedirs
11508: # Recursive function to traverse either a specific user's Authoring Space
11509: # or corresponding Published Resource Space, and populate the hash ref:
11510: # $dirhashref with URLs of all directories, and if $filehashref hash
11511: # ref arg is provided, the URLs of any files, excluding versioned, .meta,
11512: # or .rights files in resource space, and .meta, .save, .log, and .bak
11513: # files in Authoring Space.
11514: #
11515: # Inputs:
11516: #
11517: # $is_home - true if current server is home server for user's space
11518: # $context - either: priv, or res respectively for Authoring or Resource Space.
11519: # $docroot - Document root (i.e., /home/httpd/html
11520: # $toppath - Top level directory (i.e., /res/$dom/$uname or /priv/$dom/$uname
11521: # $relpath - Current path (relative to top level).
11522: # $dirhashref - reference to hash to populate with URLs of directories (Required)
11523: # $filehashref - reference to hash to populate with URLs of files (Optional)
11524: #
11525: # Returns: nothing
11526: #
11527: # Side Effects: populates $dirhashref, and $filehashref (if provided).
11528: #
11529: # Currently used by interface/londocs.pm to create linked select boxes for
11530: # directory and filename to import a Course "Author" resource into a course, and
11531: # also to create linked select boxes for Authoring Space and Directory to choose
11532: # save location for creation of a new "standard" problem from the Course Editor.
11533: #
11534: 
11535: sub recursedirs {
11536:     my ($is_home,$context,$docroot,$toppath,$relpath,$dirhashref,$filehashref) = @_;
11537:     return unless (ref($dirhashref) eq 'HASH');
11538:     my $currpath = $docroot.$toppath;
11539:     if ($relpath) {
11540:         $currpath .= "/$relpath";
11541:     }
11542:     my $savefile;
11543:     if (ref($filehashref)) {
11544:         $savefile = 1;
11545:     }
11546:     if ($is_home) {
11547:         if (opendir(my $dirh,$currpath)) {
11548:             foreach my $item (sort { lc($a) cmp lc($b) } grep(!/^\.+$/,readdir($dirh))) {
11549:                 next if ($item eq '');
11550:                 if (-d "$currpath/$item") {
11551:                     my $newpath;
11552:                     if ($relpath) {
11553:                         $newpath = "$relpath/$item";
11554:                     } else {
11555:                         $newpath = $item;
11556:                     }
11557:                     $dirhashref->{&Apache::lonlocal::js_escape($newpath)} = 1;
11558:                     &recursedirs($is_home,$context,$docroot,$toppath,$newpath,$dirhashref,$filehashref);
11559:                 } elsif ($savefile) {
11560:                     if ($context eq 'priv') {
11561:                         unless ($item =~ /\.(meta|save|log|bak|DS_Store)$/) {
11562:                             $filehashref->{&Apache::lonlocal::js_escape($relpath)}{$item} = 1;
11563:                         }
11564:                     } else {
11565:                         unless (($item =~ /\.meta$/) || ($item =~ /\.\d+\.\w+$/) || ($item =~ /\.rights$/)) {
11566:                             $filehashref->{&Apache::lonlocal::js_escape($relpath)}{$item} = 1;
11567:                         }
11568:                     }
11569:                 }
11570:             }
11571:             closedir($dirh);
11572:         }
11573:     } else {
11574:         my ($dirlistref,$listerror) =
11575:             &dirlist($toppath.$relpath);
11576:         my @dir_lines;
11577:         my $dirptr=16384;
11578:         if (ref($dirlistref) eq 'ARRAY') {
11579:             foreach my $dir_line (sort
11580:                               {
11581:                                   my ($afile)=split('&',$a,2);
11582:                                   my ($bfile)=split('&',$b,2);
11583:                                   return (lc($afile) cmp lc($bfile));
11584:                               } (@{$dirlistref})) {
11585:                 my ($item,$dom,undef,$testdir,undef,undef,undef,undef,$size,undef,$mtime,undef,undef,undef,$obs,undef) =
11586:                     split(/\&/,$dir_line,16);
11587:                 $item =~ s/\s+$//;
11588:                 next if (($item =~ /^\.\.?$/) || ($obs));
11589:                 if ($dirptr&$testdir) {
11590:                     my $newpath;
11591:                     if ($relpath) {
11592:                         $newpath = "$relpath/$item";
11593:                     } else {
11594:                         $relpath = '/';
11595:                         $newpath = $item;
11596:                     }
11597:                     $dirhashref->{&Apache::lonlocal::js_escape($newpath)} = 1;
11598:                     &recursedirs($is_home,$context,$docroot,$toppath,$newpath,$dirhashref,$filehashref);
11599:                 } elsif ($savefile) {
11600:                     if ($context eq 'priv') {
11601:                         unless ($item =~ /\.(meta|save|log|bak|DS_Store)$/) {
11602:                             $filehashref->{$relpath}{$item} = 1;
11603:                         }
11604:                     } else {
11605:                         unless (($item =~ /\.meta$/) || ($item =~ /\.\d+\.\w+$/)) {
11606:                             $filehashref->{$relpath}{$item} = 1;
11607:                         }
11608:                     }
11609:                 }
11610:             }
11611:         }
11612:     }
11613:     return;
11614: }
11615: 
11616: # -------------------------------------------------------- Value of a Condition
11617: 
11618: # gets the value of a specific preevaluated condition
11619: #    stored in the string  $env{user.state.<cid>}
11620: # or looks up a condition reference in the bighash and if if hasn't
11621: # already been evaluated recurses into docondval to get the value of
11622: # the condition, then memoizing it to 
11623: #   $env{user.state.<cid>.<condition>}
11624: sub directcondval {
11625:     my $number=shift;
11626:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
11627: 	&Apache::lonuserstate::evalstate();
11628:     }
11629:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
11630: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
11631:     } elsif ($number =~ /^_/) {
11632: 	my $sub_condition;
11633: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
11634: 		&GDBM_READER(),0640)) {
11635: 	    $sub_condition=$bighash{'conditions'.$number};
11636: 	    untie(%bighash);
11637: 	}
11638: 	my $value = &docondval($sub_condition);
11639: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
11640: 	return $value;
11641:     }
11642:     if ($env{'user.state.'.$env{'request.course.id'}}) {
11643:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
11644:     } else {
11645:        return 2;
11646:     }
11647: }
11648: 
11649: # get the collection of conditions for this resource
11650: sub condval {
11651:     my $condidx=shift;
11652:     my $allpathcond='';
11653:     foreach my $cond (split(/\|/,$condidx)) {
11654: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
11655: 	    $allpathcond.=
11656: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
11657: 	}
11658:     }
11659:     $allpathcond=~s/\|$//;
11660:     return &docondval($allpathcond);
11661: }
11662: 
11663: #evaluates an expression of conditions
11664: sub docondval {
11665:     my ($allpathcond) = @_;
11666:     my $result=0;
11667:     if ($env{'request.course.id'}
11668: 	&& defined($allpathcond)) {
11669: 	my $operand='|';
11670: 	my @stack;
11671: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
11672: 	    if ($chunk eq '(') {
11673: 		push @stack,($operand,$result);
11674: 	    } elsif ($chunk eq ')') {
11675: 		my $before=pop @stack;
11676: 		if (pop @stack eq '&') {
11677: 		    $result=$result>$before?$before:$result;
11678: 		} else {
11679: 		    $result=$result>$before?$result:$before;
11680: 		}
11681: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
11682: 		$operand=$chunk;
11683: 	    } else {
11684: 		my $new=directcondval($chunk);
11685: 		if ($operand eq '&') {
11686: 		    $result=$result>$new?$new:$result;
11687: 		} else {
11688: 		    $result=$result>$new?$result:$new;
11689: 		}
11690: 	    }
11691: 	}
11692:     }
11693:     return $result;
11694: }
11695: 
11696: # ---------------------------------------------------- Devalidate courseresdata
11697: 
11698: sub devalidatecourseresdata {
11699:     my ($coursenum,$coursedomain)=@_;
11700:     my $hashid=$coursenum.':'.$coursedomain;
11701:     &devalidate_cache_new('courseres',$hashid);
11702: }
11703: 
11704: 
11705: # --------------------------------------------------- Course Resourcedata Query
11706: #
11707: #  Parameters:
11708: #      $coursenum    - Number of the course.
11709: #      $coursedomain - Domain at which the course was created.
11710: #  Returns:
11711: #     A hash of the course parameters along (I think) with timestamps
11712: #     and version info.
11713: 
11714: sub get_courseresdata {
11715:     my ($coursenum,$coursedomain)=@_;
11716:     my $coursehom=&homeserver($coursenum,$coursedomain);
11717:     my $hashid=$coursenum.':'.$coursedomain;
11718:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
11719:     my %dumpreply;
11720:     unless (defined($cached)) {
11721: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
11722: 	$result=\%dumpreply;
11723: 	my ($tmp) = keys(%dumpreply);
11724: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
11725: 	    &do_cache_new('courseres',$hashid,$result,600);
11726: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
11727: 	    return $tmp;
11728: 	} elsif ($tmp =~ /^(error)/) {
11729: 	    $result=undef;
11730: 	    &do_cache_new('courseres',$hashid,$result,600);
11731: 	}
11732:     }
11733:     return $result;
11734: }
11735: 
11736: sub devalidateuserresdata {
11737:     my ($uname,$udom)=@_;
11738:     my $hashid="$udom:$uname";
11739:     &devalidate_cache_new('userres',$hashid);
11740: }
11741: 
11742: sub get_userresdata {
11743:     my ($uname,$udom)=@_;
11744:     #most student don\'t have any data set, check if there is some data
11745:     if (&EXT_cache_status($udom,$uname)) { return undef; }
11746: 
11747:     my $hashid="$udom:$uname";
11748:     my ($result,$cached)=&is_cached_new('userres',$hashid);
11749:     if (!defined($cached)) {
11750: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
11751: 	$result=\%resourcedata;
11752: 	&do_cache_new('userres',$hashid,$result,600);
11753:     }
11754:     my ($tmp)=keys(%$result);
11755:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
11756: 	return $result;
11757:     }
11758:     #error 2 occurs when the .db doesn't exist
11759:     if ($tmp!~/error: 2 /) {
11760:         if ((!defined($cached)) || ($tmp ne 'con_lost')) {
11761: 	    &logthis("<font color=\"blue\">WARNING:".
11762: 		     " Trying to get resource data for ".
11763: 		     $uname." at ".$udom.": ".
11764: 		     $tmp."</font>");
11765:         }
11766:     } elsif ($tmp=~/error: 2 /) {
11767: 	#&EXT_cache_set($udom,$uname);
11768: 	&do_cache_new('userres',$hashid,undef,600);
11769: 	undef($tmp); # not really an error so don't send it back
11770:     }
11771:     return $tmp;
11772: }
11773: #----------------------------------------------- resdata - return resource data
11774: #  Purpose:
11775: #    Return resource data for either users or for a course.
11776: #  Parameters:
11777: #     $name      - Course/user name.
11778: #     $domain    - Name of the domain the user/course is registered on.
11779: #     $type      - Type of thing $name is (must be 'course' or 'user')
11780: #     $mapp      - decluttered URL of enclosing map  
11781: #     $recursed  - Ref to scalar -- set to 1, if nested maps have been recursed.
11782: #     $recurseup - Ref to array of map URLs, starting with map containing
11783: #                  $mapp up through hierarchy of nested maps to top level map.  
11784: #     $courseid  - CourseID (first part of param identifier).
11785: #     $modifier  - Middle part of param identifier.
11786: #     $what      - Last part of param identifier.
11787: #     @which     - Array of names of resources desired.
11788: #  Returns:
11789: #     The value of the first reasource in @which that is found in the
11790: #     resource hash.
11791: #  Exceptional Conditions:
11792: #     If the $type passed in is not valid (not the string 'course' or 
11793: #     'user', an undefined  reference is returned.
11794: #     If none of the resources are found, an undef is returned
11795: sub resdata {
11796:     my ($name,$domain,$type,$mapp,$recursed,$recurseup,$courseid,
11797:         $modifier,$what,@which)=@_;
11798:     my $result;
11799:     if ($type eq 'course') {
11800: 	$result=&get_courseresdata($name,$domain);
11801:     } elsif ($type eq 'user') {
11802: 	$result=&get_userresdata($name,$domain);
11803:     }
11804:     if (!ref($result)) { return $result; }    
11805:     foreach my $item (@which) {
11806:         if ($item->[1] eq 'course') {
11807:             if ((ref($recurseup) eq 'ARRAY') && (ref($recursed) eq 'SCALAR')) {
11808:                 unless ($$recursed) {
11809:                     @{$recurseup} = &get_map_hierarchy($mapp,$courseid);
11810:                     $$recursed = 1;
11811:                 }
11812:                 foreach my $item (@${recurseup}) {
11813:                     my $norecursechk=$courseid.$modifier.$item.'___(all).'.$what;
11814:                     last if (defined($result->{$norecursechk}));
11815:                     my $recursechk=$courseid.$modifier.$item.'___(rec).'.$what;
11816:                     if (defined($result->{$recursechk})) { return [$result->{$recursechk},'map']; }
11817:                 }
11818:             }
11819:         }
11820:         if (defined($result->{$item->[0]})) {
11821: 	    return [$result->{$item->[0]},$item->[1]];
11822: 	}
11823:     }
11824:     return undef;
11825: }
11826: 
11827: sub get_domain_lti {
11828:     my ($cdom,$context) = @_;
11829:     my ($name,%lti);
11830:     if ($context eq 'consumer') {
11831:         $name = 'ltitools';
11832:     } elsif ($context eq 'provider') {
11833:         $name = 'lti';
11834:     } else {
11835:         return %lti;
11836:     }
11837:     my ($result,$cached)=&is_cached_new($name,$cdom);
11838:     if (defined($cached)) {
11839:         if (ref($result) eq 'HASH') {
11840:             %lti = %{$result};
11841:         }
11842:     } else {
11843:         my %domconfig = &get_dom('configuration',[$name],$cdom);
11844:         if (ref($domconfig{$name}) eq 'HASH') {
11845:             %lti = %{$domconfig{$name}};
11846:             my %encdomconfig = &get_dom('encconfig',[$name],$cdom);
11847:             if (ref($encdomconfig{$name}) eq 'HASH') {
11848:                 foreach my $id (keys(%lti)) {
11849:                     if (ref($encdomconfig{$name}{$id}) eq 'HASH') {
11850:                         foreach my $item ('key','secret') {
11851:                             $lti{$id}{$item} = $encdomconfig{$name}{$id}{$item};
11852:                         }
11853:                     }
11854:                 }
11855:             }
11856:         }
11857:         my $cachetime = 24*60*60;
11858:         &do_cache_new($name,$cdom,\%lti,$cachetime);
11859:     }
11860:     return %lti;
11861: }
11862: 
11863: sub get_numsuppfiles {
11864:     my ($cnum,$cdom,$ignorecache)=@_;
11865:     my $hashid=$cnum.':'.$cdom;
11866:     my ($suppcount,$cached);
11867:     unless ($ignorecache) {
11868:         ($suppcount,$cached) = &is_cached_new('suppcount',$hashid);
11869:     }
11870:     unless (defined($cached)) {
11871:         my $chome=&homeserver($cnum,$cdom);
11872:         unless ($chome eq 'no_host') {
11873:             ($suppcount,my $supptools,my $errors) = (0,0,0);
11874:             my $suppmap = 'supplemental.sequence';
11875:             ($suppcount,$supptools,$errors) =
11876:                 &Apache::loncommon::recurse_supplemental($cnum,$cdom,$suppmap,$suppcount,
11877:                                                          $supptools,$errors);
11878:         }
11879:         &do_cache_new('suppcount',$hashid,$suppcount,600);
11880:     }
11881:     return $suppcount;
11882: }
11883: 
11884: #
11885: # EXT resource caching routines
11886: #
11887: 
11888: {
11889: # Cache (5 seconds) of map hierarchy for speedup of navmaps display
11890: #
11891: # The course for which we cache
11892: my $cachedmapkey='';
11893: # The cached recursive maps for this course
11894: my %cachedmaps=();
11895: # When this was last done
11896: my $cachedmaptime='';
11897: 
11898: sub clear_EXT_cache_status {
11899:     &delenv('cache.EXT.');
11900: }
11901: 
11902: sub EXT_cache_status {
11903:     my ($target_domain,$target_user) = @_;
11904:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
11905:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
11906:         # We know already the user has no data
11907:         return 1;
11908:     } else {
11909:         return 0;
11910:     }
11911: }
11912: 
11913: sub EXT_cache_set {
11914:     my ($target_domain,$target_user) = @_;
11915:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
11916:     #&appenv({$cachename => time});
11917: }
11918: 
11919: # --------------------------------------------------------- Value of a Variable
11920: sub EXT {
11921: 
11922:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse,$cid)=@_;
11923:     unless ($varname) { return ''; }
11924:     #get real user name/domain, courseid and symb
11925:     my $courseid;
11926:     my $publicuser;
11927:     if ($symbparm) {
11928: 	$symbparm=&get_symb_from_alias($symbparm);
11929:     }
11930:     if (!($uname && $udom)) {
11931:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
11932:       if (!$symbparm) {	$symbparm=$cursymb; }
11933:     } else {
11934: 	$courseid=$env{'request.course.id'};
11935:     }
11936:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
11937:     my $rest;
11938:     if (defined($therest[0])) {
11939:        $rest=join('.',@therest);
11940:     } else {
11941:        $rest='';
11942:     }
11943: 
11944:     my $qualifierrest=$qualifier;
11945:     if ($rest) { $qualifierrest.='.'.$rest; }
11946:     my $spacequalifierrest=$space;
11947:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
11948:     if ($realm eq 'user') {
11949: # --------------------------------------------------------------- user.resource
11950: 	if ($space eq 'resource') {
11951: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
11952: 		  || defined($Apache::lonhomework::parsing_a_task))
11953: 		 &&
11954: 		 ($symbparm eq &symbread()) ) {	
11955: 		# if we are in the middle of processing the resource the
11956: 		# get the value we are planning on committing
11957:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
11958:                     return $Apache::lonhomework::results{$qualifierrest};
11959:                 } else {
11960:                     return $Apache::lonhomework::history{$qualifierrest};
11961:                 }
11962: 	    } else {
11963: 		my %restored;
11964: 		if ($publicuser || $env{'request.state'} eq 'construct') {
11965: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
11966: 		} else {
11967: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
11968: 		}
11969: 		return $restored{$qualifierrest};
11970: 	    }
11971: # ----------------------------------------------------------------- user.access
11972:         } elsif ($space eq 'access') {
11973: 	    # FIXME - not supporting calls for a specific user
11974:             return &allowed($qualifier,$rest);
11975: # ------------------------------------------ user.preferences, user.environment
11976:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
11977: 	    if (($uname eq $env{'user.name'}) &&
11978: 		($udom eq $env{'user.domain'})) {
11979: 		return $env{join('.',('environment',$qualifierrest))};
11980: 	    } else {
11981: 		my %returnhash;
11982: 		if (!$publicuser) {
11983: 		    %returnhash=&userenvironment($udom,$uname,
11984: 						 $qualifierrest);
11985: 		}
11986: 		return $returnhash{$qualifierrest};
11987: 	    }
11988: # ----------------------------------------------------------------- user.course
11989:         } elsif ($space eq 'course') {
11990: 	    # FIXME - not supporting calls for a specific user
11991:             return $env{join('.',('request.course',$qualifier))};
11992: # ------------------------------------------------------------------- user.role
11993:         } elsif ($space eq 'role') {
11994: 	    # FIXME - not supporting calls for a specific user
11995:             my ($role,$where)=split(/\./,$env{'request.role'});
11996:             if ($qualifier eq 'value') {
11997: 		return $role;
11998:             } elsif ($qualifier eq 'extent') {
11999:                 return $where;
12000:             }
12001: # ----------------------------------------------------------------- user.domain
12002:         } elsif ($space eq 'domain') {
12003:             return $udom;
12004: # ------------------------------------------------------------------- user.name
12005:         } elsif ($space eq 'name') {
12006:             return $uname;
12007: # ---------------------------------------------------- Any other user namespace
12008:         } else {
12009: 	    my %reply;
12010: 	    if (!$publicuser) {
12011: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
12012: 	    }
12013: 	    return $reply{$qualifierrest};
12014:         }
12015:     } elsif ($realm eq 'query') {
12016: # ---------------------------------------------- pull stuff out of query string
12017:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
12018: 						[$spacequalifierrest]);
12019: 	return $env{'form.'.$spacequalifierrest}; 
12020:    } elsif ($realm eq 'request') {
12021: # ------------------------------------------------------------- request.browser
12022:         if ($space eq 'browser') {
12023:             return $env{'browser.'.$qualifier};
12024: # ------------------------------------------------------------ request.filename
12025:         } else {
12026:             return $env{'request.'.$spacequalifierrest};
12027:         }
12028:     } elsif ($realm eq 'course') {
12029: # ---------------------------------------------------------- course.description
12030:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
12031:     } elsif ($realm eq 'resource') {
12032: 
12033: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
12034: 	    if (!$symbparm) { $symbparm=&symbread(); }
12035: 	}
12036: 
12037:         if ($qualifier eq '') {
12038: 	    if ($space eq 'title') {
12039: 	        if (!$symbparm) { $symbparm = $env{'request.filename'}; }
12040: 	        return &gettitle($symbparm);
12041: 	    }
12042: 	
12043: 	    if ($space eq 'map') {
12044: 	        my ($map) = &decode_symb($symbparm);
12045: 	        return &symbread($map);
12046: 	    }
12047:             if ($space eq 'maptitle') {
12048:                 my ($map) = &decode_symb($symbparm);
12049:                 return &gettitle($map);
12050:             }
12051: 	    if ($space eq 'filename') {
12052: 	        if ($symbparm) {
12053: 		    return &clutter((&decode_symb($symbparm))[2]);
12054: 	        }
12055: 	        return &hreflocation('',$env{'request.filename'});
12056: 	    }
12057: 
12058:             if ((defined($courseid)) && ($courseid eq $env{'request.course.id'}) && $symbparm) {
12059:                 if ($space eq 'visibleparts') {
12060:                     my $navmap = Apache::lonnavmaps::navmap->new();
12061:                     my $item;
12062:                     if (ref($navmap)) {
12063:                         my $res = $navmap->getBySymb($symbparm);
12064:                         my $parts = $res->parts();
12065:                         if (ref($parts) eq 'ARRAY') {
12066:                             $item = join(',',@{$parts});
12067:                         }
12068:                         undef($navmap);
12069:                     }
12070:                     return $item;
12071:                 }
12072:             }
12073:         }
12074: 
12075: 	my ($section, $group, @groups, @recurseup, $recursed);
12076: 	my ($courselevelm,$courseleveli,$courselevel,$mapp);
12077:         if (($courseid eq '') && ($cid)) {
12078:             $courseid = $cid;
12079:         }
12080: 	if (($symbparm && $courseid) && 
12081: 	    (($courseid eq $env{'request.course.id'}) || ($courseid eq $cid)))  {
12082: 
12083: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
12084: 
12085: # ----------------------------------------------------- Cascading lookup scheme
12086: 	    my $symbp=$symbparm;
12087: 	    $mapp=&deversion((&decode_symb($symbp))[0]);
12088: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
12089:             my $recurseparm=$mapp.'___(rec).'.$spacequalifierrest;
12090: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
12091: 	    if (($env{'user.name'} eq $uname) &&
12092: 		($env{'user.domain'} eq $udom)) {
12093: 		$section=$env{'request.course.sec'};
12094:                 @groups = split(/:/,$env{'request.course.groups'});  
12095:                 @groups=&sort_course_groups($courseid,@groups); 
12096: 	    } else {
12097: 		if (! defined($usection)) {
12098: 		    $section=&getsection($udom,$uname,$courseid);
12099: 		} else {
12100: 		    $section = $usection;
12101: 		}
12102:                 @groups = &get_users_groups($udom,$uname,$courseid);
12103: 	    }
12104: 
12105: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
12106: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
12107:             my $secleveli=$courseid.'.['.$section.'].'.$recurseparm;
12108: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
12109: 
12110: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
12111: 	    my $courselevelr=$courseid.'.'.$symbparm;
12112:             $courseleveli=$courseid.'.'.$recurseparm;
12113: 	    $courselevelm=$courseid.'.'.$mapparm;
12114: 
12115: # ----------------------------------------------------------- first, check user
12116: 
12117: 	    my $userreply=&resdata($uname,$udom,'user',$mapp,\$recursed,
12118:                                    \@recurseup,$courseid,'.',$spacequalifierrest, 
12119: 				       ([$courselevelr,'resource'],
12120: 					[$courselevelm,'map'     ],
12121:                                         [$courseleveli,'map'     ],
12122: 					[$courselevel, 'course'  ]));
12123: 	    if (defined($userreply)) { return &get_reply($userreply); }
12124: 
12125: # ------------------------------------------------ second, check some of course
12126:             my $coursereply;
12127:             if (@groups > 0) {
12128:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
12129:                                        $recurseparm,$mapparm,$spacequalifierrest,
12130:                                        $mapp,\$recursed,\@recurseup);
12131:                 if (defined($coursereply)) { return &get_reply($coursereply); } 
12132:             }
12133: 
12134: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
12135: 				  $env{'course.'.$courseid.'.domain'},
12136: 				  'course',$mapp,\$recursed,\@recurseup,
12137:                                   $courseid,'.['.$section.'].',$spacequalifierrest,
12138: 				  ([$seclevelr,   'resource'],
12139: 				   [$seclevelm,   'map'     ],
12140:                                    [$secleveli,   'map'     ],
12141: 				   [$seclevel,    'course'  ],
12142: 				   [$courselevelr,'resource']));
12143: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
12144: 
12145: # ------------------------------------------------------ third, check map parms
12146: 	    my %parmhash=();
12147: 	    my $thisparm='';
12148: 	    if (tie(%parmhash,'GDBM_File',
12149: 		    $env{'request.course.fn'}.'_parms.db',
12150: 		    &GDBM_READER(),0640)) {
12151: 		$thisparm=$parmhash{$symbparm};
12152: 		untie(%parmhash);
12153: 	    }
12154: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
12155: 	}
12156: # ------------------------------------------ fourth, look in resource metadata
12157:  
12158:         my $what = $spacequalifierrest;
12159: 	$what=~s/\./\_/;
12160: 	my $filename;
12161: 	if (!$symbparm) { $symbparm=&symbread(); }
12162: 	if ($symbparm) {
12163: 	    $filename=(&decode_symb($symbparm))[2];
12164: 	} else {
12165: 	    $filename=$env{'request.filename'};
12166: 	}
12167:         my $toolsymb;
12168:         if (($filename =~ /ext\.tool$/) && ($what ne '0_gradable')) {
12169:             $toolsymb = $symbparm;
12170:         }
12171: 	my $metadata=&metadata($filename,$what,$toolsymb);
12172: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
12173: 	$metadata=&metadata($filename,'parameter_'.$what,$toolsymb);
12174: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
12175: 
12176: # ----------------------------------------------- fifth, look in rest of course
12177: 	if ($symbparm && defined($courseid) && 
12178: 	    $courseid eq $env{'request.course.id'}) {
12179: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
12180: 				     $env{'course.'.$courseid.'.domain'},
12181: 				     'course',$mapp,\$recursed,\@recurseup,
12182:                                      $courseid,'.',$spacequalifierrest,
12183: 				     ([$courselevelm,'map'   ],
12184:                                       [$courseleveli,'map'   ],
12185: 				      [$courselevel, 'course']));
12186: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
12187: 	}
12188: # ------------------------------------------------------------------ Cascade up
12189: 	unless ($space eq '0') {
12190: 	    my @parts=split(/_/,$space);
12191: 	    my $id=pop(@parts);
12192: 	    my $part=join('_',@parts);
12193: 	    if ($part eq '') { $part='0'; }
12194: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
12195: 				 $symbparm,$udom,$uname,$section,1);
12196: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
12197: 	}
12198: 	if ($recurse) { return undef; }
12199: 	my $pack_def=&packages_tab_default($filename,$varname,$toolsymb);
12200: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
12201: # ---------------------------------------------------- Any other user namespace
12202:     } elsif ($realm eq 'environment') {
12203: # ----------------------------------------------------------------- environment
12204: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
12205: 	    return $env{'environment.'.$spacequalifierrest};
12206: 	} else {
12207: 	    if ($uname eq 'anonymous' && $udom eq '') {
12208: 		return '';
12209: 	    }
12210: 	    my %returnhash=&userenvironment($udom,$uname,
12211: 					    $spacequalifierrest);
12212: 	    return $returnhash{$spacequalifierrest};
12213: 	}
12214:     } elsif ($realm eq 'system') {
12215: # ----------------------------------------------------------------- system.time
12216: 	if ($space eq 'time') {
12217: 	    return time;
12218:         }
12219:     } elsif ($realm eq 'server') {
12220: # ----------------------------------------------------------------- system.time
12221: 	if ($space eq 'name') {
12222: 	    return $ENV{'SERVER_NAME'};
12223:         }
12224:     }
12225:     return '';
12226: }
12227: 
12228: sub get_reply {
12229:     my ($reply_value) = @_;
12230:     if (ref($reply_value) eq 'ARRAY') {
12231:         if (wantarray) {
12232: 	    return @$reply_value;
12233:         }
12234:         return $reply_value->[0];
12235:     } else {
12236:         return $reply_value;
12237:     }
12238: }
12239: 
12240: sub check_group_parms {
12241:     my ($courseid,$groups,$symbparm,$recurseparm,$mapparm,$what,$mapp,
12242:         $recursed,$recurseupref) = @_;
12243:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$recurseparm,'map'],
12244:                   [$what,'course']);
12245:     my $coursereply;
12246:     foreach my $group (@{$groups}) {
12247:         my @groupitems = ();
12248:         foreach my $level (@levels) {
12249:              my $item = $courseid.'.['.$group.'].'.$level->[0];
12250:              push(@groupitems,[$item,$level->[1]]);
12251:         }
12252:         my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
12253:                                    $env{'course.'.$courseid.'.domain'},
12254:                                    'course',$mapp,$recursed,$recurseupref,
12255:                                    $courseid,'.['.$group.'].',$what,
12256:                                    @groupitems);
12257:         last if (defined($coursereply));
12258:     }
12259:     return $coursereply;
12260: }
12261: 
12262: sub get_map_hierarchy {
12263:     my ($mapname,$courseid) = @_;
12264:     my @recurseup = ();
12265:     if ($mapname) {
12266:         if (($cachedmapkey eq $courseid) &&
12267:             (abs($cachedmaptime-time)<5)) {
12268:             if (ref($cachedmaps{$mapname}) eq 'ARRAY') {
12269:                 return @{$cachedmaps{$mapname}};
12270:             }
12271:         }
12272:         my $navmap = Apache::lonnavmaps::navmap->new();
12273:         if (ref($navmap)) {
12274:             @recurseup = $navmap->recurseup_maps($mapname);
12275:             undef($navmap);
12276:             $cachedmaps{$mapname} = \@recurseup;
12277:             $cachedmaptime=time;
12278:             $cachedmapkey=$courseid;
12279:         }
12280:     }
12281:     return @recurseup;
12282: }
12283: 
12284: }
12285: 
12286: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
12287:     my ($courseid,@groups) = @_;
12288:     @groups = sort(@groups);
12289:     return @groups;
12290: }
12291: 
12292: sub packages_tab_default {
12293:     my ($uri,$varname,$toolsymb)=@_;
12294:     my (undef,$part,$name)=split(/\./,$varname);
12295: 
12296:     my (@extension,@specifics,$do_default);
12297:     foreach my $package (split(/,/,&metadata($uri,'packages',$toolsymb))) {
12298: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
12299: 	if ($pack_type eq 'default') {
12300: 	    $do_default=1;
12301: 	} elsif ($pack_type eq 'extension') {
12302: 	    push(@extension,[$package,$pack_type,$pack_part]);
12303: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
12304: 	    # only look at packages defaults for packages that this id is
12305: 	    push(@specifics,[$package,$pack_type,$pack_part]);
12306: 	}
12307:     }
12308:     # first look for a package that matches the requested part id
12309:     foreach my $package (@specifics) {
12310: 	my (undef,$pack_type,$pack_part)=@{$package};
12311: 	next if ($pack_part ne $part);
12312: 	if (defined($packagetab{"$pack_type&$name&default"})) {
12313: 	    return $packagetab{"$pack_type&$name&default"};
12314: 	}
12315:     }
12316:     # look for any possible matching non extension_ package
12317:     foreach my $package (@specifics) {
12318: 	my (undef,$pack_type,$pack_part)=@{$package};
12319: 	if (defined($packagetab{"$pack_type&$name&default"})) {
12320: 	    return $packagetab{"$pack_type&$name&default"};
12321: 	}
12322: 	if ($pack_type eq 'part') { $pack_part='0'; }
12323: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
12324: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
12325: 	}
12326:     }
12327:     # look for any posible extension_ match
12328:     foreach my $package (@extension) {
12329: 	my ($package,$pack_type)=@{$package};
12330: 	if (defined($packagetab{"$pack_type&$name&default"})) {
12331: 	    return $packagetab{"$pack_type&$name&default"};
12332: 	}
12333: 	if (defined($packagetab{$package."&$name&default"})) {
12334: 	    return $packagetab{$package."&$name&default"};
12335: 	}
12336:     }
12337:     # look for a global default setting
12338:     if ($do_default && defined($packagetab{"default&$name&default"})) {
12339: 	return $packagetab{"default&$name&default"};
12340:     }
12341:     return undef;
12342: }
12343: 
12344: sub add_prefix_and_part {
12345:     my ($prefix,$part)=@_;
12346:     my $keyroot;
12347:     if (defined($prefix) && $prefix !~ /^__/) {
12348: 	# prefix that has a part already
12349: 	$keyroot=$prefix;
12350:     } elsif (defined($prefix)) {
12351: 	# prefix that is missing a part
12352: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
12353:     } else {
12354: 	# no prefix at all
12355: 	if (defined($part)) { $keyroot='_'.$part; }
12356:     }
12357:     return $keyroot;
12358: }
12359: 
12360: # ---------------------------------------------------------------- Get metadata
12361: 
12362: my %metaentry;
12363: my %importedpartids;
12364: my %importedrespids;
12365: sub metadata {
12366:     my ($uri,$what,$toolsymb,$liburi,$prefix,$depthcount)=@_;
12367:     $uri=&declutter($uri);
12368:     # if it is a non metadata possible uri return quickly
12369:     if (($uri eq '') || 
12370: 	(($uri =~ m|^/*adm/|) && 
12371: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard|ext\.tool)$})) ||
12372:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
12373: 	return undef;
12374:     }
12375:     if (($uri =~ /^priv/ || $uri=~m{^home/httpd/html/priv}) 
12376: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
12377: 	return undef;
12378:     }
12379:     my $filename=$uri;
12380:     $uri=~s/\.meta$//;
12381: #
12382: # Is the metadata already cached?
12383: # Look at timestamp of caching
12384: # Everything is cached by the main uri, libraries are never directly cached
12385: #
12386:     if (!defined($liburi)) {
12387: 	my ($result,$cached)=&is_cached_new('meta',$uri);
12388: 	if (defined($cached)) { return $result->{':'.$what}; }
12389:     }
12390: 
12391: #
12392: # If the uri is for an external tool the file from
12393: # which metadata should be retrieved depends on whether
12394: # the tool had been configured to be gradable (set in the Course
12395: # Editor or Resource Editor).
12396: #
12397: # If a valid symb has been included as the third arg in the call
12398: # to &metadata() that can be used to retrieve the value of
12399: # parameter_0_gradable set for the resource, and included in the
12400: # uploaded map containing the tool. The value is retrieved via
12401: # &EXT(), if a valid symb is available.  Otherwise the value of
12402: # gradable in the exttool_$marker.db file for the tool instance
12403: # is retrieved via &get().
12404: #
12405: # When lonuserstate::traceroute() calls lonnet::EXT() for 
12406: # hiddenresource and encrypturl (during course initialization)
12407: # the map-level parameter for resource.0.gradable included in the 
12408: # uploaded map containing the tool will not yet have been stored
12409: # in the user_course_parms.db file for the user's session, so in 
12410: # this case fall back to retrieving gradable status from the
12411: # exttool_$marker.db file.
12412: #
12413: # In order to avoid an infinite loop, &metadata() will return
12414: # before a call to &EXT(), if the uri is for an external tool
12415: # and the $what for which metadata is being requested is
12416: # parameter_0_gradable or 0_gradable.
12417: #
12418: 
12419:     if ($uri =~ /ext\.tool$/) {
12420:         if (($what eq 'parameter_0_gradable') || ($what eq '0_gradable')) {
12421:             return;
12422:         } else {
12423:             my ($checked,$use_passback);
12424:             if ($toolsymb ne '') {
12425:                 (undef,undef,my $tooluri) = &decode_symb($toolsymb);
12426:                 if (($tooluri eq $uri) && (&EXT('resource.0.gradable',$toolsymb))) {
12427:                     $checked = 1;
12428:                     if (&EXT('resource.0.gradable',$toolsymb) =~ /^yes$/i) {
12429:                         $use_passback = 1;
12430:                     }
12431:                 }
12432:             }
12433:             unless ($checked) {
12434:                 my ($ignore,$cdom,$cnum,$marker) = split(m{/},$uri);
12435:                 $marker=~s/\D//g;
12436:                 if ($marker) {
12437:                     my %toolsettings=&get('exttool_'.$marker,['gradable'],$cdom,$cnum);
12438:                     $use_passback = $toolsettings{'gradable'};
12439:                 }
12440:             }
12441:             if ($use_passback) {
12442:                 $filename = '/home/httpd/html/res/lib/templates/LTIpassback.tool';
12443:             } else {
12444:                 $filename = '/home/httpd/html/res/lib/templates/LTIstandard.tool';
12445:             }
12446:         }
12447:     }
12448: 
12449:     {
12450: # Imported parts would go here
12451:         my @origfiletagids=();
12452:         my $importedparts=0;
12453: 
12454: # Imported responseids would go here
12455:         my $importedresponses=0;
12456: #
12457: # Is this a recursive call for a library?
12458: #
12459: #	if (! exists($metacache{$uri})) {
12460: #	    $metacache{$uri}={};
12461: #	}
12462: 	my $cachetime = 60*60;
12463:         if ($liburi) {
12464: 	    $liburi=&declutter($liburi);
12465:             $filename=$liburi;
12466:         } else {
12467: 	    &devalidate_cache_new('meta',$uri);
12468: 	    undef(%metaentry);
12469: 	}
12470:         my %metathesekeys=();
12471:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
12472: 	my $metastring;
12473: 	if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
12474: 	    my $which = &hreflocation('','/'.($liburi || $uri));
12475: 	    $metastring = 
12476: 		&Apache::lonnet::ssi_body($which,
12477: 					  ('grade_target' => 'meta'));
12478: 	    $cachetime = 1; # only want this cached in the child not long term
12479: 	} elsif (($uri !~ m -^(editupload)/-) && 
12480:                  ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
12481: 	    my $file=&filelocation('',&clutter($filename));
12482: 	    #push(@{$metaentry{$uri.'.file'}},$file);
12483: 	    $metastring=&getfile($file);
12484: 	}
12485:         my $parser=HTML::LCParser->new(\$metastring);
12486:         my $token;
12487:         undef %metathesekeys;
12488:         while ($token=$parser->get_token) {
12489: 	    if ($token->[0] eq 'S') {
12490: 		if (defined($token->[2]->{'package'})) {
12491: #
12492: # This is a package - get package info
12493: #
12494: 		    my $package=$token->[2]->{'package'};
12495: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
12496: 		    if (defined($token->[2]->{'id'})) { 
12497: 			$keyroot.='_'.$token->[2]->{'id'}; 
12498: 		    }
12499: 		    if ($metaentry{':packages'}) {
12500: 			$metaentry{':packages'}.=','.$package.$keyroot;
12501: 		    } else {
12502: 			$metaentry{':packages'}=$package.$keyroot;
12503: 		    }
12504: 		    foreach my $pack_entry (keys(%packagetab)) {
12505: 			my $part=$keyroot;
12506: 			$part=~s/^\_//;
12507: 			if ($pack_entry=~/^\Q$package\E\&/ || 
12508: 			    $pack_entry=~/^\Q$package\E_0\&/) {
12509: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
12510: 			    # ignore package.tab specified default values
12511:                             # here &package_tab_default() will fetch those
12512: 			    if ($subp eq 'default') { next; }
12513: 			    my $value=$packagetab{$pack_entry};
12514: 			    my $unikey;
12515: 			    if ($pack =~ /_0$/) {
12516: 				$unikey='parameter_0_'.$name;
12517: 				$part=0;
12518: 			    } else {
12519: 				$unikey='parameter'.$keyroot.'_'.$name;
12520: 			    }
12521: 			    if ($subp eq 'display') {
12522: 				$value.=' [Part: '.$part.']';
12523: 			    }
12524: 			    $metaentry{':'.$unikey.'.part'}=$part;
12525: 			    $metathesekeys{$unikey}=1;
12526: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
12527: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
12528: 			    }
12529: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
12530: 				$metaentry{':'.$unikey}=
12531: 				    $metaentry{':'.$unikey.'.default'};
12532: 			    }
12533: 			}
12534: 		    }
12535: 		} else {
12536: #
12537: # This is not a package - some other kind of start tag
12538: #
12539: 		    my $entry=$token->[1];
12540: 		    my $unikey='';
12541: 
12542: 		    if ($entry eq 'import') {
12543: #
12544: # Importing a library here
12545: #
12546:                         my $location=$parser->get_text('/import');
12547:                         my $dir=$filename;
12548:                         $dir=~s|[^/]*$||;
12549:                         $location=&filelocation($dir,$location);
12550: 
12551:                         my $importid=$token->[2]->{'id'};
12552:                         my $importmode=$token->[2]->{'importmode'};
12553: #
12554: # Check metadata for imported file to
12555: # see if it contained response items
12556: #
12557:                         my ($origfile,@libfilekeys);
12558:                         my %currmetaentry = %metaentry;
12559:                         @libfilekeys = split(/,/,&metadata($location,'keys',undef,undef,undef,
12560:                                                            $depthcount+1));
12561:                         if (grep(/^responseorder$/,@libfilekeys)) {
12562:                             my $libresponseorder = &metadata($location,'responseorder',undef,undef,
12563:                                                              undef,$depthcount+1);
12564:                             if ($libresponseorder ne '') {
12565:                                 if ($#origfiletagids<0) {
12566:                                     undef(%importedrespids);
12567:                                     undef(%importedpartids);
12568:                                 }
12569:                                 my @respids = split(/\s*,\s*/,$libresponseorder);
12570:                                 if (@respids) {
12571:                                     $importedrespids{$importid} = join(',',map { $importid.'_'.$_ } @respids);
12572:                                 }
12573:                                 if ($importedrespids{$importid} ne '') {
12574:                                     $importedresponses = 1;
12575: # We need to get the original file and the imported file to get the response order correct
12576: # Load and inspect original file
12577:                                     if ($#origfiletagids<0) {
12578:                                         my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
12579:                                         $origfile=&getfile($origfilelocation);
12580:                                         @origfiletagids=($origfile=~/<((?:\w+)response|import|part)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
12581:                                     }
12582:                                 }
12583:                             }
12584:                         }
12585: # Do not overwrite contents of %metaentry hash for resource itself with 
12586: # hash populated for imported library file
12587:                         %metaentry = %currmetaentry;
12588:                         undef(%currmetaentry);
12589:                         if ($importmode eq 'part') {
12590: # Import as part(s)
12591:                            $importedparts=1;
12592: # We need to get the original file and the imported file to get the part order correct
12593: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
12594: # Load and inspect original file if we didn't do that already
12595:                            if ($#origfiletagids<0) {
12596:                                undef(%importedrespids);
12597:                                undef(%importedpartids);
12598:                                if ($origfile eq '') {
12599:                                    my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
12600:                                    $origfile=&getfile($origfilelocation);
12601:                                    @origfiletagids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
12602:                                }
12603:                            }
12604:                            my @impfilepartids;
12605: # If <partorder> tag is included in metadata for the imported file
12606: # get the parts in the imported file from that.
12607:                            if (grep(/^partorder$/,@libfilekeys)) {
12608:                                %currmetaentry = %metaentry;
12609:                                my $libpartorder = &metadata($location,'partorder',undef,undef,undef,
12610:                                                             $depthcount+1);
12611:                                %metaentry = %currmetaentry;
12612:                                undef(%currmetaentry);
12613:                                if ($libpartorder ne '') {
12614:                                    @impfilepartids=split(/\s*,\s*/,$libpartorder);
12615:                                }
12616:                            } else {
12617: # If no <partorder> tag available, load and inspect imported file
12618:                                my $impfile=&getfile($location);
12619:                                @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
12620:                            }
12621:                            if ($#impfilepartids>=0) {
12622: # This problem had parts
12623:                                $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
12624:                            } else {
12625: # Importing by turning a single problem into a problem part
12626: # It gets the import-tags ID as part-ID
12627:                                $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
12628:                                $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
12629:                            }
12630:                         } else {
12631: # Import as problem or as normal import
12632:                             $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
12633:                             unless ($importmode eq 'problem') {
12634: # Normal import
12635:                                 if (defined($token->[2]->{'id'})) {
12636:                                     $unikey.='_'.$token->[2]->{'id'};
12637:                                 }
12638:                             }
12639: # Check metadata for imported file to
12640: # see if it contained parts
12641:                             if (grep(/^partorder$/,@libfilekeys)) {
12642:                                 %currmetaentry = %metaentry;
12643:                                 my $libpartorder = &metadata($location,'partorder',undef,undef,undef,
12644:                                                              $depthcount+1);
12645:                                 %metaentry = %currmetaentry;
12646:                                 undef(%currmetaentry);
12647:                                 if ($libpartorder ne '') {
12648:                                     $importedparts = 1;
12649:                                     $importedpartids{$token->[2]->{'id'}}=$libpartorder;
12650:                                 }
12651:                             }
12652:                         }
12653: 			if ($depthcount<20) {
12654: 			    my $metadata = 
12655: 				&metadata($uri,'keys',$toolsymb,$location,$unikey,
12656: 					  $depthcount+1);
12657: 			    foreach my $meta (split(',',$metadata)) {
12658: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
12659: 				$metathesekeys{$meta}=1;
12660: 			    }
12661:                         }
12662: 		    } else {
12663: #
12664: # Not importing, some other kind of non-package, non-library start tag
12665: # 
12666:                         $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
12667:                         if (defined($token->[2]->{'id'})) {
12668:                             $unikey.='_'.$token->[2]->{'id'};
12669:                         }
12670: 			if (defined($token->[2]->{'name'})) { 
12671: 			    $unikey.='_'.$token->[2]->{'name'}; 
12672: 			}
12673: 			$metathesekeys{$unikey}=1;
12674: 			foreach my $param (@{$token->[3]}) {
12675: 			    $metaentry{':'.$unikey.'.'.$param} =
12676: 				$token->[2]->{$param};
12677: 			}
12678: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
12679: 			my $default=$metaentry{':'.$unikey.'.default'};
12680: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
12681: 		 # only ws inside the tag, and not in default, so use default
12682: 		 # as value
12683: 			    $metaentry{':'.$unikey}=$default;
12684: 			} elsif ( $internaltext =~ /\S/ ) {
12685: 		  # something interesting inside the tag
12686: 			    $metaentry{':'.$unikey}=$internaltext;
12687: 			} else {
12688: 		  # no interesting values, don't set a default
12689: 			}
12690: # end of not-a-package not-a-library import
12691: 		    }
12692: # end of not-a-package start tag
12693: 		}
12694: # the next is the end of "start tag"
12695: 	    }
12696: 	}
12697: 	my ($extension) = ($uri =~ /\.(\w+)$/);
12698: 	$extension = lc($extension);
12699: 	if ($extension eq 'htm') { $extension='html'; }
12700: 
12701: 	foreach my $key (keys(%packagetab)) {
12702: 	    #no specific packages #how's our extension
12703: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
12704: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
12705: 					 \%metathesekeys);
12706: 	}
12707: 
12708: 	if (!exists($metaentry{':packages'})
12709: 	    || $packagetab{"import_defaults&extension_$extension"}) {
12710: 	    foreach my $key (keys(%packagetab)) {
12711: 		#no specific packages well let's get default then
12712: 		if ($key!~/^default&/) { next; }
12713: 		&metadata_create_package_def($uri,$key,'default',
12714: 					     \%metathesekeys);
12715: 	    }
12716: 	}
12717: # are there custom rights to evaluate
12718: 	if ($metaentry{':copyright'} eq 'custom') {
12719: 
12720:     #
12721:     # Importing a rights file here
12722:     #
12723: 	    unless ($depthcount) {
12724: 		my $location=$metaentry{':customdistributionfile'};
12725: 		my $dir=$filename;
12726: 		$dir=~s|[^/]*$||;
12727: 		$location=&filelocation($dir,$location);
12728: 		my $rights_metadata =
12729: 		    &metadata($uri,'keys',$toolsymb,$location,'_rights',
12730: 			      $depthcount+1);
12731: 		foreach my $rights (split(',',$rights_metadata)) {
12732: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
12733: 		    $metathesekeys{$rights}=1;
12734: 		}
12735: 	    }
12736: 	}
12737: 	# uniqifiy package listing
12738: 	my %seen;
12739: 	my @uniq_packages =
12740: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
12741: 	$metaentry{':packages'} = join(',',@uniq_packages);
12742: 
12743:         if (($importedresponses) || ($importedparts)) {
12744:             if ($importedparts) {
12745: # We had imported parts and need to rebuild partorder
12746:                 $metaentry{':partorder'}='';
12747:                 $metathesekeys{'partorder'}=1;
12748:             }
12749:             if ($importedresponses) {
12750: # We had imported responses and need to rebuil responseorder
12751:                 $metaentry{':responseorder'}='';
12752:                 $metathesekeys{'responseorder'}=1;
12753:             }
12754:             for (my $index=0;$index<$#origfiletagids;$index+=2) {
12755:                 my $origid = $origfiletagids[$index+1];
12756:                 if ($origfiletagids[$index] eq 'part') {
12757: # Original part, part of the problem
12758:                     if ($importedparts) {
12759:                         $metaentry{':partorder'}.=','.$origid;
12760:                     }
12761:                 } elsif ($origfiletagids[$index] eq 'import') {
12762:                     if ($importedparts) {
12763: # We have imported parts at this position
12764:                         if ($importedpartids{$origid} ne '') {
12765:                             $metaentry{':partorder'}.=','.$importedpartids{$origid};
12766:                         }
12767:                     }
12768:                     if ($importedresponses) {
12769: # We have imported responses at this position
12770:                         if ($importedrespids{$origid} ne '') {
12771:                             $metaentry{':responseorder'}.=','.$importedrespids{$origid};
12772:                         }
12773:                     }
12774:                 } else {
12775: # Original response item, part of the problem
12776:                     if ($importedresponses) {
12777:                         $metaentry{':responseorder'}.=','.$origid;
12778:                     }
12779:                 }
12780:             }
12781:             if ($importedparts) {
12782:                 $metaentry{':partorder'}=~s/^\,//;
12783:             }
12784:             if ($importedresponses) {
12785:                 $metaentry{':responseorder'}=~s/^\,//;
12786:             }
12787:         }
12788: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
12789: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
12790: 	$metaentry{':allpossiblekeys'}=join(',',keys(%metathesekeys));
12791:         unless ($liburi) {
12792: 	    &do_cache_new('meta',$uri,\%metaentry,$cachetime);
12793:         }
12794: # this is the end of "was not already recently cached
12795:     }
12796:     return $metaentry{':'.$what};
12797: }
12798: 
12799: sub metadata_create_package_def {
12800:     my ($uri,$key,$package,$metathesekeys)=@_;
12801:     my ($pack,$name,$subp)=split(/\&/,$key);
12802:     if ($subp eq 'default') { next; }
12803:     
12804:     if (defined($metaentry{':packages'})) {
12805: 	$metaentry{':packages'}.=','.$package;
12806:     } else {
12807: 	$metaentry{':packages'}=$package;
12808:     }
12809:     my $value=$packagetab{$key};
12810:     my $unikey;
12811:     $unikey='parameter_0_'.$name;
12812:     $metaentry{':'.$unikey.'.part'}=0;
12813:     $$metathesekeys{$unikey}=1;
12814:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
12815: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
12816:     }
12817:     if (defined($metaentry{':'.$unikey.'.default'})) {
12818: 	$metaentry{':'.$unikey}=
12819: 	    $metaentry{':'.$unikey.'.default'};
12820:     }
12821: }
12822: 
12823: sub metadata_generate_part0 {
12824:     my ($metadata,$metacache,$uri) = @_;
12825:     my %allnames;
12826:     foreach my $metakey (keys(%$metadata)) {
12827: 	if ($metakey=~/^parameter\_(.*)/) {
12828: 	  my $part=$$metacache{':'.$metakey.'.part'};
12829: 	  my $name=$$metacache{':'.$metakey.'.name'};
12830: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
12831: 	    $allnames{$name}=$part;
12832: 	  }
12833: 	}
12834:     }
12835:     foreach my $name (keys(%allnames)) {
12836:       $$metadata{"parameter_0_$name"}=1;
12837:       my $key=":parameter_0_$name";
12838:       $$metacache{"$key.part"}='0';
12839:       $$metacache{"$key.name"}=$name;
12840:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
12841: 					   $allnames{$name}.'_'.$name.
12842: 					   '.type'};
12843:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
12844: 			     '.display'};
12845:       my $expr='[Part: '.$allnames{$name}.']';
12846:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
12847:       $$metacache{"$key.display"}=$olddis;
12848:     }
12849: }
12850: 
12851: # ------------------------------------------------------ Devalidate title cache
12852: 
12853: sub devalidate_title_cache {
12854:     my ($url)=@_;
12855:     if (!$env{'request.course.id'}) { return; }
12856:     my $symb=&symbread($url);
12857:     if (!$symb) { return; }
12858:     my $key=$env{'request.course.id'}."\0".$symb;
12859:     &devalidate_cache_new('title',$key);
12860: }
12861: 
12862: # ------------------------------------------------- Get the title of a course
12863: 
12864: sub current_course_title {
12865:     return $env{ 'course.' . $env{'request.course.id'} . '.description' };
12866: }
12867: # ------------------------------------------------- Get the title of a resource
12868: 
12869: sub gettitle {
12870:     my $urlsymb=shift;
12871:     my $symb=&symbread($urlsymb);
12872:     if ($symb) {
12873: 	my $key=$env{'request.course.id'}."\0".$symb;
12874: 	my ($result,$cached)=&is_cached_new('title',$key);
12875: 	if (defined($cached)) { 
12876: 	    return $result;
12877: 	}
12878: 	my ($map,$resid,$url)=&decode_symb($symb);
12879: 	my $title='';
12880: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
12881: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
12882: 	} else {
12883: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
12884: 		    &GDBM_READER(),0640)) {
12885: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
12886: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
12887: 		untie(%bighash);
12888: 	    }
12889: 	}
12890: 	$title=~s/\&colon\;/\:/gs;
12891: 	if ($title) {
12892: # Remember both $symb and $title for dynamic metadata
12893:             $accesshash{$symb.'___crstitle'}=$title;
12894:             $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
12895: # Cache this title and then return it
12896: 	    return &do_cache_new('title',$key,$title,600);
12897: 	}
12898: 	$urlsymb=$url;
12899:     }
12900:     my $title=&metadata($urlsymb,'title');
12901:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
12902:     return $title;
12903: }
12904: 
12905: sub get_slot {
12906:     my ($which,$cnum,$cdom)=@_;
12907:     if (!$cnum || !$cdom) {
12908: 	(undef,my $courseid)=&whichuser();
12909: 	$cdom=$env{'course.'.$courseid.'.domain'};
12910: 	$cnum=$env{'course.'.$courseid.'.num'};
12911:     }
12912:     my $key=join("\0",'slots',$cdom,$cnum,$which);
12913:     my %slotinfo;
12914:     if (exists($remembered{$key})) {
12915: 	$slotinfo{$which} = $remembered{$key};
12916:     } else {
12917: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
12918: 	&Apache::lonhomework::showhash(%slotinfo);
12919: 	my ($tmp)=keys(%slotinfo);
12920: 	if ($tmp=~/^error:/) { return (); }
12921: 	$remembered{$key} = $slotinfo{$which};
12922:     }
12923:     if (ref($slotinfo{$which}) eq 'HASH') {
12924: 	return %{$slotinfo{$which}};
12925:     }
12926:     return $slotinfo{$which};
12927: }
12928: 
12929: sub get_reservable_slots {
12930:     my ($cnum,$cdom,$uname,$udom) = @_;
12931:     my $now = time;
12932:     my $reservable_info;
12933:     my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
12934:     if (exists($remembered{$key})) {
12935:         $reservable_info = $remembered{$key};
12936:     } else {
12937:         my %resv;
12938:         ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
12939:         &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
12940:         $reservable_info = \%resv;
12941:         $remembered{$key} = $reservable_info;
12942:     }
12943:     return $reservable_info;
12944: }
12945: 
12946: sub get_course_slots {
12947:     my ($cnum,$cdom) = @_;
12948:     my $hashid=$cnum.':'.$cdom;
12949:     my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
12950:     if (defined($cached)) {
12951:         if (ref($result) eq 'HASH') {
12952:             return %{$result};
12953:         }
12954:     } else {
12955:         my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
12956:         my ($tmp) = keys(%slots);
12957:         if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
12958:             &do_cache_new('allslots',$hashid,\%slots,600);
12959:             return %slots;
12960:         }
12961:     }
12962:     return;
12963: }
12964: 
12965: sub devalidate_slots_cache {
12966:     my ($cnum,$cdom)=@_;
12967:     my $hashid=$cnum.':'.$cdom;
12968:     &devalidate_cache_new('allslots',$hashid);
12969: }
12970: 
12971: sub get_coursechange {
12972:     my ($cdom,$cnum) = @_;
12973:     if ($cdom eq '' || $cnum eq '') {
12974:         return unless ($env{'request.course.id'});
12975:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
12976:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
12977:     }
12978:     my $hashid=$cdom.'_'.$cnum;
12979:     my ($change,$cached)=&is_cached_new('crschange',$hashid);
12980:     if ((defined($cached)) && ($change ne '')) {
12981:         return $change;
12982:     } else {
12983:         my %crshash;
12984:         %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
12985:         if ($crshash{'internal.contentchange'} eq '') {
12986:             $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
12987:             if ($change eq '') {
12988:                 %crshash = &get('environment',['internal.created'],$cdom,$cnum);
12989:                 $change = $crshash{'internal.created'};
12990:             }
12991:         } else {
12992:             $change = $crshash{'internal.contentchange'};
12993:         }
12994:         my $cachetime = 600;
12995:         &do_cache_new('crschange',$hashid,$change,$cachetime);
12996:     }
12997:     return $change;
12998: }
12999: 
13000: sub devalidate_coursechange_cache {
13001:     my ($cnum,$cdom)=@_;
13002:     my $hashid=$cnum.':'.$cdom;
13003:     &devalidate_cache_new('crschange',$hashid);
13004: }
13005: 
13006: # ------------------------------------------------- Update symbolic store links
13007: 
13008: sub symblist {
13009:     my ($mapname,%newhash)=@_;
13010:     $mapname=&deversion(&declutter($mapname));
13011:     my %hash;
13012:     if (($env{'request.course.fn'}) && (%newhash)) {
13013:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
13014:                       &GDBM_WRCREAT(),0640)) {
13015: 	    foreach my $url (keys(%newhash)) {
13016: 		next if ($url eq 'last_known'
13017: 			 && $env{'form.no_update_last_known'});
13018: 		$hash{declutter($url)}=&encode_symb($mapname,
13019: 						    $newhash{$url}->[1],
13020: 						    $newhash{$url}->[0]);
13021:             }
13022:             if (untie(%hash)) {
13023: 		return 'ok';
13024:             }
13025:         }
13026:     }
13027:     return 'error';
13028: }
13029: 
13030: # --------------------------------------------------------------- Verify a symb
13031: 
13032: sub symbverify {
13033:     my ($symb,$thisurl,$encstate)=@_;
13034:     my $thisfn=$thisurl;
13035:     $thisfn=&declutter($thisfn);
13036: # direct jump to resource in page or to a sequence - will construct own symbs
13037:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
13038: # check URL part
13039:     my ($map,$resid,$url)=&decode_symb($symb);
13040: 
13041:     unless ($url eq $thisfn) { return 0; }
13042: 
13043:     $symb=&symbclean($symb);
13044:     $thisurl=&deversion($thisurl);
13045:     $thisfn=&deversion($thisfn);
13046: 
13047:     my %bighash;
13048:     my $okay=0;
13049: 
13050:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
13051:                             &GDBM_READER(),0640)) {
13052:         my $noclutter;
13053:         if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
13054:             $thisurl =~ s/\?.+$//;
13055:             if ($map =~ m{^uploaded/.+\.page$}) {
13056:                 $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
13057:                 $thisurl =~ s{^\Qhttp://https://\E}{https://};
13058:                 $noclutter = 1;
13059:             }
13060:         }
13061:         my $ids;
13062:         if ($noclutter) {
13063:             $ids=$bighash{'ids_'.$thisurl};
13064:         } else {
13065:             $ids=$bighash{'ids_'.&clutter($thisurl)};
13066:         }
13067:         unless ($ids) {
13068:             my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;  
13069:             $ids=$bighash{$idkey};
13070:         }
13071:         if ($ids) {
13072: # ------------------------------------------------------------------- Has ID(s)
13073:             if ($thisfn =~ m{^/adm/wrapper/ext/}) {
13074:                 $symb =~ s/\?.+$//;
13075:             }
13076: 	    foreach my $id (split(/\,/,$ids)) {
13077: 	       my ($mapid,$resid)=split(/\./,$id);
13078:                if (
13079:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
13080:    eq $symb) {
13081:                    if (ref($encstate)) {
13082:                        $$encstate = $bighash{'encrypted_'.$id};
13083:                    }
13084: 		   if (($env{'request.role.adv'}) ||
13085: 		       ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
13086:                        ($thisurl eq '/adm/navmaps')) {
13087: 		       $okay=1;
13088:                        last;
13089: 		   }
13090: 	       }
13091: 	   }
13092:         }
13093: 	untie(%bighash);
13094:     }
13095:     return $okay;
13096: }
13097: 
13098: # --------------------------------------------------------------- Clean-up symb
13099: 
13100: sub symbclean {
13101:     my $symb=shift;
13102:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
13103: # remove version from map
13104:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
13105: 
13106: # remove version from URL
13107:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
13108: 
13109: # remove wrapper
13110: 
13111:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
13112:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
13113:     return $symb;
13114: }
13115: 
13116: # ---------------------------------------------- Split symb to find map and url
13117: 
13118: sub encode_symb {
13119:     my ($map,$resid,$url)=@_;
13120:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
13121: }
13122: 
13123: sub decode_symb {
13124:     my $symb=shift;
13125:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
13126:     my ($map,$resid,$url)=split(/___/,$symb);
13127:     return (&fixversion($map),$resid,&fixversion($url));
13128: }
13129: 
13130: sub fixversion {
13131:     my $fn=shift;
13132:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
13133:     my %bighash;
13134:     my $uri=&clutter($fn);
13135:     my $key=$env{'request.course.id'}.'_'.$uri;
13136: # is this cached?
13137:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
13138:     if (defined($cached)) { return $result; }
13139: # unfortunately not cached, or expired
13140:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
13141: 	    &GDBM_READER(),0640)) {
13142:  	if ($bighash{'version_'.$uri}) {
13143:  	    my $version=$bighash{'version_'.$uri};
13144:  	    unless (($version eq 'mostrecent') || 
13145: 		    ($version==&getversion($uri))) {
13146:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
13147:  	    }
13148:  	}
13149:  	untie %bighash;
13150:     }
13151:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
13152: }
13153: 
13154: sub deversion {
13155:     my $url=shift;
13156:     $url=~s/\.\d+\.(\w+)$/\.$1/;
13157:     return $url;
13158: }
13159: 
13160: # ------------------------------------------------------ Return symb list entry
13161: 
13162: sub symbread {
13163:     my ($thisfn,$donotrecurse,$ignorecachednull,$checkforblock,$possibles)=@_;
13164:     my $cache_str='request.symbread.cached.'.$thisfn;
13165:     if (defined($env{$cache_str})) {
13166:         if ($ignorecachednull) {
13167:             return $env{$cache_str} unless ($env{$cache_str} eq '');
13168:         } else {
13169:             return $env{$cache_str};
13170:         }
13171:     }
13172: # no filename provided? try from environment
13173:     unless ($thisfn) {
13174:         if ($env{'request.symb'}) {
13175: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
13176: 	}
13177: 	$thisfn=$env{'request.filename'};
13178:     }
13179:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
13180: # is that filename actually a symb? Verify, clean, and return
13181:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
13182: 	if (&symbverify($thisfn,$1)) {
13183: 	    return $env{$cache_str}=&symbclean($thisfn);
13184: 	}
13185:     }
13186:     $thisfn=declutter($thisfn);
13187:     my %hash;
13188:     my %bighash;
13189:     my $syval='';
13190:     if (($env{'request.course.fn'}) && ($thisfn)) {
13191:         my $targetfn = $thisfn;
13192:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
13193:             $targetfn = 'adm/wrapper/'.$thisfn;
13194:         }
13195: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
13196: 	    $targetfn=$1;
13197: 	}
13198:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
13199:                       &GDBM_READER(),0640)) {
13200: 	    $syval=$hash{$targetfn};
13201:             untie(%hash);
13202:         }
13203: # ---------------------------------------------------------- There was an entry
13204:         if ($syval) {
13205: 	    #unless ($syval=~/\_\d+$/) {
13206: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
13207: 		    #&appenv({'request.ambiguous' => $thisfn});
13208: 		    #return $env{$cache_str}='';
13209: 		#}    
13210: 		#$syval.=$1;
13211: 	    #}
13212:         } else {
13213: # ------------------------------------------------------- Was not in symb table
13214:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
13215:                             &GDBM_READER(),0640)) {
13216: # ---------------------------------------------- Get ID(s) for current resource
13217:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
13218:               unless ($ids) { 
13219:                  $ids=$bighash{'ids_/'.$thisfn};
13220:               }
13221:               unless ($ids) {
13222: # alias?
13223: 		  $ids=$bighash{'mapalias_'.$thisfn};
13224:               }
13225:               if ($ids) {
13226: # ------------------------------------------------------------------- Has ID(s)
13227:                  my @possibilities=split(/\,/,$ids);
13228:                  if ($#possibilities==0) {
13229: # ----------------------------------------------- There is only one possibility
13230: 		     my ($mapid,$resid)=split(/\./,$ids);
13231: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
13232: 						    $resid,$thisfn);
13233:                      if (ref($possibles) eq 'HASH') {
13234:                          $possibles->{$syval} = 1;    
13235:                      }
13236:                      if ($checkforblock) {
13237:                          my @blockers = &has_comm_blocking('bre',$syval,$bighash{'src_'.$ids});
13238:                          if (@blockers) {
13239:                              $syval = '';
13240:                              return;
13241:                          }
13242:                      }
13243:                  } elsif ((!$donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) { 
13244: # ------------------------------------------ There is more than one possibility
13245:                      my $realpossible=0;
13246:                      foreach my $id (@possibilities) {
13247: 			 my $file=$bighash{'src_'.$id};
13248:                          my $canaccess;
13249:                          if (($donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
13250:                              $canaccess = 1;
13251:                          } else { 
13252:                              $canaccess = &allowed('bre',$file);
13253:                          }
13254:                          if ($canaccess) {
13255:          		     my ($mapid,$resid)=split(/\./,$id);
13256:                              if ($bighash{'map_type_'.$mapid} ne 'page') {
13257:                                  my $poss_syval=&encode_symb($bighash{'map_id_'.$mapid},
13258: 						             $resid,$thisfn);
13259:                                  if (ref($possibles) eq 'HASH') {
13260:                                      $possibles->{$syval} = 1;
13261:                                  }
13262:                                  if ($checkforblock) {
13263:                                      my @blockers = &has_comm_blocking('bre',$poss_syval,$file);
13264:                                      unless (@blockers > 0) {
13265:                                          $syval = $poss_syval;
13266:                                          $realpossible++;
13267:                                      }
13268:                                  } else {
13269:                                      $syval = $poss_syval;
13270:                                      $realpossible++;
13271:                                  }
13272:                              }
13273: 			 }
13274:                      }
13275: 		     if ($realpossible!=1) { $syval=''; }
13276:                  } else {
13277:                      $syval='';
13278:                  }
13279: 	      }
13280:               untie(%bighash);
13281:            }
13282:         }
13283:         if ($syval) {
13284: 	    return $env{$cache_str}=$syval;
13285:         }
13286:     }
13287:     &appenv({'request.ambiguous' => $thisfn});
13288:     return $env{$cache_str}='';
13289: }
13290: 
13291: # ---------------------------------------------------------- Return random seed
13292: 
13293: sub numval {
13294:     my $txt=shift;
13295:     $txt=~tr/A-J/0-9/;
13296:     $txt=~tr/a-j/0-9/;
13297:     $txt=~tr/K-T/0-9/;
13298:     $txt=~tr/k-t/0-9/;
13299:     $txt=~tr/U-Z/0-5/;
13300:     $txt=~tr/u-z/0-5/;
13301:     $txt=~s/\D//g;
13302:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
13303:     return int($txt);
13304: }
13305: 
13306: sub numval2 {
13307:     my $txt=shift;
13308:     $txt=~tr/A-J/0-9/;
13309:     $txt=~tr/a-j/0-9/;
13310:     $txt=~tr/K-T/0-9/;
13311:     $txt=~tr/k-t/0-9/;
13312:     $txt=~tr/U-Z/0-5/;
13313:     $txt=~tr/u-z/0-5/;
13314:     $txt=~s/\D//g;
13315:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
13316:     my $total;
13317:     foreach my $val (@txts) { $total+=$val; }
13318:     if ($_64bit) { if ($total > 2**32) { return -1; } }
13319:     return int($total);
13320: }
13321: 
13322: sub numval3 {
13323:     use integer;
13324:     my $txt=shift;
13325:     $txt=~tr/A-J/0-9/;
13326:     $txt=~tr/a-j/0-9/;
13327:     $txt=~tr/K-T/0-9/;
13328:     $txt=~tr/k-t/0-9/;
13329:     $txt=~tr/U-Z/0-5/;
13330:     $txt=~tr/u-z/0-5/;
13331:     $txt=~s/\D//g;
13332:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
13333:     my $total;
13334:     foreach my $val (@txts) { $total+=$val; }
13335:     if ($_64bit) { $total=(($total<<32)>>32); }
13336:     return $total;
13337: }
13338: 
13339: sub digest {
13340:     my ($data)=@_;
13341:     my $digest=&Digest::MD5::md5($data);
13342:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
13343:     my ($e,$f);
13344:     {
13345:         use integer;
13346:         $e=($a+$b);
13347:         $f=($c+$d);
13348:         if ($_64bit) {
13349:             $e=(($e<<32)>>32);
13350:             $f=(($f<<32)>>32);
13351:         }
13352:     }
13353:     if (wantarray) {
13354: 	return ($e,$f);
13355:     } else {
13356: 	my $g;
13357: 	{
13358: 	    use integer;
13359: 	    $g=($e+$f);
13360: 	    if ($_64bit) {
13361: 		$g=(($g<<32)>>32);
13362: 	    }
13363: 	}
13364: 	return $g;
13365:     }
13366: }
13367: 
13368: sub latest_rnd_algorithm_id {
13369:     return '64bit5';
13370: }
13371: 
13372: sub get_rand_alg {
13373:     my ($courseid)=@_;
13374:     if (!$courseid) { $courseid=(&whichuser())[1]; }
13375:     if ($courseid) {
13376: 	return $env{"course.$courseid.rndseed"};
13377:     }
13378:     return &latest_rnd_algorithm_id();
13379: }
13380: 
13381: sub validCODE {
13382:     my ($CODE)=@_;
13383:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
13384:     return 0;
13385: }
13386: 
13387: sub getCODE {
13388:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
13389:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
13390: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
13391: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
13392: 	return $Apache::lonhomework::history{'resource.CODE'};
13393:     }
13394:     return undef;
13395: }
13396: #
13397: #  Determines the random seed for a specific context:
13398: #
13399: # parameters:
13400: #   symb      - in course context the symb for the seed.
13401: #   course_id - The course id of the form domain_coursenum.
13402: #   domain    - Domain for the user.
13403: #   course    - Course for the user.
13404: #   cenv      - environment of the course.
13405: #
13406: # NOTE:
13407: #   All parameters are picked out of the environment if missing
13408: #   or not defined.
13409: #   If a symb cannot be determined the current time is used instead.
13410: #
13411: #  For a given well defined symb, courside, domain, username,
13412: #  and course environment, the seed is reproducible.
13413: #
13414: sub rndseed {
13415:     my ($symb,$courseid,$domain,$username, $cenv)=@_;
13416:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
13417:     if (!defined($symb)) {
13418: 	unless ($symb=$wsymb) { return time; }
13419:     }
13420:     if (!defined $courseid) { 
13421: 	$courseid=$wcourseid; 
13422:     }
13423:     if (!defined $domain) { $domain=$wdomain; }
13424:     if (!defined $username) { $username=$wusername }
13425: 
13426:     my $which;
13427:     if (defined($cenv->{'rndseed'})) {
13428: 	$which = $cenv->{'rndseed'};
13429:     } else {
13430: 	$which =&get_rand_alg($courseid);
13431:     }
13432:     if (defined(&getCODE())) {
13433: 
13434: 	if ($which eq '64bit5') {
13435: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
13436: 	} elsif ($which eq '64bit4') {
13437: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
13438: 	} else {
13439: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
13440: 	}
13441:     } elsif ($which eq '64bit5') {
13442: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
13443:     } elsif ($which eq '64bit4') {
13444: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
13445:     } elsif ($which eq '64bit3') {
13446: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
13447:     } elsif ($which eq '64bit2') {
13448: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
13449:     } elsif ($which eq '64bit') {
13450: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
13451:     }
13452:     return &rndseed_32bit($symb,$courseid,$domain,$username);
13453: }
13454: 
13455: sub rndseed_32bit {
13456:     my ($symb,$courseid,$domain,$username)=@_;
13457:     {
13458: 	use integer;
13459: 	my $symbchck=unpack("%32C*",$symb) << 27;
13460: 	my $symbseed=numval($symb) << 22;
13461: 	my $namechck=unpack("%32C*",$username) << 17;
13462: 	my $nameseed=numval($username) << 12;
13463: 	my $domainseed=unpack("%32C*",$domain) << 7;
13464: 	my $courseseed=unpack("%32C*",$courseid);
13465: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
13466: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
13467: 	#&logthis("rndseed :$num:$symb");
13468: 	if ($_64bit) { $num=(($num<<32)>>32); }
13469: 	return $num;
13470:     }
13471: }
13472: 
13473: sub rndseed_64bit {
13474:     my ($symb,$courseid,$domain,$username)=@_;
13475:     {
13476: 	use integer;
13477: 	my $symbchck=unpack("%32S*",$symb) << 21;
13478: 	my $symbseed=numval($symb) << 10;
13479: 	my $namechck=unpack("%32S*",$username);
13480: 	
13481: 	my $nameseed=numval($username) << 21;
13482: 	my $domainseed=unpack("%32S*",$domain) << 10;
13483: 	my $courseseed=unpack("%32S*",$courseid);
13484: 	
13485: 	my $num1=$symbchck+$symbseed+$namechck;
13486: 	my $num2=$nameseed+$domainseed+$courseseed;
13487: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
13488: 	#&logthis("rndseed :$num:$symb");
13489: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
13490: 	return "$num1,$num2";
13491:     }
13492: }
13493: 
13494: sub rndseed_64bit2 {
13495:     my ($symb,$courseid,$domain,$username)=@_;
13496:     {
13497: 	use integer;
13498: 	# strings need to be an even # of cahracters long, it it is odd the
13499:         # last characters gets thrown away
13500: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
13501: 	my $symbseed=numval($symb) << 10;
13502: 	my $namechck=unpack("%32S*",$username.' ');
13503: 	
13504: 	my $nameseed=numval($username) << 21;
13505: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
13506: 	my $courseseed=unpack("%32S*",$courseid.' ');
13507: 	
13508: 	my $num1=$symbchck+$symbseed+$namechck;
13509: 	my $num2=$nameseed+$domainseed+$courseseed;
13510: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
13511: 	#&logthis("rndseed :$num:$symb");
13512: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
13513: 	return "$num1,$num2";
13514:     }
13515: }
13516: 
13517: sub rndseed_64bit3 {
13518:     my ($symb,$courseid,$domain,$username)=@_;
13519:     {
13520: 	use integer;
13521: 	# strings need to be an even # of cahracters long, it it is odd the
13522:         # last characters gets thrown away
13523: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
13524: 	my $symbseed=numval2($symb) << 10;
13525: 	my $namechck=unpack("%32S*",$username.' ');
13526: 	
13527: 	my $nameseed=numval2($username) << 21;
13528: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
13529: 	my $courseseed=unpack("%32S*",$courseid.' ');
13530: 	
13531: 	my $num1=$symbchck+$symbseed+$namechck;
13532: 	my $num2=$nameseed+$domainseed+$courseseed;
13533: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
13534: 	#&logthis("rndseed :$num1:$num2:$_64bit");
13535: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
13536: 	
13537: 	return "$num1:$num2";
13538:     }
13539: }
13540: 
13541: sub rndseed_64bit4 {
13542:     my ($symb,$courseid,$domain,$username)=@_;
13543:     {
13544: 	use integer;
13545: 	# strings need to be an even # of cahracters long, it it is odd the
13546:         # last characters gets thrown away
13547: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
13548: 	my $symbseed=numval3($symb) << 10;
13549: 	my $namechck=unpack("%32S*",$username.' ');
13550: 	
13551: 	my $nameseed=numval3($username) << 21;
13552: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
13553: 	my $courseseed=unpack("%32S*",$courseid.' ');
13554: 	
13555: 	my $num1=$symbchck+$symbseed+$namechck;
13556: 	my $num2=$nameseed+$domainseed+$courseseed;
13557: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
13558: 	#&logthis("rndseed :$num1:$num2:$_64bit");
13559: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
13560: 	
13561: 	return "$num1:$num2";
13562:     }
13563: }
13564: 
13565: sub rndseed_64bit5 {
13566:     my ($symb,$courseid,$domain,$username)=@_;
13567:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
13568:     return "$num1:$num2";
13569: }
13570: 
13571: sub rndseed_CODE_64bit {
13572:     my ($symb,$courseid,$domain,$username)=@_;
13573:     {
13574: 	use integer;
13575: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
13576: 	my $symbseed=numval2($symb);
13577: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
13578: 	my $CODEseed=numval(&getCODE());
13579: 	my $courseseed=unpack("%32S*",$courseid.' ');
13580: 	my $num1=$symbseed+$CODEchck;
13581: 	my $num2=$CODEseed+$courseseed+$symbchck;
13582: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
13583: 	#&logthis("rndseed :$num1:$num2:$symb");
13584: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
13585: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
13586: 	return "$num1:$num2";
13587:     }
13588: }
13589: 
13590: sub rndseed_CODE_64bit4 {
13591:     my ($symb,$courseid,$domain,$username)=@_;
13592:     {
13593: 	use integer;
13594: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
13595: 	my $symbseed=numval3($symb);
13596: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
13597: 	my $CODEseed=numval3(&getCODE());
13598: 	my $courseseed=unpack("%32S*",$courseid.' ');
13599: 	my $num1=$symbseed+$CODEchck;
13600: 	my $num2=$CODEseed+$courseseed+$symbchck;
13601: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
13602: 	#&logthis("rndseed :$num1:$num2:$symb");
13603: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
13604: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
13605: 	return "$num1:$num2";
13606:     }
13607: }
13608: 
13609: sub rndseed_CODE_64bit5 {
13610:     my ($symb,$courseid,$domain,$username)=@_;
13611:     my $code = &getCODE();
13612:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
13613:     return "$num1:$num2";
13614: }
13615: 
13616: sub setup_random_from_rndseed {
13617:     my ($rndseed)=@_;
13618:     if ($rndseed =~/([,:])/) {
13619:         my ($num1,$num2) = map { abs($_); } (split(/[,:]/,$rndseed));
13620:         if ((!$num1) || (!$num2) || ($num1 > 2147483562) || ($num2 > 2147483398)) {
13621:             &Math::Random::random_set_seed_from_phrase($rndseed);
13622:         } else {
13623:             &Math::Random::random_set_seed($num1,$num2);
13624:         }
13625:     } else {
13626: 	&Math::Random::random_set_seed_from_phrase($rndseed);
13627:     }
13628: }
13629: 
13630: sub latest_receipt_algorithm_id {
13631:     return 'receipt3';
13632: }
13633: 
13634: sub recunique {
13635:     my $fucourseid=shift;
13636:     my $unique;
13637:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
13638: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
13639: 	$unique=$env{"course.$fucourseid.internal.encseed"};
13640:     } else {
13641: 	$unique=$perlvar{'lonReceipt'};
13642:     }
13643:     return unpack("%32C*",$unique);
13644: }
13645: 
13646: sub recprefix {
13647:     my $fucourseid=shift;
13648:     my $prefix;
13649:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
13650: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
13651: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
13652:     } else {
13653: 	$prefix=$perlvar{'lonHostID'};
13654:     }
13655:     return unpack("%32C*",$prefix);
13656: }
13657: 
13658: sub ireceipt {
13659:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
13660: 
13661:     my $return =&recprefix($fucourseid).'-';
13662: 
13663:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
13664: 	$env{'request.state'} eq 'construct') {
13665: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
13666: 	return $return;
13667:     }
13668: 
13669:     my $cuname=unpack("%32C*",$funame);
13670:     my $cudom=unpack("%32C*",$fudom);
13671:     my $cucourseid=unpack("%32C*",$fucourseid);
13672:     my $cusymb=unpack("%32C*",$fusymb);
13673:     my $cunique=&recunique($fucourseid);
13674:     my $cpart=unpack("%32S*",$part);
13675:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
13676: 
13677: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
13678: 			       
13679: 	$return.= ($cunique%$cuname+
13680: 		   $cunique%$cudom+
13681: 		   $cusymb%$cuname+
13682: 		   $cusymb%$cudom+
13683: 		   $cucourseid%$cuname+
13684: 		   $cucourseid%$cudom+
13685: 		   $cpart%$cuname+
13686: 		   $cpart%$cudom);
13687:     } else {
13688: 	$return.= ($cunique%$cuname+
13689: 		   $cunique%$cudom+
13690: 		   $cusymb%$cuname+
13691: 		   $cusymb%$cudom+
13692: 		   $cucourseid%$cuname+
13693: 		   $cucourseid%$cudom);
13694:     }
13695:     return $return;
13696: }
13697: 
13698: sub receipt {
13699:     my ($part)=@_;
13700:     my ($symb,$courseid,$domain,$name) = &whichuser();
13701:     return &ireceipt($name,$domain,$courseid,$symb,$part);
13702: }
13703: 
13704: sub whichuser {
13705:     my ($passedsymb)=@_;
13706:     my ($symb,$courseid,$domain,$name,$publicuser);
13707:     if (defined($env{'form.grade_symb'})) {
13708: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
13709: 	my $allowed=&allowed('vgr',$tmp_courseid);
13710: 	if (!$allowed &&
13711: 	    exists($env{'request.course.sec'}) &&
13712: 	    $env{'request.course.sec'} !~ /^\s*$/) {
13713: 	    $allowed=&allowed('vgr',$tmp_courseid.
13714: 			      '/'.$env{'request.course.sec'});
13715: 	}
13716: 	if ($allowed) {
13717: 	    ($symb)=&get_env_multiple('form.grade_symb');
13718: 	    $courseid=$tmp_courseid;
13719: 	    ($domain)=&get_env_multiple('form.grade_domain');
13720: 	    ($name)=&get_env_multiple('form.grade_username');
13721: 	    return ($symb,$courseid,$domain,$name,$publicuser);
13722: 	}
13723:     }
13724:     if (!$passedsymb) {
13725: 	$symb=&symbread();
13726:     } else {
13727: 	$symb=$passedsymb;
13728:     }
13729:     $courseid=$env{'request.course.id'};
13730:     $domain=$env{'user.domain'};
13731:     $name=$env{'user.name'};
13732:     if ($name eq 'public' && $domain eq 'public') {
13733: 	if (!defined($env{'form.username'})) {
13734: 	    $env{'form.username'}.=time.rand(10000000);
13735: 	}
13736: 	$name.=$env{'form.username'};
13737:     }
13738:     return ($symb,$courseid,$domain,$name,$publicuser);
13739: 
13740: }
13741: 
13742: # ------------------------------------------------------------ Serves up a file
13743: # returns either the contents of the file or 
13744: # -1 if the file doesn't exist
13745: #
13746: # if the target is a file that was uploaded via DOCS, 
13747: # a check will be made to see if a current copy exists on the local server,
13748: # if it does this will be served, otherwise a copy will be retrieved from
13749: # the home server for the course and stored in /home/httpd/html/userfiles on
13750: # the local server.   
13751: 
13752: sub getfile {
13753:     my ($file) = @_;
13754:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
13755:     &repcopy($file);
13756:     return &readfile($file);
13757: }
13758: 
13759: sub repcopy_userfile {
13760:     my ($file)=@_;
13761:     my $londocroot = $perlvar{'lonDocRoot'};
13762:     if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
13763:     if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
13764:     my ($cdom,$cnum,$filename) = 
13765: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
13766:     my $uri="/uploaded/$cdom/$cnum/$filename";
13767:     if (-e "$file") {
13768: # we already have a local copy, check it out
13769: 	my @fileinfo = stat($file);
13770: 	my $rtncode;
13771: 	my $info;
13772: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
13773: 	if ($lwpresp ne 'ok') {
13774: # there is no such file anymore, even though we had a local copy
13775: 	    if ($rtncode eq '404') {
13776: 		unlink($file);
13777: 	    }
13778: 	    return -1;
13779: 	}
13780: 	if ($info < $fileinfo[9]) {
13781: # nice, the file we have is up-to-date, just say okay
13782: 	    return 'ok';
13783: 	} else {
13784: # the file is outdated, get rid of it
13785: 	    unlink($file);
13786: 	}
13787:     }
13788: # one way or the other, at this point, we don't have the file
13789: # construct the correct path for the file
13790:     my @parts = ($cdom,$cnum); 
13791:     if ($filename =~ m|^(.+)/[^/]+$|) {
13792: 	push @parts, split(/\//,$1);
13793:     }
13794:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
13795:     foreach my $part (@parts) {
13796: 	$path .= '/'.$part;
13797: 	if (!-e $path) {
13798: 	    mkdir($path,0770);
13799: 	}
13800:     }
13801: # now the path exists for sure
13802: # get a user agent
13803:     my $transferfile=$file.'.in.transfer';
13804: # FIXME: this should flock
13805:     if (-e $transferfile) { return 'ok'; }
13806:     my $request;
13807:     $uri=~s/^\///;
13808:     my $homeserver = &homeserver($cnum,$cdom);
13809:     my $hostname = &hostname($homeserver);
13810:     my $protocol = $protocol{$homeserver};
13811:     $protocol = 'http' if ($protocol ne 'https');
13812:     $request=new HTTP::Request('GET',$protocol.'://'.$hostname.'/raw/'.$uri);
13813:     my $response = &LONCAPA::LWPReq::makerequest($homeserver,$request,$transferfile,\%perlvar,'',0,1);
13814: # did it work?
13815:     if ($response->is_error()) {
13816: 	unlink($transferfile);
13817: 	&logthis("Userfile repcopy failed for $uri");
13818: 	return -1;
13819:     }
13820: # worked, rename the transfer file
13821:     rename($transferfile,$file);
13822:     return 'ok';
13823: }
13824: 
13825: sub tokenwrapper {
13826:     my $uri=shift;
13827:     $uri=~s|^https?\://([^/]+)||;
13828:     $uri=~s|^/||;
13829:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
13830:     my $token=$1;
13831:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
13832:     if ($udom && $uname && $file) {
13833: 	$file=~s|(\?\.*)*$||;
13834:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
13835:         my $homeserver = &homeserver($uname,$udom);
13836:         my $hostname = &hostname($homeserver);
13837:         my $protocol = $protocol{$homeserver};
13838:         $protocol = 'http' if ($protocol ne 'https');
13839:         return $protocol.'://'.$hostname.'/'.$uri.
13840:                (($uri=~/\?/)?'&':'?').'token='.$token.
13841:                                '&tokenissued='.$perlvar{'lonHostID'};
13842:     } else {
13843:         return '/adm/notfound.html';
13844:     }
13845: }
13846: 
13847: # call with reqtype HEAD: get last modification time
13848: # call with reqtype GET: get the file contents
13849: # Do not call this with reqtype GET for large files! It loads everything into memory
13850: #
13851: sub getuploaded {
13852:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
13853:     $uri=~s/^\///;
13854:     my $homeserver = &homeserver($cnum,$cdom);
13855:     my $hostname = &hostname($homeserver);
13856:     my $protocol = $protocol{$homeserver};
13857:     $protocol = 'http' if ($protocol ne 'https');
13858:     $uri = $protocol.'://'.$hostname.'/raw/'.$uri;
13859:     my $request=new HTTP::Request($reqtype,$uri);
13860:     my $response=&LONCAPA::LWPReq::makerequest($homeserver,$request,'',\%perlvar,'',0,1);
13861:     $$rtncode = $response->code;
13862:     if (! $response->is_success()) {
13863: 	return 'failed';
13864:     }      
13865:     if ($reqtype eq 'HEAD') {
13866: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
13867:     } elsif ($reqtype eq 'GET') {
13868: 	$$info = $response->content;
13869:     }
13870:     return 'ok';
13871: }
13872: 
13873: sub readfile {
13874:     my $file = shift;
13875:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
13876:     my $fh;
13877:     open($fh,"<",$file);
13878:     my $a='';
13879:     while (my $line = <$fh>) { $a .= $line; }
13880:     return $a;
13881: }
13882: 
13883: sub filelocation {
13884:     my ($dir,$file) = @_;
13885:     my $location;
13886:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
13887: 
13888:     if ($file =~ m-^/adm/-) {
13889: 	$file=~s-^/adm/wrapper/-/-;
13890: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
13891:     }
13892: 
13893:     if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
13894:         $location = $file;
13895:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
13896:         my ($udom,$uname,$filename)=
13897:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
13898:         my $home=&homeserver($uname,$udom);
13899:         my $is_me=0;
13900:         my @ids=&current_machine_ids();
13901:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
13902:         if ($is_me) {
13903:   	    $location=propath($udom,$uname).'/userfiles/'.$filename;
13904:         } else {
13905:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
13906:   	      $udom.'/'.$uname.'/'.$filename;
13907:         }
13908:     } elsif ($file =~ m-^/adm/-) {
13909: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
13910:     } else {
13911:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
13912:         $file=~s:^/(res|priv)/:/:;
13913:         my $space=$1;
13914:         if ( !( $file =~ m:^/:) ) {
13915:             $location = $dir. '/'.$file;
13916:         } else {
13917:             $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
13918:         }
13919:     }
13920:     $location=~s://+:/:g; # remove duplicate /
13921:     while ($location=~m{/\.\./}) {
13922: 	if ($location =~ m{/[^/]+/\.\./}) {
13923: 	    $location=~ s{/[^/]+/\.\./}{/}g;
13924: 	} else {
13925: 	    $location=~ s{/\.\./}{/}g;
13926: 	}
13927:     } #remove dir/..
13928:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
13929:     return $location;
13930: }
13931: 
13932: sub hreflocation {
13933:     my ($dir,$file)=@_;
13934:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
13935: 	$file=filelocation($dir,$file);
13936:     } elsif ($file=~m-^/adm/-) {
13937: 	$file=~s-^/adm/wrapper/-/-;
13938: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
13939:     }
13940:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
13941: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
13942:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
13943: 	$file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
13944: 	        {/uploaded/$1/$2/}x;
13945:     }
13946:     if ($file=~ m{^/userfiles/}) {
13947: 	$file =~ s{^/userfiles/}{/uploaded/};
13948:     }
13949:     return $file;
13950: }
13951: 
13952: 
13953: 
13954: 
13955: 
13956: sub current_machine_domains {
13957:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
13958: }
13959: 
13960: sub machine_domains {
13961:     my ($hostname) = @_;
13962:     my @domains;
13963:     my %hostname = &all_hostnames();
13964:     while( my($id, $name) = each(%hostname)) {
13965: #	&logthis("-$id-$name-$hostname-");
13966: 	if ($hostname eq $name) {
13967: 	    push(@domains,&host_domain($id));
13968: 	}
13969:     }
13970:     return @domains;
13971: }
13972: 
13973: sub current_machine_ids {
13974:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
13975: }
13976: 
13977: sub machine_ids {
13978:     my ($hostname) = @_;
13979:     $hostname ||= &hostname($perlvar{'lonHostID'});
13980:     my @ids;
13981:     my %name_to_host = &all_names();
13982:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
13983: 	return @{ $name_to_host{$hostname} };
13984:     }
13985:     return;
13986: }
13987: 
13988: sub additional_machine_domains {
13989:     my @domains;
13990:     open(my $fh,"<","$perlvar{'lonTabDir'}/expected_domains.tab");
13991:     while( my $line = <$fh>) {
13992:         $line =~ s/\s//g;
13993:         push(@domains,$line);
13994:     }
13995:     return @domains;
13996: }
13997: 
13998: sub default_login_domain {
13999:     my $domain = $perlvar{'lonDefDomain'};
14000:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
14001:     foreach my $posdom (&current_machine_domains(),
14002:                         &additional_machine_domains()) {
14003:         if (lc($posdom) eq lc($testdomain)) {
14004:             $domain=$posdom;
14005:             last;
14006:         }
14007:     }
14008:     return $domain;
14009: }
14010: 
14011: sub uses_sts {
14012:     my ($ignore_cache) = @_;
14013:     my $lonhost = $perlvar{'lonHostID'};
14014:     my $hostname = &hostname($lonhost);
14015:     my $sts_on;
14016:     if ($protocol{$lonhost} eq 'https') {
14017:         my $cachetime = 12*3600;
14018:         if (!$ignore_cache) {
14019:             ($sts_on,my $cached)=&is_cached_new('stspolicy',$lonhost);
14020:             if (defined($cached)) {
14021:                 return $sts_on;
14022:             }
14023:         }
14024:         my $url = $protocol{$lonhost}.'://'.$hostname.'/index.html';
14025:         my $request=new HTTP::Request('HEAD',$url);
14026:         my $response=&LONCAPA::LWPReq::makerequest($lonhost,$request,'',\%perlvar,'','','',1);
14027:         if ($response->is_success) {
14028:             my $has_sts = $response->header('Strict-Transport-Security');
14029:             if ($has_sts eq '') {
14030:                 $sts_on = 0;
14031:             } else {
14032:                 if ($has_sts =~ /\Qmax-age=\E(\d+)/) {
14033:                     my $maxage = $1;
14034:                     if ($maxage) {
14035:                         $sts_on = 1;
14036:                     } else {
14037:                         $sts_on = 0;
14038:                     }
14039:                 } else {
14040:                     $sts_on = 0;
14041:                 }
14042:             }
14043:             return &do_cache_new('stspolicy',$lonhost,$sts_on,$cachetime);
14044:         }
14045:     }
14046:     return;
14047: }
14048: 
14049: # ------------------------------------------------------------- Declutters URLs
14050: 
14051: sub declutter {
14052:     my $thisfn=shift;
14053:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
14054:     unless ($thisfn=~m{^/home/httpd/html/priv/}) {
14055:         $thisfn=~s{^/home/httpd/html}{};
14056:     }
14057:     $thisfn=~s/^\///;
14058:     $thisfn=~s|^adm/wrapper/||;
14059:     $thisfn=~s|^adm/coursedocs/showdoc/||;
14060:     $thisfn=~s/^res\///;
14061:     $thisfn=~s/^priv\///;
14062:     unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
14063:         $thisfn=~s/\?.+$//;
14064:     }
14065:     return $thisfn;
14066: }
14067: 
14068: # ------------------------------------------------------------- Clutter up URLs
14069: 
14070: sub clutter {
14071:     my $thisfn='/'.&declutter(shift);
14072:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
14073: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
14074:        $thisfn='/res'.$thisfn; 
14075:     }
14076:     if ($thisfn !~m|^/adm|) {
14077: 	if ($thisfn =~ m|^/ext/|) {
14078: 	    $thisfn='/adm/wrapper'.$thisfn;
14079: 	} else {
14080: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
14081: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
14082: 	    if ($embstyle eq 'ssi'
14083: 		|| ($embstyle eq 'hdn')
14084: 		|| ($embstyle eq 'rat')
14085: 		|| ($embstyle eq 'prv')
14086: 		|| ($embstyle eq 'ign')) {
14087: 		#do nothing with these
14088: 	    } elsif (($embstyle eq 'img') 
14089: 		|| ($embstyle eq 'emb')
14090: 		|| ($embstyle eq 'wrp')) {
14091: 		$thisfn='/adm/wrapper'.$thisfn;
14092: 	    } elsif ($embstyle eq 'unk'
14093: 		     && $thisfn!~/\.(sequence|page)$/) {
14094: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
14095: 	    } else {
14096: #		&logthis("Got a blank emb style");
14097: 	    }
14098: 	}
14099:     } elsif ($thisfn =~ m{^/adm/$match_domain/$match_courseid/\d+/ext\.tool$}) {
14100:         $thisfn='/adm/wrapper'.$thisfn;
14101:     }
14102:     return $thisfn;
14103: }
14104: 
14105: sub clutter_with_no_wrapper {
14106:     my $uri = &clutter(shift);
14107:     if ($uri =~ m-^/adm/-) {
14108: 	$uri =~ s-^/adm/wrapper/-/-;
14109: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
14110:     }
14111:     return $uri;
14112: }
14113: 
14114: sub freeze_escape {
14115:     my ($value)=@_;
14116:     if (ref($value)) {
14117: 	$value=&nfreeze($value);
14118: 	return '__FROZEN__'.&escape($value);
14119:     }
14120:     return &escape($value);
14121: }
14122: 
14123: 
14124: sub thaw_unescape {
14125:     my ($value)=@_;
14126:     if ($value =~ /^__FROZEN__/) {
14127: 	substr($value,0,10,undef);
14128: 	$value=&unescape($value);
14129: 	return &thaw($value);
14130:     }
14131:     return &unescape($value);
14132: }
14133: 
14134: sub correct_line_ends {
14135:     my ($result)=@_;
14136:     $$result =~s/\r\n/\n/mg;
14137:     $$result =~s/\r/\n/mg;
14138: }
14139: # ================================================================ Main Program
14140: 
14141: sub goodbye {
14142:    &logthis("Starting Shut down");
14143: #not converted to using infrastruture and probably shouldn't be
14144:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
14145: #converted
14146: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
14147:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
14148: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
14149: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
14150: #1.1 only
14151: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
14152: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
14153: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
14154: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
14155:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
14156:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
14157:    &logthis(sprintf("%-20s is %s",'hits',$hits));
14158:    &flushcourselogs();
14159:    &logthis("Shutting down");
14160: }
14161: 
14162: sub get_dns {
14163:     my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
14164:     if (!$ignore_cache) {
14165: 	my ($content,$cached)=
14166: 	    &Apache::lonnet::is_cached_new('dns',$url);
14167: 	if ($cached) {
14168: 	    &$func($content,$hashref);
14169: 	    return;
14170: 	}
14171:     }
14172: 
14173:     my %alldns;
14174:     if (open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab")) {
14175:         foreach my $dns (<$config>) {
14176: 	    next if ($dns !~ /^\^(\S*)/x);
14177:             my $line = $1;
14178:             my ($host,$protocol) = split(/:/,$line);
14179:             if ($protocol ne 'https') {
14180:                 $protocol = 'http';
14181:             }
14182: 	    $alldns{$host} = $protocol;
14183:         }
14184:         close($config);
14185:     }
14186:     while (%alldns) {
14187: 	my ($dns) = sort { $b cmp $a } keys(%alldns);
14188: 	my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
14189:         my $response = &LONCAPA::LWPReq::makerequest('',$request,'',\%perlvar,30,0);
14190:         delete($alldns{$dns});
14191: 	next if ($response->is_error());
14192:         if ($url eq '/adm/dns/loncapaCRL') {
14193:             return &$func($response);
14194:         } else {
14195: 	    my @content = split("\n",$response->content);
14196: 	    unless ($nocache) {
14197: 	        &do_cache_new('dns',$url,\@content,30*24*60*60);
14198: 	    }
14199: 	    &$func(\@content,$hashref);
14200:             return;
14201:         }
14202:     }
14203:     my $which = (split('/',$url,4))[3];
14204:     if ($which eq 'loncapaCRL') {
14205:         my $diskfile = "$perlvar{'lonCertificateDirectory'}/$perlvar{'lonnetCertRevocationList'}";
14206:         if (-e $diskfile) {
14207:             &logthis("unable to contact DNS, on disk file $diskfile not updated");
14208:         } else {
14209:             &logthis("unable to contact DNS, no on disk file $diskfile available");
14210:         }
14211:     } else {
14212:         &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
14213:         if (open(my $config,"<","$perlvar{'lonTabDir'}/dns_$which.tab")) {
14214:             my @content = <$config>;
14215:             close($config);
14216:             &$func(\@content,$hashref);
14217:         }
14218:     }
14219:     return;
14220: }
14221: 
14222: # ------------------------------------------------------Get DNS checksums file
14223: sub parse_dns_checksums_tab {
14224:     my ($lines,$hashref) = @_;
14225:     my $lonhost = $perlvar{'lonHostID'};
14226:     my $machine_dom = &Apache::lonnet::host_domain($lonhost);
14227:     my $loncaparev = &get_server_loncaparev($machine_dom);
14228:     my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
14229:     my $webconfdir = '/etc/httpd/conf';
14230:     if ($distro =~ /^(ubuntu|debian)(\d+)$/) {
14231:         $webconfdir = '/etc/apache2';
14232:     } elsif ($distro =~ /^sles(\d+)$/) {
14233:         if ($1 >= 10) {
14234:             $webconfdir = '/etc/apache2';
14235:         }
14236:     } elsif ($distro =~ /^suse(\d+\.\d+)$/) {
14237:         if ($1 >= 10.0) {
14238:             $webconfdir = '/etc/apache2';
14239:         }
14240:     }
14241:     my ($release,$timestamp) = split(/\-/,$loncaparev);
14242:     my (%chksum,%revnum);
14243:     if (ref($lines) eq 'ARRAY') {
14244:         chomp(@{$lines});
14245:         my $version = shift(@{$lines});
14246:         if ($version eq $release) {  
14247:             foreach my $line (@{$lines}) {
14248:                 my ($file,$version,$shasum) = split(/,/,$line);
14249:                 if ($file =~ m{^/etc/httpd/conf}) {
14250:                     if ($webconfdir eq '/etc/apache2') {
14251:                         $file =~ s{^\Q/etc/httpd/conf/\E}{$webconfdir/};
14252:                     }
14253:                 }
14254:                 $chksum{$file} = $shasum;
14255:                 $revnum{$file} = $version;
14256:             }
14257:             if (ref($hashref) eq 'HASH') {
14258:                 %{$hashref} = (
14259:                                 sums     => \%chksum,
14260:                                 versions => \%revnum,
14261:                               );
14262:             }
14263:         }
14264:     }
14265:     return;
14266: }
14267: 
14268: sub fetch_dns_checksums {
14269:     my %checksums;
14270:     my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
14271:     my $loncaparev = &get_server_loncaparev($machine_dom,$perlvar{'lonHostID'});
14272:     my ($release,$timestamp) = split(/\-/,$loncaparev);
14273:     &get_dns("/adm/dns/checksums/$release",\&parse_dns_checksums_tab,1,1,
14274:              \%checksums);
14275:     return \%checksums;
14276: }
14277: 
14278: sub fetch_crl_pemfile {
14279:     return &get_dns("/adm/dns/loncapaCRL",\&save_crl_pem,1,1);
14280: }
14281: 
14282: sub save_crl_pem {
14283:     my ($response) = @_;
14284:     my ($msg,$hadchanges);
14285:     if (ref($response)) {
14286:         my $now = time;
14287:         my $lonca = $perlvar{'lonCertificateDirectory'}.'/'.$perlvar{'lonnetCertificateAuthority'};
14288:         my $tmpcrl = $tmpdir.'/'.$perlvar{'lonnetCertRevocationList'}.'_'.$now.'.'.$$.'.tmp';
14289:         if (open(my $fh,'>',"$tmpcrl")) {
14290:             print $fh $response->content;
14291:             close($fh);
14292:             if (-e $lonca) {
14293:                 if (open(PIPE,"openssl crl -in $tmpcrl -inform pem -CAfile $lonca -noout 2>&1 |")) {
14294:                     my $check = <PIPE>;
14295:                     close(PIPE);
14296:                     chomp($check);
14297:                     if ($check eq 'verify OK') {
14298:                         my $dest = "$perlvar{'lonCertificateDirectory'}/$perlvar{'lonnetCertRevocationList'}";
14299:                         my $backup;
14300:                         if (-e $dest) {
14301:                             if (&File::Copy::move($dest,"$dest.bak")) {
14302:                                 $backup = 'ok';
14303:                             }
14304:                         }
14305:                         if (&File::Copy::move($tmpcrl,$dest)) {
14306:                             $msg = 'ok';
14307:                             if ($backup) {
14308:                                 my (%oldnums,%newnums);
14309:                                 if (open(PIPE, "openssl crl -inform PEM -text -noout -in $dest.bak |grep 'Serial Number' |")) {
14310:                                     while (<PIPE>) {
14311:                                         $oldnums{(split(/:/))[1]} = 1;
14312:                                     }
14313:                                     close(PIPE);
14314:                                 }
14315:                                 if (open(PIPE, "openssl crl -inform PEM -text -noout -in $dest |grep 'Serial Number' |")) {
14316:                                     while(<PIPE>) {
14317:                                         $newnums{(split(/:/))[1]} = 1;
14318:                                     }
14319:                                     close(PIPE);
14320:                                 }
14321:                                 foreach my $key (sort {$b <=> $a } (keys(%newnums))) {
14322:                                     unless (exists($oldnums{$key})) {
14323:                                         $hadchanges = 1;
14324:                                         last;
14325:                                     }
14326:                                 }
14327:                                 unless ($hadchanges) {
14328:                                     foreach my $key (sort {$b <=> $a } (keys(%oldnums))) {
14329:                                         unless (exists($newnums{$key})) {
14330:                                             $hadchanges = 1;
14331:                                             last;
14332:                                         }
14333:                                     }
14334:                                 }
14335:                             }
14336:                         }
14337:                     } else {
14338:                         unlink($tmpcrl);
14339:                     }
14340:                 } else {
14341:                     unlink($tmpcrl);
14342:                 }
14343:             } else {
14344:                 unlink($tmpcrl);
14345:             }
14346:         }
14347:     }
14348:     return ($msg,$hadchanges);
14349: }
14350: 
14351: # ------------------------------------------------------------ Read domain file
14352: {
14353:     my $loaded;
14354:     my %domain;
14355: 
14356:     sub parse_domain_tab {
14357: 	my ($lines) = @_;
14358: 	foreach my $line (@$lines) {
14359: 	    next if ($line =~ /^(\#|\s*$ )/x);
14360: 
14361: 	    chomp($line);
14362: 	    my ($name,@elements) = split(/:/,$line,9);
14363: 	    my %this_domain;
14364: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
14365: 			       'lang_def', 'city', 'longi', 'lati',
14366: 			       'primary') {
14367: 		$this_domain{$field} = shift(@elements);
14368: 	    }
14369: 	    $domain{$name} = \%this_domain;
14370: 	}
14371:     }
14372: 
14373:     sub reset_domain_info {
14374: 	undef($loaded);
14375: 	undef(%domain);
14376:     }
14377: 
14378:     sub load_domain_tab {
14379: 	my ($ignore_cache,$nocache) = @_;
14380: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache,$nocache);
14381: 	my $fh;
14382: 	if (open($fh,"<",$perlvar{'lonTabDir'}.'/domain.tab')) {
14383: 	    my @lines = <$fh>;
14384: 	    &parse_domain_tab(\@lines);
14385: 	}
14386: 	close($fh);
14387: 	$loaded = 1;
14388:     }
14389: 
14390:     sub domain {
14391: 	&load_domain_tab() if (!$loaded);
14392: 
14393: 	my ($name,$what) = @_;
14394: 	return if ( !exists($domain{$name}) );
14395: 
14396: 	if (!$what) {
14397: 	    return $domain{$name}{'description'};
14398: 	}
14399: 	return $domain{$name}{$what};
14400:     }
14401: 
14402:     sub domain_info {
14403:         &load_domain_tab() if (!$loaded);
14404:         return %domain;
14405:     }
14406: 
14407: }
14408: 
14409: 
14410: # ------------------------------------------------------------- Read hosts file
14411: {
14412:     my %hostname;
14413:     my %hostdom;
14414:     my %libserv;
14415:     my $loaded;
14416:     my %name_to_host;
14417:     my %internetdom;
14418:     my %LC_dns_serv;
14419: 
14420:     sub parse_hosts_tab {
14421: 	my ($file) = @_;
14422: 	foreach my $configline (@$file) {
14423: 	    next if ($configline =~ /^(\#|\s*$ )/x);
14424:             chomp($configline);
14425: 	    if ($configline =~ /^\^/) {
14426:                 if ($configline =~ /^\^([\w.\-]+)/) {
14427:                     $LC_dns_serv{$1} = 1;
14428:                 }
14429:                 next;
14430:             }
14431: 	    my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
14432: 	    $name=~s/\s//g;
14433: 	    if ($id && $domain && $role && $name) {
14434:                 if ((exists($hostname{$id})) && ($hostname{$id} ne '')) {
14435:                     my $curr = $hostname{$id};
14436:                     my $skip;
14437:                     if (ref($name_to_host{$curr}) eq 'ARRAY') {
14438:                         if (($curr eq $name) && (@{$name_to_host{$curr}} == 1)) {
14439:                             $skip = 1;
14440:                         } else {
14441:                             @{$name_to_host{$curr}} = grep { $_ ne $id } @{$name_to_host{$curr}};
14442:                         }
14443:                     }
14444:                     unless ($skip) {
14445:                         push(@{$name_to_host{$name}},$id);
14446:                     }
14447:                 } else {
14448:                     push(@{$name_to_host{$name}},$id);
14449:                 }
14450: 		$hostname{$id}=$name;
14451: 		$hostdom{$id}=$domain;
14452: 		if ($role eq 'library') { $libserv{$id}=$name; }
14453:                 if (defined($protocol)) {
14454:                     if ($protocol eq 'https') {
14455:                         $protocol{$id} = $protocol;
14456:                     } else {
14457:                         $protocol{$id} = 'http'; 
14458:                     }
14459:                 } else {
14460:                     $protocol{$id} = 'http';
14461:                 }
14462:                 if (defined($intdom)) {
14463:                     $internetdom{$id} = $intdom;
14464:                 }
14465: 	    }
14466: 	}
14467:     }
14468:     
14469:     sub reset_hosts_info {
14470: 	&purge_remembered();
14471: 	&reset_domain_info();
14472: 	&reset_hosts_ip_info();
14473:         undef(%internetdom);
14474: 	undef(%name_to_host);
14475: 	undef(%hostname);
14476: 	undef(%hostdom);
14477: 	undef(%libserv);
14478: 	undef($loaded);
14479:     }
14480: 
14481:     sub load_hosts_tab {
14482: 	my ($ignore_cache,$nocache) = @_;
14483: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache,$nocache);
14484: 	open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab");
14485: 	my @config = <$config>;
14486: 	&parse_hosts_tab(\@config);
14487: 	close($config);
14488: 	$loaded=1;
14489:     }
14490: 
14491:     sub hostname {
14492: 	&load_hosts_tab() if (!$loaded);
14493: 
14494: 	my ($lonid) = @_;
14495: 	return $hostname{$lonid};
14496:     }
14497: 
14498:     sub all_hostnames {
14499: 	&load_hosts_tab() if (!$loaded);
14500: 
14501: 	return %hostname;
14502:     }
14503: 
14504:     sub all_names {
14505:         my ($ignore_cache,$nocache) = @_;
14506: 	&load_hosts_tab($ignore_cache,$nocache) if (!$loaded);
14507: 
14508: 	return %name_to_host;
14509:     }
14510: 
14511:     sub all_host_domain {
14512:         &load_hosts_tab() if (!$loaded);
14513:         return %hostdom;
14514:     }
14515: 
14516:     sub all_host_intdom {
14517:         &load_hosts_tab() if (!$loaded);
14518:         return %internetdom;
14519:     }
14520: 
14521:     sub is_library {
14522: 	&load_hosts_tab() if (!$loaded);
14523: 
14524: 	return exists($libserv{$_[0]});
14525:     }
14526: 
14527:     sub all_library {
14528: 	&load_hosts_tab() if (!$loaded);
14529: 
14530: 	return %libserv;
14531:     }
14532: 
14533:     sub unique_library {
14534: 	#2x reverse removes all hostnames that appear more than once
14535:         my %unique = reverse &all_library();
14536:         return reverse %unique;
14537:     }
14538: 
14539:     sub get_servers {
14540: 	&load_hosts_tab() if (!$loaded);
14541: 
14542: 	my ($domain,$type) = @_;
14543: 	my %possible_hosts = ($type eq 'library') ? %libserv
14544: 	                                          : %hostname;
14545: 	my %result;
14546: 	if (ref($domain) eq 'ARRAY') {
14547: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
14548: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
14549: 		    $result{$host} = $hostname;
14550: 		}
14551: 	    }
14552: 	} else {
14553: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
14554: 		if ($hostdom{$host} eq $domain) {
14555: 		    $result{$host} = $hostname;
14556: 		}
14557: 	    }
14558: 	}
14559: 	return %result;
14560:     }
14561: 
14562:     sub get_unique_servers {
14563:         my %unique = reverse &get_servers(@_);
14564: 	return reverse %unique;
14565:     }
14566: 
14567:     sub host_domain {
14568: 	&load_hosts_tab() if (!$loaded);
14569: 
14570: 	my ($lonid) = @_;
14571: 	return $hostdom{$lonid};
14572:     }
14573: 
14574:     sub all_domains {
14575: 	&load_hosts_tab() if (!$loaded);
14576: 
14577: 	my %seen;
14578: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
14579: 	return @uniq;
14580:     }
14581: 
14582:     sub internet_dom {
14583:         &load_hosts_tab() if (!$loaded);
14584: 
14585:         my ($lonid) = @_;
14586:         return $internetdom{$lonid};
14587:     }
14588: 
14589:     sub is_LC_dns {
14590:         &load_hosts_tab() if (!$loaded);
14591: 
14592:         my ($hostname) = @_;
14593:         return exists($LC_dns_serv{$hostname});
14594:     }
14595: 
14596: }
14597: 
14598: { 
14599:     my %iphost;
14600:     my %name_to_ip;
14601:     my %lonid_to_ip;
14602: 
14603:     sub get_hosts_from_ip {
14604: 	my ($ip) = @_;
14605: 	my %iphosts = &get_iphost();
14606: 	if (ref($iphosts{$ip})) {
14607: 	    return @{$iphosts{$ip}};
14608: 	}
14609: 	return;
14610:     }
14611:     
14612:     sub reset_hosts_ip_info {
14613: 	undef(%iphost);
14614: 	undef(%name_to_ip);
14615: 	undef(%lonid_to_ip);
14616:     }
14617: 
14618:     sub get_host_ip {
14619: 	my ($lonid) = @_;
14620: 	if (exists($lonid_to_ip{$lonid})) {
14621: 	    return $lonid_to_ip{$lonid};
14622: 	}
14623: 	my $name=&hostname($lonid);
14624:    	my $ip = gethostbyname($name);
14625: 	return if (!$ip || length($ip) ne 4);
14626: 	$ip=inet_ntoa($ip);
14627: 	$name_to_ip{$name}   = $ip;
14628: 	$lonid_to_ip{$lonid} = $ip;
14629: 	return $ip;
14630:     }
14631:     
14632:     sub get_iphost {
14633: 	my ($ignore_cache,$nocache) = @_;
14634: 
14635: 	if (!$ignore_cache) {
14636: 	    if (%iphost) {
14637: 		return %iphost;
14638: 	    }
14639: 	    my ($ip_info,$cached)=
14640: 		&Apache::lonnet::is_cached_new('iphost','iphost');
14641: 	    if ($cached) {
14642: 		%iphost      = %{$ip_info->[0]};
14643: 		%name_to_ip  = %{$ip_info->[1]};
14644: 		%lonid_to_ip = %{$ip_info->[2]};
14645: 		return %iphost;
14646: 	    }
14647: 	}
14648: 
14649: 	# get yesterday's info for fallback
14650: 	my %old_name_to_ip;
14651: 	my ($ip_info,$cached)=
14652: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
14653: 	if ($cached) {
14654: 	    %old_name_to_ip = %{$ip_info->[1]};
14655: 	}
14656: 
14657: 	my %name_to_host = &all_names($ignore_cache,$nocache);
14658: 	foreach my $name (keys(%name_to_host)) {
14659: 	    my $ip;
14660: 	    if (!exists($name_to_ip{$name})) {
14661: 		$ip = gethostbyname($name);
14662: 		if (!$ip || length($ip) ne 4) {
14663: 		    if (defined($old_name_to_ip{$name})) {
14664: 			$ip = $old_name_to_ip{$name};
14665: 			&logthis("Can't find $name defaulting to old $ip");
14666: 		    } else {
14667: 			&logthis("Name $name no IP found");
14668: 			next;
14669: 		    }
14670: 		} else {
14671: 		    $ip=inet_ntoa($ip);
14672: 		}
14673: 		$name_to_ip{$name} = $ip;
14674: 	    } else {
14675: 		$ip = $name_to_ip{$name};
14676: 	    }
14677: 	    foreach my $id (@{ $name_to_host{$name} }) {
14678: 		$lonid_to_ip{$id} = $ip;
14679: 	    }
14680: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
14681: 	}
14682:         unless ($nocache) {
14683: 	    &do_cache_new('iphost','iphost',
14684: 		          [\%iphost,\%name_to_ip,\%lonid_to_ip],
14685: 		          48*60*60);
14686:         }
14687: 
14688: 	return %iphost;
14689:     }
14690: 
14691:     #
14692:     #  Given a DNS returns the loncapa host name for that DNS 
14693:     # 
14694:     sub host_from_dns {
14695:         my ($dns) = @_;
14696:         my @hosts;
14697:         my $ip;
14698: 
14699:         if (exists($name_to_ip{$dns})) {
14700:             $ip = $name_to_ip{$dns};
14701:         }
14702:         if (!$ip) {
14703:             $ip = gethostbyname($dns); # Initial translation to IP is in net order.
14704:             if (length($ip) == 4) { 
14705: 	        $ip   = &IO::Socket::inet_ntoa($ip);
14706:             }
14707:         }
14708:         if ($ip) {
14709: 	    @hosts = get_hosts_from_ip($ip);
14710: 	    return $hosts[0];
14711:         }
14712:         return undef;
14713:     }
14714: 
14715:     sub get_internet_names {
14716:         my ($lonid) = @_;
14717:         return if ($lonid eq '');
14718:         my ($idnref,$cached)=
14719:             &Apache::lonnet::is_cached_new('internetnames',$lonid);
14720:         if ($cached) {
14721:             return $idnref;
14722:         }
14723:         my $ip = &get_host_ip($lonid);
14724:         my @hosts = &get_hosts_from_ip($ip);
14725:         my %iphost = &get_iphost();
14726:         my (@idns,%seen);
14727:         foreach my $id (@hosts) {
14728:             my $dom = &host_domain($id);
14729:             my $prim_id = &domain($dom,'primary');
14730:             my $prim_ip = &get_host_ip($prim_id);
14731:             next if ($seen{$prim_ip});
14732:             if (ref($iphost{$prim_ip}) eq 'ARRAY') {
14733:                 foreach my $id (@{$iphost{$prim_ip}}) {
14734:                     my $intdom = &internet_dom($id);
14735:                     unless (grep(/^\Q$intdom\E$/,@idns)) {
14736:                         push(@idns,$intdom);
14737:                     }
14738:                 }
14739:             }
14740:             $seen{$prim_ip} = 1;
14741:         }
14742:         return &do_cache_new('internetnames',$lonid,\@idns,12*60*60);
14743:     }
14744: 
14745: }
14746: 
14747: sub all_loncaparevs {
14748:     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);
14749: }
14750: 
14751: # ---------------------------------------------------------- Read loncaparev table
14752: {
14753:     sub load_loncaparevs { 
14754:         if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
14755:             if (open(my $config,"<","$perlvar{'lonTabDir'}/loncaparevs.tab")) {
14756:                 while (my $configline=<$config>) {
14757:                     chomp($configline);
14758:                     my ($hostid,$loncaparev)=split(/:/,$configline);
14759:                     $loncaparevs{$hostid}=$loncaparev;
14760:                 }
14761:                 close($config);
14762:             }
14763:         }
14764:     }
14765: }
14766: 
14767: # ---------------------------------------------------------- Read serverhostID table
14768: {
14769:     sub load_serverhomeIDs {
14770:         if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
14771:             if (open(my $config,"<","$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
14772:                 while (my $configline=<$config>) {
14773:                     chomp($configline);
14774:                     my ($name,$id)=split(/:/,$configline);
14775:                     $serverhomeIDs{$name}=$id;
14776:                 }
14777:                 close($config);
14778:             }
14779:         }
14780:     }
14781: }
14782: 
14783: 
14784: BEGIN {
14785: 
14786: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
14787:     unless ($readit) {
14788: {
14789:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
14790:     %perlvar = (%perlvar,%{$configvars});
14791: }
14792: 
14793: 
14794: # ------------------------------------------------------ Read spare server file
14795: {
14796:     open(my $config,"<","$perlvar{'lonTabDir'}/spare.tab");
14797: 
14798:     while (my $configline=<$config>) {
14799:        chomp($configline);
14800:        if ($configline) {
14801: 	   my ($host,$type) = split(':',$configline,2);
14802: 	   if (!defined($type) || $type eq '') { $type = 'default' };
14803: 	   push(@{ $spareid{$type} }, $host);
14804:        }
14805:     }
14806:     close($config);
14807: }
14808: # ------------------------------------------------------------ Read permissions
14809: {
14810:     open(my $config,"<","$perlvar{'lonTabDir'}/roles.tab");
14811: 
14812:     while (my $configline=<$config>) {
14813: 	chomp($configline);
14814: 	if ($configline) {
14815: 	    my ($role,$perm)=split(/ /,$configline);
14816: 	    if ($perm ne '') { $pr{$role}=$perm; }
14817: 	}
14818:     }
14819:     close($config);
14820: }
14821: 
14822: # -------------------------------------------- Read plain texts for permissions
14823: {
14824:     open(my $config,"<","$perlvar{'lonTabDir'}/rolesplain.tab");
14825: 
14826:     while (my $configline=<$config>) {
14827: 	chomp($configline);
14828: 	if ($configline) {
14829: 	    my ($short,@plain)=split(/:/,$configline);
14830:             %{$prp{$short}} = ();
14831: 	    if (@plain > 0) {
14832:                 $prp{$short}{'std'} = $plain[0];
14833:                 for (my $i=1; $i<@plain; $i++) {
14834:                     $prp{$short}{'alt'.$i} = $plain[$i];  
14835:                 }
14836:             }
14837: 	}
14838:     }
14839:     close($config);
14840: }
14841: 
14842: # ---------------------------------------------------------- Read package table
14843: {
14844:     open(my $config,"<","$perlvar{'lonTabDir'}/packages.tab");
14845: 
14846:     while (my $configline=<$config>) {
14847: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
14848: 	chomp($configline);
14849: 	my ($short,$plain)=split(/:/,$configline);
14850: 	my ($pack,$name)=split(/\&/,$short);
14851: 	if ($plain ne '') {
14852: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
14853: 	    $packagetab{$short}=$plain; 
14854: 	}
14855:     }
14856:     close($config);
14857: }
14858: 
14859: # ---------------------------------------------------------- Read loncaparev table
14860: 
14861: &load_loncaparevs();
14862: 
14863: # ---------------------------------------------------------- Read serverhostID table
14864: 
14865: &load_serverhomeIDs();
14866: 
14867: # ---------------------------------------------------------- Read releaseslist XML
14868: {
14869:     my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
14870:     if (-e $file) {
14871:         my $parser = HTML::LCParser->new($file);
14872:         while (my $token = $parser->get_token()) {
14873:             if ($token->[0] eq 'S') {
14874:                 my $item = $token->[1];
14875:                 my $name = $token->[2]{'name'};
14876:                 my $value = $token->[2]{'value'};
14877:                 my $valuematch = $token->[2]{'valuematch'};
14878:                 my $namematch = $token->[2]{'namematch'};
14879:                 if ($item eq 'parameter') {
14880:                     if (($namematch ne '') || (($name ne '') && ($value ne '' || $valuematch ne ''))) {
14881:                         my $release = $parser->get_text();
14882:                         $release =~ s/(^\s*|\s*$ )//gx;
14883:                         $needsrelease{$item.':'.$name.':'.$value.':'.$valuematch.':'.$namematch} = $release;
14884:                     }
14885:                 } elsif ($item ne '' && $name ne '') {
14886:                     my $release = $parser->get_text();
14887:                     $release =~ s/(^\s*|\s*$ )//gx;
14888:                     $needsrelease{$item.':'.$name.':'.$value} = $release;
14889:                 }
14890:             }
14891:         }
14892:     }
14893: }
14894: 
14895: # ---------------------------------------------------------- Read managers table
14896: {
14897:     if (-e "$perlvar{'lonTabDir'}/managers.tab") {
14898:         if (open(my $config,"<","$perlvar{'lonTabDir'}/managers.tab")) {
14899:             while (my $configline=<$config>) {
14900:                 chomp($configline);
14901:                 next if ($configline =~ /^\#/);
14902:                 if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
14903:                     $managerstab{$configline} = 1;
14904:                 }
14905:             }
14906:             close($config);
14907:         }
14908:     }
14909: }
14910: 
14911: # ------------- set up temporary directory
14912: {
14913:     $tmpdir = LONCAPA::tempdir();
14914: 
14915: }
14916: 
14917: # ------------- set default texengine (domain default overrides this)
14918: {
14919:     $deftex = LONCAPA::texengine();
14920: }
14921: 
14922: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
14923: 				'compress_threshold'=> 20_000,
14924:  			        });
14925: 
14926: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
14927: $dumpcount=0;
14928: $locknum=0;
14929: 
14930: &logtouch();
14931: &logthis('<font color="yellow">INFO: Read configuration</font>');
14932: $readit=1;
14933:     {
14934: 	use integer;
14935: 	my $test=(2**32)+1;
14936: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
14937: 	&logthis(" Detected 64bit platform ($_64bit)");
14938:     }
14939: }
14940: }
14941: 
14942: 1;
14943: __END__
14944: 
14945: =pod
14946: 
14947: =head1 NAME
14948: 
14949: Apache::lonnet - Subroutines to ask questions about things in the network.
14950: 
14951: =head1 SYNOPSIS
14952: 
14953: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
14954: 
14955:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
14956: 
14957: Common parameters:
14958: 
14959: =over 4
14960: 
14961: =item *
14962: 
14963: $uname : an internal username (if $cname expecting a course Id specifically)
14964: 
14965: =item *
14966: 
14967: $udom : a domain (if $cdom expecting a course's domain specifically)
14968: 
14969: =item *
14970: 
14971: $symb : a resource instance identifier
14972: 
14973: =item *
14974: 
14975: $namespace : the name of a .db file that contains the data needed or
14976: being set.
14977: 
14978: =back
14979: 
14980: =head1 OVERVIEW
14981: 
14982: lonnet provides subroutines which interact with the
14983: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
14984: about classes, users, and resources.
14985: 
14986: For many of these objects you can also use this to store data about
14987: them or modify them in various ways.
14988: 
14989: =head2 Symbs
14990: 
14991: To identify a specific instance of a resource, LON-CAPA uses symbols
14992: or "symbs"X<symb>. These identifiers are built from the URL of the
14993: map, the resource number of the resource in the map, and the URL of
14994: the resource itself. The latter is somewhat redundant, but might help
14995: if maps change.
14996: 
14997: An example is
14998: 
14999:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
15000: 
15001: The respective map entry is
15002: 
15003:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
15004:   title="Problem 2">
15005:  </resource>
15006: 
15007: Symbs are used by the random number generator, as well as to store and
15008: restore data specific to a certain instance of for example a problem.
15009: 
15010: =head2 Storing And Retrieving Data
15011: 
15012: X<store()>X<cstore()>X<restore()>Three of the most important functions
15013: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
15014: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
15015: is is the non-critical message twin of cstore. These functions are for
15016: handlers to store a perl hash to a user's permanent data space in an
15017: easy manner, and to retrieve it again on another call. It is expected
15018: that a handler would use this once at the beginning to retrieve data,
15019: and then again once at the end to send only the new data back.
15020: 
15021: The data is stored in the user's data directory on the user's
15022: homeserver under the ID of the course.
15023: 
15024: The hash that is returned by restore will have all of the previous
15025: value for all of the elements of the hash.
15026: 
15027: Example:
15028: 
15029:  #creating a hash
15030:  my %hash;
15031:  $hash{'foo'}='bar';
15032: 
15033:  #storing it
15034:  &Apache::lonnet::cstore(\%hash);
15035: 
15036:  #changing a value
15037:  $hash{'foo'}='notbar';
15038: 
15039:  #adding a new value
15040:  $hash{'bar'}='foo';
15041:  &Apache::lonnet::cstore(\%hash);
15042: 
15043:  #retrieving the hash
15044:  my %history=&Apache::lonnet::restore();
15045: 
15046:  #print the hash
15047:  foreach my $key (sort(keys(%history))) {
15048:    print("\%history{$key} = $history{$key}");
15049:  }
15050: 
15051: Will print out:
15052: 
15053:  %history{1:foo} = bar
15054:  %history{1:keys} = foo:timestamp
15055:  %history{1:timestamp} = 990455579
15056:  %history{2:bar} = foo
15057:  %history{2:foo} = notbar
15058:  %history{2:keys} = foo:bar:timestamp
15059:  %history{2:timestamp} = 990455580
15060:  %history{bar} = foo
15061:  %history{foo} = notbar
15062:  %history{timestamp} = 990455580
15063:  %history{version} = 2
15064: 
15065: Note that the special hash entries C<keys>, C<version> and
15066: C<timestamp> were added to the hash. C<version> will be equal to the
15067: total number of versions of the data that have been stored. The
15068: C<timestamp> attribute will be the UNIX time the hash was
15069: stored. C<keys> is available in every historical section to list which
15070: keys were added or changed at a specific historical revision of a
15071: hash.
15072: 
15073: B<Warning>: do not store the hash that restore returns directly. This
15074: will cause a mess since it will restore the historical keys as if the
15075: were new keys. I.E. 1:foo will become 1:1:foo etc.
15076: 
15077: Calling convention:
15078: 
15079:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname);
15080:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$laststore);
15081: 
15082: For more detailed information, see lonnet specific documentation.
15083: 
15084: =head1 RETURN MESSAGES
15085: 
15086: =over 4
15087: 
15088: =item * B<con_lost>: unable to contact remote host
15089: 
15090: =item * B<con_delayed>: unable to contact remote host, message will be delivered
15091: when the connection is brought back up
15092: 
15093: =item * B<con_failed>: unable to contact remote host and unable to save message
15094: for later delivery
15095: 
15096: =item * B<error:>: an error a occurred, a description of the error follows the :
15097: 
15098: =item * B<no_such_host>: unable to fund a host associated with the user/domain
15099: that was requested
15100: 
15101: =back
15102: 
15103: =head1 PUBLIC SUBROUTINES
15104: 
15105: =head2 Session Environment Functions
15106: 
15107: =over 4
15108: 
15109: =item * 
15110: X<appenv()>
15111: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
15112: the user envirnoment file, and will be restored for each access this
15113: user makes during this session, also modifies the %env for the current
15114: process. Optional rolesarrayref - if defined contains a reference to an array
15115: of roles which are exempt from the restriction on modifying user.role entries 
15116: in the user's environment.db and in %env.    
15117: 
15118: =item *
15119: X<delenv()>
15120: B<delenv($delthis,$regexp)>: removes all items from the session
15121: environment file that begin with $delthis. If the 
15122: optional second arg - $regexp - is true, $delthis is treated as a 
15123: regular expression, otherwise \Q$delthis\E is used. 
15124: The values are also deleted from the current processes %env.
15125: 
15126: =item * get_env_multiple($name) 
15127: 
15128: gets $name from the %env hash, it seemlessly handles the cases where multiple
15129: values may be defined and end up as an array ref.
15130: 
15131: returns an array of values
15132: 
15133: =back
15134: 
15135: =head2 User Information
15136: 
15137: =over 4
15138: 
15139: =item *
15140: X<queryauthenticate()>
15141: B<queryauthenticate($uname,$udom)>: try to determine user's current 
15142: authentication scheme
15143: 
15144: =item *
15145: X<authenticate()>
15146: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
15147: authenticate user from domain's lib servers (first use the current
15148: one). C<$upass> should be the users password.
15149: $checkdefauth is optional (value is 1 if a check should be made to
15150:    authenticate user using default authentication method, and allow
15151:    account creation if username does not have account in the domain).
15152: $clientcancheckhost is optional (value is 1 if checking whether the
15153:    server can host will occur on the client side in lonauth.pm).   
15154: 
15155: =item *
15156: X<homeserver()>
15157: B<homeserver($uname,$udom)>: find the server which has
15158: the user's directory and files (there must be only one), this caches
15159: the answer, and also caches if there is a borken connection.
15160: 
15161: =item *
15162: X<idget()>
15163: B<idget($udom,$idsref,$namespace)>: find the usernames behind either 
15164: a list of student/employee IDs or clicker IDs
15165: (student/employee IDs are a unique resource in a domain, there must be 
15166: only 1 ID per username, and only 1 username per ID in a specific domain).
15167: clickerIDs are not necessarily unique, as students might share clickers.
15168: (returns hash: id=>name,id=>name)
15169: 
15170: =item *
15171: X<idrget()>
15172: B<idrget($udom,@unames)>: find the IDs behind a list of
15173: usernames (returns hash: name=>id,name=>id)
15174: 
15175: =item *
15176: X<idput()>
15177: B<idput($udom,$idsref,$uhome,$namespace)>: store away a list of 
15178: names and associated student/employee IDs or clicker IDs.
15179: 
15180: =item *
15181: X<iddel()>
15182: B<iddel($udom,$idshashref,$uhome,$namespace)>: delete unwanted 
15183: student/employee ID or clicker ID username look-ups from domain.
15184: The homeserver ($uhome) and namespace ($namespace) are optional.
15185: If no $uhome is provided, it will be determined usig &homeserver()
15186: for each user.  If no $namespace is provided, the default is ids.
15187: 
15188: =item *
15189: X<updateclickers()>
15190: B<updateclickers($udom,$action,$idshashref,$uhome,$critical)>: update 
15191: clicker ID-to-username look-ups in clickers.db on library server.
15192: Permitted actions are add or del (i.e., add or delete). The 
15193: clickers.db contains clickerID as keys (escaped), and each corresponding
15194: value is an escaped comma-separated list of usernames (for whom the
15195: library server is the homeserver), who registered that particular ID.
15196: If $critical is true, the update will be sent via &critical, otherwise
15197: &reply() will be used.
15198: 
15199: =item *
15200: X<rolesinit()>
15201: B<rolesinit($udom,$username)>: get user privileges.
15202: returns user role, first access and timer interval hashes
15203: 
15204: =item *
15205: X<privileged()>
15206: B<privileged($username,$domain)>: returns a true if user has a
15207: privileged and active role (i.e. su or dc), false otherwise.
15208: 
15209: =item *
15210: X<getsection()>
15211: B<getsection($udom,$uname,$cname)>: finds the section of student in the
15212: course $cname, return section name/number or '' for "not in course"
15213: and '-1' for "no section"
15214: 
15215: =item *
15216: X<userenvironment()>
15217: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
15218: passed in @what from the requested user's environment, returns a hash
15219: 
15220: =item * 
15221: X<userlog_query()>
15222: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
15223: activity.log file. %filters defines filters applied when parsing the
15224: log file. These can be start or end timestamps, or the type of action
15225: - log to look for Login or Logout events, check for Checkin or
15226: Checkout, role for role selection. The response is in the form
15227: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
15228: escaped strings of the action recorded in the activity.log file.
15229: 
15230: =back
15231: 
15232: =head2 User Roles
15233: 
15234: =over 4
15235: 
15236: =item *
15237: 
15238: allowed($priv,$uri,$symb,$role,$clientip,$noblockcheck) : check for a user privilege; 
15239: returns codes for allowed actions.
15240: 
15241: The first argument is required, all others are optional.
15242: 
15243: $priv is the privilege being checked.
15244: $uri contains additional information about what is being checked for access (e.g.,
15245: URL, course ID etc.). 
15246: $symb is the unique resource instance identifier in a course; if needed,
15247: but not provided, it will be retrieved via a call to &symbread(). 
15248: $role is the role for which a priv is being checked (only used if priv is evb). 
15249: $clientip is the user's IP address (only used when checking for access to portfolio 
15250: files).
15251: $noblockcheck, if true, skips calls to &has_comm_blocking() for the bre priv. This 
15252: prevents recursive calls to &allowed.
15253: 
15254:  F: full access
15255:  U,I,K: authentication modes (cxx only)
15256:  '': forbidden
15257:  1: user needs to choose course
15258:  2: browse allowed
15259:  A: passphrase authentication needed
15260:  B: access temporarily blocked because of a blocking event in a course.
15261:  D: access blocked because access is required via session initiated via deep-link 
15262: 
15263: =item *
15264: 
15265: constructaccess($url,$setpriv) : check for access to construction space URL
15266: 
15267: See if the owner domain and name in the URL match those in the
15268: expected environment.  If so, return three element list
15269: ($ownername,$ownerdomain,$ownerhome).
15270: 
15271: Otherwise return the null string.
15272: 
15273: If second argument 'setpriv' is true, it assigns the privileges,
15274: and returns the same three element list, unless the owner has
15275: blocked "ad hoc" Domain Coordinator access to the Author Space,
15276: in which case the null string is returned.
15277: 
15278: =item *
15279: 
15280: definerole($rolename,$sysrole,$domrole,$courole,$uname,$udom) : define role;
15281: define a custom role rolename set privileges in format of lonTabs/roles.tab
15282: for system, domain, and course level. $uname and $udom are optional (current
15283: user's username and domain will be used when either of $uname or $udom are absent.
15284: 
15285: =item *
15286: 
15287: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
15288: (rolesplain.tab); plain text explanation of a user role term.
15289: $type is Course (default) or Community.
15290: If $forcedefault evaluates to true, text returned will be default 
15291: text for $type. Otherwise, if this is a course, the text returned 
15292: will be a custom name for the role (if defined in the course's 
15293: environment).  If no custom name is defined the default is returned.
15294:    
15295: =item *
15296: 
15297: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv) :
15298: All arguments are optional. Returns a hash of a roles, either for
15299: co-author/assistant author roles for a user's Construction Space
15300: (default), or if $context is 'userroles', roles for the user himself,
15301: In the hash, keys are set to colon-separated $uname,$udom,$role, and
15302: (optionally) if $withsec is true, a fourth colon-separated item - $section.
15303: For each key, value is set to colon-separated start and end times for
15304: the role.  If no username and domain are specified, will default to
15305: current user/domain. Types, roles, and roledoms are references to arrays
15306: of role statuses (active, future or previous), roles 
15307: (e.g., cc,in, st etc.) and domains of the roles which can be used
15308: to restrict the list of roles reported. If no array ref is 
15309: provided for types, will default to return only active roles.
15310: 
15311: =item *
15312: 
15313: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
15314: user: $uname:$udom has a role in the course: $cdom_$cnum. 
15315: 
15316: Additional optional arguments are: $type (if role checking is to be restricted 
15317: to certain user status types -- previous (expired roles), active (currently
15318: available roles) or future (roles available in the future), and
15319: $hideprivileged -- if true will not report course roles for users who
15320: have active Domain Coordinator role in course's domain or in additional
15321: domains (specified in 'Domains to check for privileged users' in course
15322: environment -- set via:  Course Settings -> Classlists and staff listing).
15323: 
15324: =item *
15325: 
15326: privileged($username,$domain,$possdomains,$possroles) : returns 1 if user
15327: $username:$domain is a privileged user (e.g., Domain Coordinator or Super User)
15328: $possdomains and $possroles are optional array refs -- to domains to check and
15329: roles to check.  If $possdomains is not specified, a dump will be done of the
15330: users' roles.db to check for a dc or su role in any domain. This can be
15331: time consuming if &privileged is called repeatedly (e.g., when displaying a
15332: classlist), so in such cases, supplying a $possdomains array is preferred, as
15333: this then allows &privileged_by_domain() to be used, which caches the identity
15334: of privileged users, eliminating the need for repeated calls to &dump().
15335: 
15336: =item *
15337: 
15338: privileged_by_domain($possdomains,$roles) : returns a hash of a hash of a hash,
15339: where the outer hash keys are domains specified in the $possdomains array ref,
15340: next inner hash keys are privileged roles specified in the $roles array ref,
15341: and the innermost hash contains key = value pairs for username:domain = end:start
15342: for active or future "privileged" users with that role in that domain. To avoid
15343: repeated dumps of domain roles -- via &get_domain_roles() -- contents of the
15344: innerhash are cached using priv_$role and $dom as the identifiers.
15345: 
15346: =back
15347: 
15348: =head2 User Modification
15349: 
15350: =over 4
15351: 
15352: =item *
15353: 
15354: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
15355: user for the level given by URL.  Optional start and end dates (leave empty
15356: string or zero for "no date")
15357: 
15358: =item *
15359: 
15360: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
15361: change a users, password, possible return values are: ok,
15362: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
15363: refused
15364: 
15365: =item *
15366: 
15367: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
15368: 
15369: =item *
15370: 
15371: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
15372:            $forceid,$desiredhome,$email,$inststatus,$candelete) :
15373: 
15374: will update user information (firstname,middlename,lastname,generation,
15375: permanentemail), and if forceid is true, student/employee ID also.
15376: A user's institutional affiliation(s) can also be updated.
15377: User information fields will not be overwritten with empty entries 
15378: unless the field is included in the $candelete array reference.
15379: This array is included when a single user is modified via "Manage Users",
15380: or when Autoupdate.pl is run by cron in a domain.
15381: 
15382: =item *
15383: 
15384: modifystudent
15385: 
15386: modify a student's enrollment and identification information.
15387: The course id is resolved based on the current user's environment.  
15388: This means the invoking user must be a course coordinator or otherwise
15389: associated with a course.
15390: 
15391: This call is essentially a wrapper for lonnet::modifyuser and
15392: lonnet::modify_student_enrollment
15393: 
15394: Inputs: 
15395: 
15396: =over 4
15397: 
15398: =item B<$udom> Student's loncapa domain
15399: 
15400: =item B<$uname> Student's loncapa login name
15401: 
15402: =item B<$uid> Student/Employee ID
15403: 
15404: =item B<$umode> Student's authentication mode
15405: 
15406: =item B<$upass> Student's password
15407: 
15408: =item B<$first> Student's first name
15409: 
15410: =item B<$middle> Student's middle name
15411: 
15412: =item B<$last> Student's last name
15413: 
15414: =item B<$gene> Student's generation
15415: 
15416: =item B<$usec> Student's section in course
15417: 
15418: =item B<$end> Unix time of the roles expiration
15419: 
15420: =item B<$start> Unix time of the roles start date
15421: 
15422: =item B<$forceid> If defined, allow $uid to be changed
15423: 
15424: =item B<$desiredhome> server to use as home server for student
15425: 
15426: =item B<$email> Student's permanent e-mail address
15427: 
15428: =item B<$type> Type of enrollment (auto or manual)
15429: 
15430: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
15431: 
15432: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
15433: 
15434: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
15435: 
15436: =item B<$context> role change context (shown in User Management Logs display in a course)
15437: 
15438: =item B<$inststatus> institutional status of user - : separated string of escaped status types
15439: 
15440: =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.
15441: 
15442: =back
15443: 
15444: =item *
15445: 
15446: modify_student_enrollment
15447: 
15448: Change a student's enrollment status in a class.  The environment variable
15449: 'role.request.course' must be defined for this function to proceed.
15450: 
15451: Inputs:
15452: 
15453: =over 4
15454: 
15455: =item $udom, student's domain
15456: 
15457: =item $uname, student's name
15458: 
15459: =item $uid, student's user id
15460: 
15461: =item $first, student's first name
15462: 
15463: =item $middle
15464: 
15465: =item $last
15466: 
15467: =item $gene
15468: 
15469: =item $usec
15470: 
15471: =item $end
15472: 
15473: =item $start
15474: 
15475: =item $type
15476: 
15477: =item $locktype
15478: 
15479: =item $cid
15480: 
15481: =item $selfenroll
15482: 
15483: =item $context
15484: 
15485: =item $credits, number of credits student will earn from this class
15486: 
15487: =item $instsec, institutional course section code for student
15488: 
15489: =back
15490: 
15491: 
15492: =item *
15493: 
15494: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
15495: custom role; give a custom role to a user for the level given by URL.  Specify
15496: name and domain of role author, and role name
15497: 
15498: =item *
15499: 
15500: revokerole($udom,$uname,$url,$role) : revoke a role for url
15501: 
15502: =item *
15503: 
15504: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
15505: 
15506: =back
15507: 
15508: =head2 Course Infomation
15509: 
15510: =over 4
15511: 
15512: =item *
15513: 
15514: coursedescription($courseid,$options) : returns a hash of information about the
15515: specified course id, including all environment settings for the
15516: course, the description of the course will be in the hash under the
15517: key 'description'
15518: 
15519: $options is an optional parameter that if supplied is a hash reference that controls
15520: what how this function works.  It has the following key/values:
15521: 
15522: =over 4
15523: 
15524: =item freshen_cache
15525: 
15526: If defined, and the environment cache for the course is valid, it is 
15527: returned in the returned hash.
15528: 
15529: =item one_time
15530: 
15531: If defined, the last cache time is set to _now_
15532: 
15533: =item user
15534: 
15535: If defined, the supplied username is used instead of the current user.
15536: 
15537: 
15538: =back
15539: 
15540: =item *
15541: 
15542: resdata($name,$domain,$type,@which) : request for current parameter
15543: setting for a specific $type, where $type is either 'course' or 'user',
15544: @what should be a list of parameters to ask about. This routine caches
15545: answers for 10 minutes.
15546: 
15547: =item *
15548: 
15549: get_courseresdata($courseid, $domain) : dump the entire course resource
15550: data base, returning a hash that is keyed by the resource name and has
15551: values that are the resource value.  I believe that the timestamps and
15552: versions are also returned.
15553: 
15554: get_numsuppfiles($cnum,$cdom) : retrieve number of files in a course's
15555: supplemental content area. This routine caches the number of files for 
15556: 10 minutes.
15557: 
15558: =back
15559: 
15560: =head2 Course Modification
15561: 
15562: =over 4
15563: 
15564: =item *
15565: 
15566: writecoursepref($courseid,%prefs) : write preferences (environment
15567: database) for a course
15568: 
15569: =item *
15570: 
15571: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
15572: 
15573: =item *
15574: 
15575: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
15576: 
15577: =item *
15578: 
15579: is_course($courseid), is_course($cdom, $cnum)
15580: 
15581: Accepts either a combined $courseid (in the form of domain_courseid) or the
15582: two component version $cdom, $cnum. It checks if the specified course exists.
15583: 
15584: Returns:
15585:     undef if the course doesn't exist, otherwise
15586:     in scalar context the combined courseid.
15587:     in list context the two components of the course identifier, domain and 
15588:     courseid.    
15589: 
15590: =back
15591: 
15592: =head2 Bubblesheet Configuration
15593: 
15594: =over 4
15595: 
15596: =item *
15597: 
15598: get_scantron_config($which)
15599: 
15600: $which - the name of the configuration to parse from the file.
15601: 
15602: Parses and returns the bubblesheet configuration line selected as a
15603: hash of configuration file fields.
15604: 
15605: 
15606: Returns:
15607:     If the named configuration is not in the file, an empty
15608:     hash is returned.
15609: 
15610:     a hash with the fields
15611:       name         - internal name for the this configuration setup
15612:       description  - text to display to operator that describes this config
15613:       CODElocation - if 0 or the string 'none'
15614:                           - no CODE exists for this config
15615:                      if -1 || the string 'letter'
15616:                           - a CODE exists for this config and is
15617:                             a string of letters
15618:                      Unsupported value (but planned for future support)
15619:                           if a positive integer
15620:                                - The CODE exists as the first n items from
15621:                                  the question section of the form
15622:                           if the string 'number'
15623:                                - The CODE exists for this config and is
15624:                                  a string of numbers
15625:       CODEstart   - (only matter if a CODE exists) column in the line where
15626:                      the CODE starts
15627:       CODElength  - length of the CODE
15628:       IDstart     - column where the student/employee ID starts
15629:       IDlength    - length of the student/employee ID info
15630:       Qstart      - column where the information from the bubbled
15631:                     'questions' start
15632:       Qlength     - number of columns comprising a single bubble line from
15633:                     the sheet. (usually either 1 or 10)
15634:       Qon         - either a single character representing the character used
15635:                     to signal a bubble was chosen in the positional setup, or
15636:                     the string 'letter' if the letter of the chosen bubble is
15637:                     in the final, or 'number' if a number representing the
15638:                     chosen bubble is in the file (1->A 0->J)
15639:       Qoff        - the character used to represent that a bubble was
15640:                     left blank
15641:       PaperID     - if the scanning process generates a unique number for each
15642:                     sheet scanned the column that this ID number starts in
15643:       PaperIDlength - number of columns that comprise the unique ID number
15644:                       for the sheet of paper
15645:       FirstName   - column that the first name starts in
15646:       FirstNameLength - number of columns that the first name spans
15647:       LastName    - column that the last name starts in
15648:       LastNameLength - number of columns that the last name spans
15649:       BubblesPerRow - number of bubbles available in each row used to
15650:                       bubble an answer. (If not specified, 10 assumed).
15651: 
15652: 
15653: =item *
15654: 
15655: get_scantronformat_file($cdom)
15656: 
15657: $cdom - the course's domain (optional); if not supplied, uses
15658: domain for current $env{'request.course.id'}.
15659: 
15660: Returns an array containing lines from the scantron format file for
15661: the domain of the course.
15662: 
15663: If a url for a custom.tab file is listed in domain's configuration.db,
15664: lines are from this file.
15665: 
15666: Otherwise, if a default.tab has been published in RES space by the
15667: domainconfig user, lines are from this file.
15668: 
15669: Otherwise, fall back to getting lines from the legacy file on the
15670: local server:  /home/httpd/lonTabs/default_scantronformat.tab
15671: 
15672: =back
15673: 
15674: =head2 Resource Subroutines
15675: 
15676: =over 4
15677: 
15678: =item *
15679: 
15680: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
15681: 
15682: =item *
15683: 
15684: repcopy($filename) : subscribes to the requested file, and attempts to
15685: replicate from the owning library server, Might return
15686: 'unavailable', 'not_found', 'forbidden', 'ok', or
15687: 'bad_request', also attempts to grab the metadata for the
15688: resource. Expects the local filesystem pathname
15689: (/home/httpd/html/res/....)
15690: 
15691: =back
15692: 
15693: =head2 Resource Information
15694: 
15695: =over 4
15696: 
15697: =item *
15698: 
15699: EXT($varname,$symb,$udom,$uname,$usection,$recurse,$cid) : evaluates 
15700: and returns the value of a variety of different possible values,
15701: $varname should be a request string, and the other parameters can be
15702: used to specify who and what one is asking about. Ordinarily, $cid 
15703: does not need to be specified, as it is retrived from 
15704: $env{'request.course.id'}, but &Apache::lonnet::EXT() is called
15705: within lonuserstate::loadmap() when initializing a course, before
15706: $env{'request.course.id'} has been set, so it needs to be provided
15707: in that one case.
15708: 
15709: Possible values for $varname are environment.lastname (or other item
15710: from the envirnment hash), user.name (or someother aspect about the
15711: user), resource.0.maxtries (or some other part and parameter of a
15712: resource)
15713: 
15714: =item *
15715: 
15716: directcondval($number) : get current value of a condition; reads from a state
15717: string
15718: 
15719: =item *
15720: 
15721: condval($condidx) : value of condition index based on state
15722: 
15723: =item *
15724: 
15725: metadata($uri,$what,$toolsymb,$liburi,$prefix,$depthcount) : request a
15726: resource's metadata, $what should be either a specific key, or either
15727: 'keys' (to get a list of possible keys) or 'packages' to get a list of
15728: packages that this resource currently uses, the last 3 arguments are 
15729: only used internally for recursive metadata.
15730: 
15731: the toolsymb is only used where the uri is for an external tool (for which
15732: the uri as well as the symb are guaranteed to be unique).
15733: 
15734: this function automatically caches all requests except any made recursively
15735: to retrieve a list of metadata keys for an imported library file ($liburi is 
15736: defined).
15737: 
15738: =item *
15739: 
15740: metadata_query($query,$custom,$customshow) : make a metadata query against the
15741: network of library servers; returns file handle of where SQL and regex results
15742: will be stored for query
15743: 
15744: =item *
15745: 
15746: symbread($filename,$donotrecurse,$ignorecachednull,$checkforblock,$possibles) : 
15747: return symbolic list entry (all arguments optional). 
15748: 
15749: Args: filename is the filename (including path) for the file for which a symb 
15750: is required; donotrecurse, if true will prevent calls to allowed() being made 
15751: to check access status if more than one resource was found in the bighash 
15752: (see rev. 1.249) to avoid an infinite loop if an ambiguous resource is part of 
15753: a randompick); ignorecachednull, if true will prevent a symb of '' being 
15754: returned if $env{$cache_str} is defined as ''; checkforblock if true will
15755: cause possible symbs to be checked to determine if they are subject to content
15756: blocking, if so they will not be included as possible symbs; possibles is a
15757: ref to a hash, which, as a side effect, will be populated with all possible 
15758: symbs (content blocking not tested).
15759:  
15760: returns the data handle
15761: 
15762: =item *
15763: 
15764: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
15765: and is a possible symb for the URL in $thisfn, and if is an encrypted
15766: resource that the user accessed using /enc/ returns a 1 on success, 0
15767: on failure, user must be in a course, as it assumes the existence of
15768: the course initial hash, and uses $env('request.course.id'}.  The third
15769: arg is an optional reference to a scalar.  If this arg is passed in the 
15770: call to symbverify, it will be set to 1 if the symb has been set to be 
15771: encrypted; otherwise it will be null.  
15772: 
15773: =item *
15774: 
15775: symbclean($symb) : removes versions numbers from a symb, returns the
15776: cleaned symb
15777: 
15778: =item *
15779: 
15780: is_on_map($uri) : checks if the $uri is somewhere on the current
15781: course map, user must be in a course for it to work.
15782: 
15783: =item *
15784: 
15785: numval($salt) : return random seed value (addend for rndseed)
15786: 
15787: =item *
15788: 
15789: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
15790: a random seed, all arguments are optional, if they aren't sent it uses the
15791: environment to derive them. Note: if symb isn't sent and it can't get one
15792: from &symbread it will use the current time as its return value
15793: 
15794: =item *
15795: 
15796: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
15797: unfakeable, receipt
15798: 
15799: =item *
15800: 
15801: receipt() : API to ireceipt working off of env values; given out to users
15802: 
15803: =item *
15804: 
15805: countacc($url) : count the number of accesses to a given URL
15806: 
15807: =item *
15808: 
15809: 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
15810: 
15811: =item *
15812: 
15813: 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)
15814: 
15815: =item *
15816: 
15817: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
15818: 
15819: =item *
15820: 
15821: devalidate($symb) : devalidate temporary spreadsheet calculations,
15822: forcing spreadsheet to reevaluate the resource scores next time.
15823: 
15824: =item * 
15825: 
15826: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
15827: when viewing in course context.
15828: 
15829:  input: six args -- filename (decluttered), course number, course domain,
15830:                     url, symb (if registered) and group (if this is a 
15831:                     group item -- e.g., bulletin board, group page etc.).
15832: 
15833:  output: array of five scalars --
15834:          $cfile -- url for file editing if editable on current server
15835:          $home -- homeserver of resource (i.e., for author if published,
15836:                                           or course if uploaded.).
15837:          $switchserver --  1 if server switch will be needed.
15838:          $forceedit -- 1 if icon/link should be to go to edit mode 
15839:          $forceview -- 1 if icon/link should be to go to view mode
15840: 
15841: =item *
15842: 
15843: is_course_upload($file,$cnum,$cdom)
15844: 
15845: Used in course context to determine if current file was uploaded to 
15846: the course (i.e., would be found in /userfiles/docs on the course's 
15847: homeserver.
15848: 
15849:   input: 3 args -- filename (decluttered), course number and course domain.
15850:   output: boolean -- 1 if file was uploaded.
15851: 
15852: =back
15853: 
15854: =head2 Storing/Retreiving Data
15855: 
15856: =over 4
15857: 
15858: =item *
15859: 
15860: store($storehash,$symb,$namespace,$udom,$uname,$laststore) : stores hash
15861: permanently for this url; hashref needs to be given and should be a \%hashname;
15862: the remaining args aren't required and if they aren't passed or are '' they will
15863: be derived from the env (with the exception of $laststore, which is an 
15864: optional arg used when a user's submission is stored in grading).
15865: $laststore is $version=$timestamp, where $version is the most recent version
15866: number retrieved for the corresponding $symb in the $namespace db file, and
15867: $timestamp is the timestamp for that transaction (UNIX time).
15868: $laststore is currently only passed when cstore() is called by 
15869: structuretags::finalize_storage().
15870: 
15871: =item *
15872: 
15873: cstore($storehash,$symb,$namespace,$udom,$uname,$laststore) : same as store
15874: but uses critical subroutine
15875: 
15876: =item *
15877: 
15878: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
15879: all args are optional
15880: 
15881: =item *
15882: 
15883: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
15884: dumps the complete (or key matching regexp) namespace into a hash
15885: ($udom, $uname, $regexp, $range are optional) for a namespace that is
15886: normally &store()ed into
15887: 
15888: $range should be either an integer '100' (give me the first 100
15889:                                            matching records)
15890:               or be  two integers sperated by a - with no spaces
15891:                  '30-50' (give me the 30th through the 50th matching
15892:                           records)
15893: 
15894: 
15895: =item *
15896: 
15897: putstore($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog) :
15898: replaces a &store() version of data with a replacement set of data
15899: for a particular resource in a namespace passed in the $storehash hash 
15900: reference. If $tolog is true, the transaction is logged in the courselog
15901: with an action=PUTSTORE.
15902: 
15903: =item *
15904: 
15905: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
15906: works very similar to store/cstore, but all data is stored in a
15907: temporary location and can be reset using tmpreset, $storehash should
15908: be a hash reference, returns nothing on success
15909: 
15910: =item *
15911: 
15912: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
15913: similar to restore, but all data is stored in a temporary location and
15914: can be reset using tmpreset. Returns a hash of values on success,
15915: error string otherwise.
15916: 
15917: =item *
15918: 
15919: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
15920: deltes all keys for $symb form the temporary storage hash.
15921: 
15922: =item *
15923: 
15924: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
15925: reference filled in from namesp ($udom and $uname are optional)
15926: 
15927: =item *
15928: 
15929: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
15930: namesp ($udom and $uname are optional)
15931: 
15932: =item *
15933: 
15934: dump($namespace,$udom,$uname,$regexp,$range) : 
15935: dumps the complete (or key matching regexp) namespace into a hash
15936: ($udom, $uname, $regexp, $range are optional)
15937: 
15938: $range should be either an integer '100' (give me the first 100
15939:                                            matching records)
15940:               or be  two integers sperated by a - with no spaces
15941:                  '30-50' (give me the 30th through the 50th matching
15942:                           records)
15943: =item *
15944: 
15945: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
15946: $store can be a scalar, an array reference, or if the amount to be 
15947: incremented is > 1, a hash reference.
15948: 
15949: ($udom and $uname are optional)
15950: 
15951: =item *
15952: 
15953: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
15954: ($udom and $uname are optional)
15955: 
15956: =item *
15957: 
15958: cput($namespace,$storehash,$udom,$uname) : critical put
15959: ($udom and $uname are optional)
15960: 
15961: =item *
15962: 
15963: newput($namespace,$storehash,$udom,$uname) :
15964: 
15965: Attempts to store the items in the $storehash, but only if they don't
15966: currently exist, if this succeeds you can be certain that you have 
15967: successfully created a new key value pair in the $namespace db.
15968: 
15969: 
15970: Args:
15971:  $namespace: name of database to store values to
15972:  $storehash: hashref to store to the db
15973:  $udom: (optional) domain of user containing the db
15974:  $uname: (optional) name of user caontaining the db
15975: 
15976: Returns:
15977:  'ok' -> succeeded in storing all keys of $storehash
15978:  'key_exists: <key>' -> failed to anything out of $storehash, as at
15979:                         least <key> already existed in the db (other
15980:                         requested keys may also already exist)
15981:  'error: <msg>' -> unable to tie the DB or other error occurred
15982:  'con_lost' -> unable to contact request server
15983:  'refused' -> action was not allowed by remote machine
15984: 
15985: 
15986: =item *
15987: 
15988: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
15989: reference filled in from namesp (encrypts the return communication)
15990: ($udom and $uname are optional)
15991: 
15992: =item *
15993: 
15994: log($udom,$name,$home,$message) : write to permanent log for user; use
15995: critical subroutine
15996: 
15997: =item *
15998: 
15999: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
16000: array reference filled in from namespace found in domain level on either
16001: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
16002: 
16003: =item *
16004: 
16005: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
16006: domain level either on specified domain server ($uhome) or primary domain 
16007: server ($udom and $uhome are optional)
16008: 
16009: =item * 
16010: 
16011: get_domain_defaults($target_domain,$ignore_cache) : returns hash with defaults 
16012: for: authentication, language, quotas, timezone, date locale, and portal URL in
16013: the target domain.
16014: 
16015: May also include additional key => value pairs for the following groups:
16016: 
16017: =over
16018: 
16019: =item
16020: disk quotas (MB allocated by default to portfolios and authoring spaces).
16021: 
16022: =over
16023: 
16024: =item defaultquota, authorquota
16025: 
16026: =back
16027: 
16028: =item
16029: tools (availability of aboutme page, blog, webDAV access for authoring spaces,
16030: portfolio for users).
16031: 
16032: =over
16033: 
16034: =item
16035: aboutme, blog, webdav, portfolio
16036: 
16037: =back
16038: 
16039: =item
16040: requestcourses: ability to request courses, and how requests are processed.
16041: 
16042: =over
16043: 
16044: =item
16045: official, unofficial, community, textbook, placement
16046: 
16047: =back
16048: 
16049: =item
16050: inststatus: types of institutional affiliation, and order in which they are displayed.
16051: 
16052: =over
16053: 
16054: =item
16055: inststatustypes, inststatusorder, inststatusguest
16056: 
16057: =back
16058: 
16059: =item
16060: coursedefaults: can PDF forms can be created, default credits for courses, default quotas (MB)
16061: for course's uploaded content.
16062: 
16063: =over
16064: 
16065: =item
16066: canuse_pdfforms, officialcredits, unofficialcredits, textbookcredits, officialquota, unofficialquota, 
16067: communityquota, textbookquota, placementquota
16068: 
16069: =back
16070: 
16071: =item
16072: usersessions: set options for hosting of your users in other domains, and hosting of users from other domains
16073: on your servers.
16074: 
16075: =over
16076: 
16077: =item 
16078: remotesessions, hostedsessions
16079: 
16080: =back
16081: 
16082: =back
16083: 
16084: In cases where a domain coordinator has never used the "Set Domain Configuration"
16085: utility to create a configuration.db file on a domain's primary library server 
16086: only the following domain defaults: auth_def, auth_arg_def, lang_def
16087: -- corresponding values are authentication type (internal, krb4, krb5,
16088: or localauth), initial password or a kerberos realm, language (e.g., en-us) -- 
16089: will be available. Values are retrieved from cache (if current), unless the
16090: optional $ignore_cache arg is true, or from domain's configuration.db (if available),
16091: or lastly from values in lonTabs/dns_domain,tab, or lonTabs/domain.tab.
16092: 
16093: Typical usage:
16094: 
16095: %domdefaults = &get_domain_defaults($target_domain);
16096: 
16097: =back
16098: 
16099: =head2 Network Status Functions
16100: 
16101: =over 4
16102: 
16103: =item *
16104: 
16105: dirlist() : return directory list based on URI (first arg).
16106: 
16107: Inputs: 1 required, 5 optional.
16108: 
16109: =over
16110: 
16111: =item 
16112: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
16113: 
16114: =item
16115: $userdomain - domain of user/course to be listed. Extracted from $uri if absent. 
16116: 
16117: =item
16118: $username -  username of user/course to be listed. Extracted from $uri if absent. 
16119: 
16120: =item
16121: $getpropath - boolean: 1 if prepend path using &propath(). 
16122: 
16123: =item
16124: $getuserdir - boolean: 1 if prepend path for "userfiles".
16125: 
16126: =item 
16127: $alternateRoot - path to prepend in place of path from $uri.
16128: 
16129: =back
16130: 
16131: Returns: Array of up to two items.
16132: 
16133: =over
16134: 
16135: a reference to an array of files/subdirectories
16136: 
16137: =over
16138: 
16139: Each element in the array of files/subdirectories is a & separated list of
16140: item name and the result of running stat on the item.  If dirlist was requested
16141: for a file instead of a directory, the item name will be ''. For a directory 
16142: listing, if the item is a metadata file, the element will end &N&M 
16143: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
16144: default copyright set (1).  
16145: 
16146: =back
16147: 
16148: a scalar containing error condition (if encountered).
16149: 
16150: =over
16151: 
16152: =item 
16153: no_host (no homeserver identified for $username:$domain).
16154: 
16155: =item 
16156: no_such_host (server contacted for listing not identified as valid host).
16157: 
16158: =item 
16159: con_lost (connection to remote server failed).
16160: 
16161: =item 
16162: refused (invalid $username:$domain received on lond side).
16163: 
16164: =item 
16165: no_such_dir (directory at specified path on lond side does not exist). 
16166: 
16167: =item 
16168: empty (directory at specified path on lond side is empty).
16169: 
16170: =over
16171: 
16172: This is currently not encountered because the &ls3, &ls2, 
16173: &ls (_handler) routines on the lond side do not filter out
16174: . and .. from a directory listing. 
16175: 
16176: =back
16177: 
16178: =back
16179: 
16180: =back
16181: 
16182: =item *
16183: 
16184: spareserver() : find server with least workload from spare.tab
16185: 
16186: 
16187: =item *
16188: 
16189: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
16190: if there is no corresponding loncapa host.
16191: 
16192: =back
16193: 
16194: 
16195: =head2 Apache Request
16196: 
16197: =over 4
16198: 
16199: =item *
16200: 
16201: ssi($url,%hash) : server side include, does a complete request cycle on url to
16202: localhost, posts hash
16203: 
16204: =back
16205: 
16206: =head2 Data to String to Data
16207: 
16208: =over 4
16209: 
16210: =item *
16211: 
16212: hash2str(%hash) : convert a hash into a string complete with escaping and '='
16213: and '&' separators, supports elements that are arrayrefs and hashrefs
16214: 
16215: =item *
16216: 
16217: hashref2str($hashref) : convert a hashref into a string complete with
16218: escaping and '=' and '&' separators, supports elements that are
16219: arrayrefs and hashrefs
16220: 
16221: =item *
16222: 
16223: arrayref2str($arrayref) : convert an arrayref into a string complete
16224: with escaping and '&' separators, supports elements that are arrayrefs
16225: and hashrefs
16226: 
16227: =item *
16228: 
16229: str2hash($string) : convert string to hash using unescaping and
16230: splitting on '=' and '&', supports elements that are arrayrefs and
16231: hashrefs
16232: 
16233: =item *
16234: 
16235: str2array($string) : convert string to hash using unescaping and
16236: splitting on '&', supports elements that are arrayrefs and hashrefs
16237: 
16238: =back
16239: 
16240: =head2 Logging Routines
16241: 
16242: 
16243: These routines allow one to make log messages in the lonnet.log and
16244: lonnet.perm logfiles.
16245: 
16246: =over 4
16247: 
16248: =item *
16249: 
16250: logtouch() : make sure the logfile, lonnet.log, exists
16251: 
16252: =item *
16253: 
16254: logthis() : append message to the normal lonnet.log file, it gets
16255: preiodically rolled over and deleted.
16256: 
16257: =item *
16258: 
16259: logperm() : append a permanent message to lonnet.perm.log, this log
16260: file never gets deleted by any automated portion of the system, only
16261: messages of critical importance should go in here.
16262: 
16263: 
16264: =back
16265: 
16266: =head2 General File Helper Routines
16267: 
16268: =over 4
16269: 
16270: =item *
16271: 
16272: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
16273: (a) files in /uploaded
16274:   (i) If a local copy of the file exists - 
16275:       compares modification date of local copy with last-modified date for 
16276:       definitive version stored on home server for course. If local copy is 
16277:       stale, requests a new version from the home server and stores it. 
16278:       If the original has been removed from the home server, then local copy 
16279:       is unlinked.
16280:   (ii) If local copy does not exist -
16281:       requests the file from the home server and stores it. 
16282:   
16283:   If $caller is 'uploadrep':  
16284:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
16285:     for request for files originally uploaded via DOCS. 
16286:      - returns 'ok' if fresh local copy now available, -1 otherwise.
16287:   
16288:   Otherwise:
16289:      This indicates a call from the content generation phase of the request.
16290:      -  returns the entire contents of the file or -1.
16291:      
16292: (b) files in /res
16293:    - returns the entire contents of a file or -1; 
16294:    it properly subscribes to and replicates the file if neccessary.
16295: 
16296: 
16297: =item *
16298: 
16299: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
16300:                   reference
16301: 
16302: returns either a stat() list of data about the file or an empty list
16303: if the file doesn't exist or couldn't find out about it (connection
16304: problems or user unknown)
16305: 
16306: =item *
16307: 
16308: filelocation($dir,$file) : returns file system location of a file
16309: based on URI; meant to be "fairly clean" absolute reference, $dir is a
16310: directory that relative $file lookups are to looked in ($dir of /a/dir
16311: and a file of ../bob will become /a/bob)
16312: 
16313: =item *
16314: 
16315: hreflocation($dir,$file) : returns file system location or a URL; same as
16316: filelocation except for hrefs
16317: 
16318: =item *
16319: 
16320: declutter() : declutters URLs -- remove beginning slashes, 'res' etc.
16321: also removes beginning /home/httpd/html unless /priv/ follows it.
16322: 
16323: =back
16324: 
16325: =head2 Usererfile file routines (/uploaded*)
16326: 
16327: =over 4
16328: 
16329: =item *
16330: 
16331: userfileupload(): main rotine for putting a file in a user or course's
16332:                   filespace, arguments are,
16333: 
16334:  formname - required - this is the name of the element in $env where the
16335:            filename, and the contents of the file to create/modifed exist
16336:            the filename is in $env{'form.'.$formname.'.filename'} and the
16337:            contents of the file is located in $env{'form.'.$formname}
16338:  context - if coursedoc, store the file in the course of the active role
16339:              of the current user; 
16340:            if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
16341:            if 'canceloverwrite': delete file in tmp/overwrites directory
16342:  subdir - required - subdirectory to put the file in under ../userfiles/
16343:          if undefined, it will be placed in "unknown"
16344: 
16345:  (This routine calls clean_filename() to remove any dangerous
16346:  characters from the filename, and then calls finuserfileupload() to
16347:  complete the transaction)
16348: 
16349:  returns either the url of the uploaded file (/uploaded/....) if successful
16350:  and /adm/notfound.html if unsuccessful
16351: 
16352: =item *
16353: 
16354: clean_filename(): routine for cleaing a filename up for storage in
16355:                  userfile space, argument is:
16356: 
16357:  filename - proposed filename
16358: 
16359: returns: the new clean filename
16360: 
16361: =item *
16362: 
16363: finishuserfileupload(): routine that creates and sends the file to
16364: userspace, probably shouldn't be called directly
16365: 
16366:   docuname: username or courseid of destination for the file
16367:   docudom: domain of user/course of destination for the file
16368:   formname: same as for userfileupload()
16369:   fname: filename (including subdirectories) for the file
16370:   parser: if 'parse', will parse (html) file to extract references to objects, links etc.
16371:           if hashref, and context is scantron, will convert csv format to standard format
16372:   allfiles: reference to hash used to store objects found by parser
16373:   codebase: reference to hash used for codebases of java objects found by parser
16374:   thumbwidth: width (pixels) of thumbnail to be created for uploaded image
16375:   thumbheight: height (pixels) of thumbnail to be created for uploaded image
16376:   resizewidth: width to be used to resize image using resizeImage from ImageMagick
16377:   resizeheight: height to be used to resize image using resizeImage from ImageMagick
16378:   context: if 'overwrite', will move the uploaded file from its temporary location to
16379:             userfiles to facilitate overwriting a previously uploaded file with same name.
16380:   mimetype: reference to scalar to accommodate mime type determined
16381:             from File::MMagic if $parser = parse.
16382: 
16383:  returns either the url of the uploaded file (/uploaded/....) if successful
16384:  and /adm/notfound.html if unsuccessful (or an error message if context 
16385:  was 'overwrite').
16386:  
16387: 
16388: =item *
16389: 
16390: renameuserfile(): renames an existing userfile to a new name
16391: 
16392:   Args:
16393:    docuname: username or courseid of destination for the file
16394:    docudom: domain of user/course of destination for the file
16395:    old: current file name (including any subdirs under userfiles)
16396:    new: desired file name (including any subdirs under userfiles)
16397: 
16398: =item *
16399: 
16400: mkdiruserfile(): creates a directory is a userfiles dir
16401: 
16402:   Args:
16403:    docuname: username or courseid of destination for the file
16404:    docudom: domain of user/course of destination for the file
16405:    dir: dir to create (including any subdirs under userfiles)
16406: 
16407: =item *
16408: 
16409: removeuserfile(): removes a file that exists in userfiles
16410: 
16411:   Args:
16412:    docuname: username or courseid of destination for the file
16413:    docudom: domain of user/course of destination for the file
16414:    fname: filname to delete (including any subdirs under userfiles)
16415: 
16416: =item *
16417: 
16418: removeuploadedurl(): convience function for removeuserfile()
16419: 
16420:   Args:
16421:    url:  a full /uploaded/... url to delete
16422: 
16423: =item * 
16424: 
16425: get_portfile_permissions():
16426:   Args:
16427:     domain: domain of user or course contain the portfolio files
16428:     user: name of user or num of course contain the portfolio files
16429:   Returns:
16430:     hashref of a dump of the proper file_permissions.db
16431:    
16432: 
16433: =item * 
16434: 
16435: get_access_controls():
16436: 
16437: Args:
16438:   current_permissions: the hash ref returned from get_portfile_permissions()
16439:   group: (optional) the group you want the files associated with
16440:   file: (optional) the file you want access info on
16441: 
16442: Returns:
16443:     a hash (keys are file names) of hashes containing
16444:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
16445:         values are XML containing access control settings (see below) 
16446: 
16447: Internal notes:
16448: 
16449:  access controls are stored in file_permissions.db as key=value pairs.
16450:     key -> path to file/file_name\0uniqueID:scope_end_start
16451:         where scope -> public,guest,course,group,domains or users.
16452:               end -> UNIX time for end of access (0 -> no end date)
16453:               start -> UNIX time for start of access
16454: 
16455:     value -> XML description of access control
16456:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
16457:             <start></start>
16458:             <end></end>
16459: 
16460:             <password></password>  for scope type = guest
16461: 
16462:             <domain></domain>     for scope type = course or group
16463:             <number></number>
16464:             <roles id="">
16465:              <role></role>
16466:              <access></access>
16467:              <section></section>
16468:              <group></group>
16469:             </roles>
16470: 
16471:             <dom></dom>         for scope type = domains
16472: 
16473:             <users>             for scope type = users
16474:              <user>
16475:               <uname></uname>
16476:               <udom></udom>
16477:              </user>
16478:             </users>
16479:            </scope> 
16480:               
16481:  Access data is also aggregated for each file in an additional key=value pair:
16482:  key -> path to file/file_name\0accesscontrol 
16483:  value -> reference to hash
16484:           hash contains key = value pairs
16485:           where key = uniqueID:scope_end_start
16486:                 value = UNIX time record was last updated
16487: 
16488:           Used to improve speed of look-ups of access controls for each file.  
16489:  
16490:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
16491: 
16492: =item *
16493: 
16494: modify_access_controls():
16495: 
16496: Modifies access controls for a portfolio file
16497: Args
16498: 1. file name
16499: 2. reference to hash of required changes,
16500: 3. domain
16501: 4. username
16502:   where domain,username are the domain of the portfolio owner 
16503:   (either a user or a course) 
16504: 
16505: Returns:
16506: 1. result of additions or updates ('ok' or 'error', with error message). 
16507: 2. result of deletions ('ok' or 'error', with error message).
16508: 3. reference to hash of any new or updated access controls.
16509: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
16510:    key = integer (inbound ID)
16511:    value = uniqueID
16512: 
16513: =item *
16514: 
16515: get_timebased_id():
16516: 
16517: Attempts to get a unique timestamp-based suffix for use with items added to a 
16518: course via the Course Editor (e.g., folders, composite pages, 
16519: group bulletin boards).
16520: 
16521: Args: (first three required; six others optional)
16522: 
16523: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
16524:    docssequence, or name of group
16525: 
16526: 2. keyid (alphanumeric): name of temporary locking key in hash,
16527:    e.g., num, boardids
16528: 
16529: 3. namespace: name of gdbm file used to store suffixes already assigned;  
16530:    file will be named nohist_namespace.db
16531: 
16532: 4. cdom: domain of course; default is current course domain from %env
16533: 
16534: 5. cnum: course number; default is current course number from %env
16535: 
16536: 6. idtype: set to concat if an additional digit is to be appended to the 
16537:    unix timestamp to form the suffix, if the plain timestamp is already
16538:    in use.  Default is to not do this, but simply increment the unix 
16539:    timestamp by 1 until a unique key is obtained.
16540: 
16541: 7. who: holder of locking key; defaults to user:domain for user.
16542: 
16543: 8. locktries: number of attempts to obtain a lock (sleep of 1s before 
16544:    retrying); default is 3.
16545: 
16546: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.  
16547: 
16548: Returns:
16549: 
16550: 1. suffix obtained (numeric)
16551: 
16552: 2. result of deleting locking key (ok if deleted, or lock never obtained)
16553: 
16554: 3. error: contains (localized) error message if an error occurred.
16555: 
16556: 
16557: =back
16558: 
16559: =head2 HTTP Helper Routines
16560: 
16561: =over 4
16562: 
16563: =item *
16564: 
16565: escape() : unpack non-word characters into CGI-compatible hex codes
16566: 
16567: =item *
16568: 
16569: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
16570: 
16571: =back
16572: 
16573: =head1 PRIVATE SUBROUTINES
16574: 
16575: =head2 Underlying communication routines (Shouldn't call)
16576: 
16577: =over 4
16578: 
16579: =item *
16580: 
16581: subreply() : tries to pass a message to lonc, returns con_lost if incapable
16582: 
16583: =item *
16584: 
16585: reply() : uses subreply to send a message to remote machine, logs all failures
16586: 
16587: =item *
16588: 
16589: critical() : passes a critical message to another server; if cannot
16590: get through then place message in connection buffer directory and
16591: returns con_delayed, if incapable of saving message, returns
16592: con_failed
16593: 
16594: =item *
16595: 
16596: reconlonc() : tries to reconnect lonc client processes.
16597: 
16598: =back
16599: 
16600: =head2 Resource Access Logging
16601: 
16602: =over 4
16603: 
16604: =item *
16605: 
16606: flushcourselogs() : flush (save) buffer logs and access logs
16607: 
16608: =item *
16609: 
16610: courselog($what) : save message for course in hash
16611: 
16612: =item *
16613: 
16614: courseacclog($what) : save message for course using &courselog().  Perform
16615: special processing for specific resource types (problems, exams, quizzes, etc).
16616: 
16617: =item *
16618: 
16619: goodbye() : flush course logs and log shutting down; it is called in srm.conf
16620: as a PerlChildExitHandler
16621: 
16622: =back
16623: 
16624: =head2 Other
16625: 
16626: =over 4
16627: 
16628: =item *
16629: 
16630: symblist($mapname,%newhash) : update symbolic storage links
16631: 
16632: =back
16633: 
16634: =cut
16635: 

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