File:  [LON-CAPA] / loncom / lonnet / perl / lonnet.pm
Revision 1.1402: download - view: text, annotated - select for diffs
Sun Jan 27 16:02:58 2019 UTC (5 years, 5 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Bug 6400
  - Enforce access restrictions for content which is deeplink-only (users
    with "advanced priv for current role are exempt).
  - Support "key" link type in deeplink parameter (requested link must either
    be sent with linkkey as element in POSTed data, or with linkkey in query
    string).  Corresponding value must match key set in deeplink parameter.

    1: # The LearningOnline Network
    2: # TCP networking package
    3: #
    4: # $Id: lonnet.pm,v 1.1402 2019/01/27 16:02: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
   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: 
  105: use File::Copy;
  106: 
  107: my $readit;
  108: my $max_connection_retries = 20;     # Or some such value.
  109: 
  110: require Exporter;
  111: 
  112: our @ISA = qw (Exporter);
  113: our @EXPORT = qw(%env);
  114: 
  115: 
  116: # ------------------------------------ Logging (parameters, docs, slots, roles)
  117: {
  118:     my $logid;
  119:     sub write_log {
  120: 	my ($context,$hash_name,$storehash,$delflag,$uname,$udom,$cnum,$cdom)=@_;
  121:         if ($context eq 'course') {
  122:             if (($cnum eq '') || ($cdom eq '')) {
  123:                 $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
  124:                 $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
  125:             }
  126:         }
  127: 	$logid ++;
  128:         my $now = time();
  129: 	my $id=$now.'00000'.$$.'00000'.$logid;
  130:         my $logentry = { 
  131:                           $id => {
  132:                                    'exe_uname' => $env{'user.name'},
  133:                                    'exe_udom'  => $env{'user.domain'},
  134:                                    'exe_time'  => $now,
  135:                                    'exe_ip'    => $ENV{'REMOTE_ADDR'},
  136:                                    'delflag'   => $delflag,
  137:                                    'logentry'  => $storehash,
  138:                                    'uname'     => $uname,
  139:                                    'udom'      => $udom,
  140:                                   }
  141:                        };
  142: 	return &put('nohist_'.$hash_name,$logentry,$cdom,$cnum);
  143:     }
  144: }
  145: 
  146: sub logtouch {
  147:     my $execdir=$perlvar{'lonDaemons'};
  148:     unless (-e "$execdir/logs/lonnet.log") {	
  149: 	open(my $fh,">>","$execdir/logs/lonnet.log");
  150: 	close $fh;
  151:     }
  152:     my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
  153:     chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
  154: }
  155: 
  156: sub logthis {
  157:     my $message=shift;
  158:     my $execdir=$perlvar{'lonDaemons'};
  159:     my $now=time;
  160:     my $local=localtime($now);
  161:     if (open(my $fh,">>","$execdir/logs/lonnet.log")) {
  162: 	my $logstring = $local. " ($$): ".$message."\n"; # Keep any \'s in string.
  163: 	print $fh $logstring;
  164: 	close($fh);
  165:     }
  166:     return 1;
  167: }
  168: 
  169: sub logperm {
  170:     my $message=shift;
  171:     my $execdir=$perlvar{'lonDaemons'};
  172:     my $now=time;
  173:     my $local=localtime($now);
  174:     if (open(my $fh,">>","$execdir/logs/lonnet.perm.log")) {
  175: 	print $fh "$now:$message:$local\n";
  176: 	close($fh);
  177:     }
  178:     return 1;
  179: }
  180: 
  181: sub create_connection {
  182:     my ($hostname,$lonid) = @_;
  183:     my $client=IO::Socket::UNIX->new(Peer    => $perlvar{'lonSockCreate'},
  184: 				     Type    => SOCK_STREAM,
  185: 				     Timeout => 10);
  186:     return 0 if (!$client);
  187:     print $client (join(':',$hostname,$lonid,&machine_ids($hostname),$loncaparevs{$lonid})."\n");
  188:     my $result = <$client>;
  189:     chomp($result);
  190:     return 1 if ($result eq 'done');
  191:     return 0;
  192: }
  193: 
  194: sub get_server_timezone {
  195:     my ($cnum,$cdom) = @_;
  196:     my $home=&homeserver($cnum,$cdom);
  197:     if ($home ne 'no_host') {
  198:         my $cachetime = 24*3600;
  199:         my ($timezone,$cached)=&is_cached_new('servertimezone',$home);
  200:         if (defined($cached)) {
  201:             return $timezone;
  202:         } else {
  203:             my $timezone = &reply('servertimezone',$home);
  204:             return &do_cache_new('servertimezone',$home,$timezone,$cachetime);
  205:         }
  206:     }
  207: }
  208: 
  209: sub get_server_distarch {
  210:     my ($lonhost,$ignore_cache) = @_;
  211:     if (defined($lonhost)) {
  212:         if (!defined(&hostname($lonhost))) {
  213:             return;
  214:         }
  215:         my $cachetime = 12*3600;
  216:         if (!$ignore_cache) {
  217:             my ($distarch,$cached)=&is_cached_new('serverdistarch',$lonhost);
  218:             if (defined($cached)) {
  219:                 return $distarch;
  220:             }
  221:         }
  222:         my $rep = &reply('serverdistarch',$lonhost);
  223:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
  224:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
  225:                 $rep eq '') {
  226:             return &do_cache_new('serverdistarch',$lonhost,$rep,$cachetime);
  227:         }
  228:     }
  229:     return;
  230: }
  231: 
  232: sub get_servercerts_info {
  233:     my ($lonhost,$hostname,$context) = @_;
  234:     return if ($lonhost eq '');
  235:     if ($hostname eq '') {
  236:         $hostname = &hostname($lonhost);
  237:     }
  238:     return if ($hostname eq '');
  239:     my ($rep,$uselocal);
  240:     if ($context eq 'install') {
  241:         $uselocal = 1;
  242:     } elsif (grep { $_ eq $lonhost } &current_machine_ids()) {
  243:         $uselocal = 1;
  244:     }
  245:     if (($context ne 'cgi') && ($context ne 'install') && ($uselocal)) {
  246:         my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
  247:         if ($distro eq '') {
  248:             $uselocal = 0;
  249:         } elsif ($distro =~ /^(?:centos|redhat|scientific)(\d+)$/) {
  250:             if ($1 < 6) {
  251:                 $uselocal = 0;
  252:             }
  253:         }  elsif ($distro =~ /^(?:sles)(\d+)$/) {
  254:             if ($1 < 12) {
  255:                 $uselocal = 0;
  256:             }
  257:         }
  258:     }
  259:     if ($uselocal) {
  260:         $rep = LONCAPA::Lond::server_certs(\%perlvar,$lonhost,$hostname);
  261:     } else {
  262:         $rep=&reply('servercerts',$lonhost);
  263:     }
  264:     my ($result,%returnhash);
  265:     if (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
  266:         ($rep eq 'unknown_cmd')) {
  267:         $result = $rep;
  268:     } else {
  269:         $result = 'ok';
  270:         my @pairs=split(/\&/,$rep);
  271:         foreach my $item (@pairs) {
  272:             my ($key,$value)=split(/=/,$item,2);
  273:             my $what = &unescape($key);
  274:             $returnhash{$what}=&thaw_unescape($value);
  275:         }
  276:     }
  277:     return ($result,\%returnhash);
  278: }
  279: 
  280: sub get_server_loncaparev {
  281:     my ($dom,$lonhost,$ignore_cache,$caller) = @_;
  282:     if (defined($lonhost)) {
  283:         if (!defined(&hostname($lonhost))) {
  284:             undef($lonhost);
  285:         }
  286:     }
  287:     if (!defined($lonhost)) {
  288:         if (defined(&domain($dom,'primary'))) {
  289:             $lonhost=&domain($dom,'primary');
  290:             if ($lonhost eq 'no_host') {
  291:                 undef($lonhost);
  292:             }
  293:         }
  294:     }
  295:     if (defined($lonhost)) {
  296:         my $cachetime = 12*3600;
  297:         if (!$ignore_cache) {
  298:             my ($loncaparev,$cached)=&is_cached_new('serverloncaparev',$lonhost);
  299:             if (defined($cached)) {
  300:                 return $loncaparev;
  301:             }
  302:         }
  303:         my ($answer,$loncaparev);
  304:         my @ids=&current_machine_ids();
  305:         if (grep(/^\Q$lonhost\E$/,@ids)) {
  306:             $answer = $perlvar{'lonVersion'};
  307:             if ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
  308:                 $loncaparev = $1;
  309:             }
  310:         } else {
  311:             $answer = &reply('serverloncaparev',$lonhost);
  312:             if (($answer eq 'unknown_cmd') || ($answer eq 'con_lost')) {
  313:                 if ($caller eq 'loncron') {
  314:                     my $hostname = &hostname($lonhost);
  315:                     my $protocol = $protocol{$lonhost};
  316:                     $protocol = 'http' if ($protocol ne 'https');
  317:                     my $url = $protocol.'://'.$hostname.'/adm/about.html';
  318:                     my $request=new HTTP::Request('GET',$url);
  319:                     my $response=&LONCAPA::LWPReq::makerequest($lonhost,$request,'',\%perlvar,4,1);
  320:                     unless ($response->is_error()) {
  321:                         my $content = $response->content;
  322:                         if ($content =~ /<p>VERSION\:\s*([\w.\-]+)<\/p>/) {
  323:                             $loncaparev = $1;
  324:                         }
  325:                     }
  326:                 } else {
  327:                     $loncaparev = $loncaparevs{$lonhost};
  328:                 }
  329:             } elsif ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
  330:                 $loncaparev = $1;
  331:             }
  332:         }
  333:         return &do_cache_new('serverloncaparev',$lonhost,$loncaparev,$cachetime);
  334:     }
  335: }
  336: 
  337: sub get_server_homeID {
  338:     my ($hostname,$ignore_cache,$caller) = @_;
  339:     unless ($ignore_cache) {
  340:         my ($serverhomeID,$cached)=&is_cached_new('serverhomeID',$hostname);
  341:         if (defined($cached)) {
  342:             return $serverhomeID;
  343:         }
  344:     }
  345:     my $cachetime = 12*3600;
  346:     my $serverhomeID;
  347:     if ($caller eq 'loncron') { 
  348:         my @machine_ids = &machine_ids($hostname);
  349:         foreach my $id (@machine_ids) {
  350:             my $response = &reply('serverhomeID',$id);
  351:             unless (($response eq 'unknown_cmd') || ($response eq 'con_lost')) {
  352:                 $serverhomeID = $response;
  353:                 last;
  354:             }
  355:         }
  356:         if ($serverhomeID eq '') {
  357:             $serverhomeID = $machine_ids[-1];
  358:         }
  359:     } else {
  360:         $serverhomeID = $serverhomeIDs{$hostname};
  361:     }
  362:     return &do_cache_new('serverhomeID',$hostname,$serverhomeID,$cachetime);
  363: }
  364: 
  365: sub get_remote_globals {
  366:     my ($lonhost,$whathash,$ignore_cache) = @_;
  367:     my ($result,%returnhash,%whatneeded);
  368:     if (ref($whathash) eq 'HASH') {
  369:         foreach my $what (sort(keys(%{$whathash}))) {
  370:             my $hashid = $lonhost.'-'.$what;
  371:             my ($response,$cached);
  372:             unless ($ignore_cache) {
  373:                 ($response,$cached)=&is_cached_new('lonnetglobal',$hashid);
  374:             }
  375:             if (defined($cached)) {
  376:                 $returnhash{$what} = $response;
  377:             } else {
  378:                 $whatneeded{$what} = 1;
  379:             }
  380:         }
  381:         if (keys(%whatneeded) == 0) {
  382:             $result = 'ok';
  383:         } else {
  384:             my $requested = &freeze_escape(\%whatneeded);
  385:             my $rep=&reply('readlonnetglobal:'.$requested,$lonhost);
  386:             if (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
  387:                 ($rep eq 'unknown_cmd')) {
  388:                 $result = $rep;
  389:             } else {
  390:                 $result = 'ok';
  391:                 my @pairs=split(/\&/,$rep);
  392:                 foreach my $item (@pairs) {
  393:                     my ($key,$value)=split(/=/,$item,2);
  394:                     my $what = &unescape($key);
  395:                     my $hashid = $lonhost.'-'.$what;
  396:                     $returnhash{$what}=&thaw_unescape($value);
  397:                     &do_cache_new('lonnetglobal',$hashid,$returnhash{$what},600);
  398:                 }
  399:             }
  400:         }
  401:     }
  402:     return ($result,\%returnhash);
  403: }
  404: 
  405: sub remote_devalidate_cache {
  406:     my ($lonhost,$cachekeys) = @_;
  407:     my $items;
  408:     return unless (ref($cachekeys) eq 'ARRAY');
  409:     my $cachestr = join('&',@{$cachekeys});
  410:     my $response = &reply('devalidatecache:'.&escape($cachestr),$lonhost);
  411:     return $response;
  412: }
  413: 
  414: # -------------------------------------------------- Non-critical communication
  415: sub subreply {
  416:     my ($cmd,$server)=@_;
  417:     my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
  418:     #
  419:     #  With loncnew process trimming, there's a timing hole between lonc server
  420:     #  process exit and the master server picking up the listen on the AF_UNIX
  421:     #  socket.  In that time interval, a lock file will exist:
  422: 
  423:     my $lockfile=$peerfile.".lock";
  424:     while (-e $lockfile) {	# Need to wait for the lockfile to disappear.
  425: 	sleep(0.1);
  426:     }
  427:     # At this point, either a loncnew parent is listening or an old lonc
  428:     # or loncnew child is listening so we can connect or everything's dead.
  429:     #
  430:     #   We'll give the connection a few tries before abandoning it.  If
  431:     #   connection is not possible, we'll con_lost back to the client.
  432:     #   
  433:     my $client;
  434:     for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
  435: 	$client=IO::Socket::UNIX->new(Peer    =>"$peerfile",
  436: 				      Type    => SOCK_STREAM,
  437: 				      Timeout => 10);
  438: 	if ($client) {
  439: 	    last;		# Connected!
  440: 	} else {
  441: 	    &create_connection(&hostname($server),$server);
  442: 	}
  443:         sleep(0.1);	# Try again later if failed connection.
  444:     }
  445:     my $answer;
  446:     if ($client) {
  447: 	print $client "sethost:$server:$cmd\n";
  448: 	$answer=<$client>;
  449: 	if (!$answer) { $answer="con_lost"; }
  450: 	chomp($answer);
  451:     } else {
  452: 	$answer = 'con_lost';	# Failed connection.
  453:     }
  454:     return $answer;
  455: }
  456: 
  457: sub reply {
  458:     my ($cmd,$server)=@_;
  459:     unless (defined(&hostname($server))) { return 'no_such_host'; }
  460:     my $answer=subreply($cmd,$server);
  461:     if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
  462:         my $logged = $cmd;
  463:         if ($cmd =~ /^encrypt:([^:]+):/) {
  464:             my $subcmd = $1;
  465:             if (($subcmd eq 'auth') || ($subcmd eq 'passwd') ||
  466:                 ($subcmd eq 'changeuserauth') || ($subcmd eq 'makeuser') ||
  467:                 ($subcmd eq 'putdom') || ($subcmd eq 'autoexportgrades')) {
  468:                 (undef,undef,my @rest) = split(/:/,$cmd);
  469:                 if (($subcmd eq 'auth') || ($subcmd eq 'putdom')) {
  470:                     splice(@rest,2,1,'Hidden');
  471:                 } elsif ($subcmd eq 'passwd') {
  472:                     splice(@rest,2,2,('Hidden','Hidden'));
  473:                 } elsif (($subcmd eq 'changeuserauth') || ($subcmd eq 'makeuser') ||
  474:                          ($subcmd eq 'autoexportgrades')) {
  475:                     splice(@rest,3,1,'Hidden');
  476:                 }
  477:                 $logged = join(':',('encrypt:'.$subcmd,@rest));
  478:             }
  479:         }
  480:         &logthis("<font color=\"blue\">WARNING:".
  481:                  " $logged to $server returned $answer</font>");
  482:     }
  483:     return $answer;
  484: }
  485: 
  486: # ----------------------------------------------------------- Send USR1 to lonc
  487: 
  488: sub reconlonc {
  489:     my ($lonid) = @_;
  490:     if ($lonid) {
  491:         my $hostname = &hostname($lonid);
  492: 	my $peerfile="$perlvar{'lonSockDir'}/$hostname";
  493: 	if ($hostname && -e $peerfile) {
  494: 	    &logthis("Trying to reconnect lonc for $lonid ($hostname)");
  495: 	    my $client=IO::Socket::UNIX->new(Peer    => $peerfile,
  496: 					     Type    => SOCK_STREAM,
  497: 					     Timeout => 10);
  498: 	    if ($client) {
  499: 		print $client ("reset_retries\n");
  500: 		my $answer=<$client>;
  501: 		#reset just this one.
  502: 	    }
  503: 	}
  504: 	return;
  505:     }
  506: 
  507:     &logthis("Trying to reconnect lonc");
  508:     my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
  509:     if (open(my $fh,"<",$loncfile)) {
  510: 	my $loncpid=<$fh>;
  511:         chomp($loncpid);
  512:         if (kill 0 => $loncpid) {
  513: 	    &logthis("lonc at pid $loncpid responding, sending USR1");
  514:             kill USR1 => $loncpid;
  515:             sleep 1;
  516:         } else {
  517: 	    &logthis(
  518:                "<font color=\"blue\">WARNING:".
  519:                " lonc at pid $loncpid not responding, giving up</font>");
  520:         }
  521:     } else {
  522: 	&logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
  523:     }
  524: }
  525: 
  526: # ------------------------------------------------------ Critical communication
  527: 
  528: sub critical {
  529:     my ($cmd,$server)=@_;
  530:     unless (&hostname($server)) {
  531:         &logthis("<font color=\"blue\">WARNING:".
  532:                " Critical message to unknown server ($server)</font>");
  533:         return 'no_such_host';
  534:     }
  535:     my $answer=reply($cmd,$server);
  536:     if ($answer eq 'con_lost') {
  537: 	&reconlonc($server);
  538: 	my $answer=reply($cmd,$server);
  539:         if ($answer eq 'con_lost') {
  540:             my $now=time;
  541:             my $middlename=$cmd;
  542:             $middlename=substr($middlename,0,16);
  543:             $middlename=~s/\W//g;
  544:             my $dfilename=
  545:       "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
  546:             $dumpcount++;
  547:             {
  548: 		my $dfh;
  549: 		if (open($dfh,">",$dfilename)) {
  550: 		    print $dfh "$cmd\n"; 
  551: 		    close($dfh);
  552: 		}
  553:             }
  554:             sleep 1;
  555:             my $wcmd='';
  556:             {
  557: 		my $dfh;
  558: 		if (open($dfh,"<",$dfilename)) {
  559: 		    $wcmd=<$dfh>; 
  560: 		    close($dfh);
  561: 		}
  562:             }
  563:             chomp($wcmd);
  564:             if ($wcmd eq $cmd) {
  565: 		&logthis("<font color=\"blue\">WARNING: ".
  566:                          "Connection buffer $dfilename: $cmd</font>");
  567:                 &logperm("D:$server:$cmd");
  568: 	        return 'con_delayed';
  569:             } else {
  570:                 &logthis("<font color=\"red\">CRITICAL:"
  571:                         ." Critical connection failed: $server $cmd</font>");
  572:                 &logperm("F:$server:$cmd");
  573:                 return 'con_failed';
  574:             }
  575:         }
  576:     }
  577:     return $answer;
  578: }
  579: 
  580: # ------------------------------------------- check if return value is an error
  581: 
  582: sub error {
  583:     my ($result) = @_;
  584:     if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
  585: 	if ($2 == 2) { return undef; }
  586: 	return $1;
  587:     }
  588:     return undef;
  589: }
  590: 
  591: sub convert_and_load_session_env {
  592:     my ($lonidsdir,$handle)=@_;
  593:     my @profile;
  594:     {
  595: 	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
  596: 	if (!$opened) {
  597: 	    return 0;
  598: 	}
  599: 	flock($idf,LOCK_SH);
  600: 	@profile=<$idf>;
  601: 	close($idf);
  602:     }
  603:     my %temp_env;
  604:     foreach my $line (@profile) {
  605: 	if ($line !~ m/=/) {
  606: 	    return 0;
  607: 	}
  608: 	chomp($line);
  609: 	my ($envname,$envvalue)=split(/=/,$line,2);
  610: 	$temp_env{&unescape($envname)} = &unescape($envvalue);
  611:     }
  612:     unlink("$lonidsdir/$handle.id");
  613:     if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
  614: 	    0640)) {
  615: 	%disk_env = %temp_env;
  616: 	@env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
  617: 	untie(%disk_env);
  618:     }
  619:     return 1;
  620: }
  621: 
  622: # ------------------------------------------- Transfer profile into environment
  623: my $env_loaded;
  624: sub transfer_profile_to_env {
  625:     my ($lonidsdir,$handle,$force_transfer) = @_;
  626:     if (!$force_transfer && $env_loaded) { return; } 
  627: 
  628:     if (!defined($lonidsdir)) {
  629: 	$lonidsdir = $perlvar{'lonIDsDir'};
  630:     }
  631:     if (!defined($handle)) {
  632:         ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
  633:     }
  634: 
  635:     my $convert;
  636:     {
  637:     	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
  638: 	if (!$opened) {
  639: 	    return;
  640: 	}
  641: 	flock($idf,LOCK_SH);
  642: 	if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
  643: 		&GDBM_READER(),0640)) {
  644: 	    @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
  645: 	    untie(%disk_env);
  646: 	} else {
  647: 	    $convert = 1;
  648: 	}
  649:     }
  650:     if ($convert) {
  651: 	if (!&convert_and_load_session_env($lonidsdir,$handle)) {
  652: 	    &logthis("Failed to load session, or convert session.");
  653: 	}
  654:     }
  655: 
  656:     my %remove;
  657:     while ( my $envname = each(%env) ) {
  658:         if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
  659:             if ($time < time-300) {
  660:                 $remove{$key}++;
  661:             }
  662:         }
  663:     }
  664: 
  665:     $env{'user.environment'} = "$lonidsdir/$handle.id";
  666:     $env_loaded=1;
  667:     foreach my $expired_key (keys(%remove)) {
  668:         &delenv($expired_key);
  669:     }
  670: }
  671: 
  672: # ---------------------------------------------------- Check for valid session 
  673: sub check_for_valid_session {
  674:     my ($r,$name,$userhashref,$domref) = @_;
  675:     my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
  676:     my ($lonidsdir,$linkname,$pubname,$secure,$lonid);
  677:     if ($name eq 'lonDAV') {
  678:         $lonidsdir=$r->dir_config('lonDAVsessDir');
  679:     } else {
  680:         $lonidsdir=$r->dir_config('lonIDsDir');
  681:         if ($name eq '') {
  682:             $name = 'lonID';
  683:         }
  684:     }
  685:     if ($name eq 'lonID') {
  686:         $secure = 'lonSID';
  687:         $linkname = 'lonLinkID';
  688:         $pubname = 'lonPubID';
  689:         if (exists($cookies{$secure})) {
  690:             $lonid=$cookies{$secure};
  691:         } elsif (exists($cookies{$name})) {
  692:             $lonid=$cookies{$name};
  693:         } elsif ((exists($cookies{$linkname})) && ($ENV{'SERVER_PORT'} != 443)) {
  694:             $lonid=$cookies{$linkname};
  695:         } elsif (exists($cookies{$pubname})) {
  696:             $lonid=$cookies{$pubname};
  697:         }
  698:     } else {
  699:         $lonid=$cookies{$name};
  700:     }
  701:     return undef if (!$lonid);
  702: 
  703:     my $handle=&LONCAPA::clean_handle($lonid->value);
  704:     if (-l "$lonidsdir/$handle.id") {
  705:         my $link = readlink("$lonidsdir/$handle.id");
  706:         if ((-e $link) && ($link =~ m{^\Q$lonidsdir\E/(.+)\.id$})) {
  707:             $handle = $1;
  708:         }
  709:     }
  710:     if (!-e "$lonidsdir/$handle.id") {
  711:         if ((ref($domref)) && ($name eq 'lonID') && 
  712:             ($handle =~ /^($match_username)\_\d+\_($match_domain)\_(.+)$/)) {
  713:             my ($possuname,$possudom,$possuhome) = ($1,$2,$3);
  714:             if ((&domain($possudom) ne '') && (&homeserver($possuname,$possudom) eq $possuhome)) {
  715:                 $$domref = $possudom;
  716:             }
  717:         }
  718:         return undef;
  719:     }
  720: 
  721:     my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
  722:     return undef if (!$opened);
  723: 
  724:     flock($idf,LOCK_SH);
  725:     my %disk_env;
  726:     if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
  727: 	    &GDBM_READER(),0640)) {
  728: 	return undef;	
  729:     }
  730: 
  731:     if (!defined($disk_env{'user.name'})
  732: 	|| !defined($disk_env{'user.domain'})) {
  733:         untie(%disk_env);
  734: 	return undef;
  735:     }
  736: 
  737:     if (ref($userhashref) eq 'HASH') {
  738:         $userhashref->{'name'} = $disk_env{'user.name'};
  739:         $userhashref->{'domain'} = $disk_env{'user.domain'};
  740:         $userhashref->{'lti'} = $disk_env{'request.lti.login'};
  741:         if ($userhashref->{'lti'}) {
  742:             $userhashref->{'ltitarget'} = $disk_env{'request.lti.target'};
  743:             $userhashref->{'ltiuri'} = $disk_env{'request.lti.uri'};
  744:         }
  745:     }
  746:     untie(%disk_env);
  747: 
  748:     return $handle;
  749: }
  750: 
  751: sub timed_flock {
  752:     my ($file,$lock_type) = @_;
  753:     my $failed=0;
  754:     eval {
  755: 	local $SIG{__DIE__}='DEFAULT';
  756: 	local $SIG{ALRM}=sub {
  757: 	    $failed=1;
  758: 	    die("failed lock");
  759: 	};
  760: 	alarm(13);
  761: 	flock($file,$lock_type);
  762: 	alarm(0);
  763:     };
  764:     if ($failed) {
  765: 	return undef;
  766:     } else {
  767: 	return 1;
  768:     }
  769: }
  770: 
  771: sub get_sessionfile_vars {
  772:     my ($handle,$lonidsdir,$storearr) = @_;
  773:     my %returnhash;
  774:     unless (ref($storearr) eq 'ARRAY') {
  775:         return %returnhash;
  776:     }
  777:     if (-l "$lonidsdir/$handle.id") {
  778:         my $link = readlink("$lonidsdir/$handle.id");
  779:         if ((-e $link) && ($link =~ m{^\Q$lonidsdir\E/(.+)\.id$})) {
  780:             $handle = $1;
  781:         }
  782:     }
  783:     if ((-e "$lonidsdir/$handle.id") &&
  784:         ($handle =~ /^($match_username)\_\d+\_($match_domain)\_(.+)$/)) {
  785:         my ($possuname,$possudom,$possuhome) = ($1,$2,$3);
  786:         if ((&domain($possudom) ne '') && (&homeserver($possuname,$possudom) eq $possuhome)) {
  787:             if (open(my $idf,'+<',"$lonidsdir/$handle.id")) {
  788:                 flock($idf,LOCK_SH);
  789:                 if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
  790:                         &GDBM_READER(),0640)) {
  791:                     foreach my $item (@{$storearr}) {
  792:                         $returnhash{$item} = $disk_env{$item};
  793:                     }
  794:                     untie(%disk_env);
  795:                 }
  796:             }
  797:         }
  798:     }
  799:     return %returnhash;
  800: }
  801: 
  802: # ---------------------------------------------------------- Append Environment
  803: 
  804: sub appenv {
  805:     my ($newenv,$roles) = @_;
  806:     if (ref($newenv) eq 'HASH') {
  807:         foreach my $key (keys(%{$newenv})) {
  808:             my $refused = 0;
  809: 	    if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
  810:                 $refused = 1;
  811:                 if (ref($roles) eq 'ARRAY') {
  812:                     my ($type,$role) = ($key =~ m{^user\.(role|priv)\.(.+?)\./});
  813:                     if (grep(/^\Q$role\E$/,@{$roles})) {
  814:                         $refused = 0;
  815:                     }
  816:                 }
  817:             }
  818:             if ($refused) {
  819:                 &logthis("<font color=\"blue\">WARNING: ".
  820:                          "Attempt to modify environment ".$key." to ".$newenv->{$key}
  821:                          .'</font>');
  822: 	        delete($newenv->{$key});
  823:             } else {
  824:                 $env{$key}=$newenv->{$key};
  825:             }
  826:         }
  827:         my $lonids = $perlvar{'lonIDsDir'};
  828:         if ($env{'user.environment'} =~ m{^\Q$lonids/\E$match_username\_\d+\_$match_domain\_[\w\-.]+\.id$}) {
  829:             my $opened = open(my $env_file,'+<',$env{'user.environment'});
  830:             if ($opened
  831: 	        && &timed_flock($env_file,LOCK_EX)
  832: 	        &&
  833: 	        tie(my %disk_env,'GDBM_File',$env{'user.environment'},
  834: 	            (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
  835: 	        while (my ($key,$value) = each(%{$newenv})) {
  836: 	            $disk_env{$key} = $value;
  837: 	        }
  838: 	        untie(%disk_env);
  839:             }
  840:         }
  841:     }
  842:     return 'ok';
  843: }
  844: # ----------------------------------------------------- Delete from Environment
  845: 
  846: sub delenv {
  847:     my ($delthis,$regexp,$roles) = @_;
  848:     if (($delthis=~/^user\.role/) || ($delthis=~/^user\.priv/)) {
  849:         my $refused = 1;
  850:         if (ref($roles) eq 'ARRAY') {
  851:             my ($type,$role) = ($delthis =~ /^user\.(role|priv)\.([^.]+)\./);
  852:             if (grep(/^\Q$role\E$/,@{$roles})) {
  853:                 $refused = 0;
  854:             }
  855:         }
  856:         if ($refused) {
  857:             &logthis("<font color=\"blue\">WARNING: ".
  858:                      "Attempt to delete from environment ".$delthis);
  859:             return 'error';
  860:         }
  861:     }
  862:     my $opened = open(my $env_file,'+<',$env{'user.environment'});
  863:     if ($opened
  864: 	&& &timed_flock($env_file,LOCK_EX)
  865: 	&&
  866: 	tie(my %disk_env,'GDBM_File',$env{'user.environment'},
  867: 	    (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
  868: 	foreach my $key (keys(%disk_env)) {
  869: 	    if ($regexp) {
  870:                 if ($key=~/^$delthis/) {
  871:                     delete($env{$key});
  872:                     delete($disk_env{$key});
  873:                 } 
  874:             } else {
  875:                 if ($key=~/^\Q$delthis\E/) {
  876: 		    delete($env{$key});
  877: 		    delete($disk_env{$key});
  878: 	        }
  879:             }
  880: 	}
  881: 	untie(%disk_env);
  882:     }
  883:     return 'ok';
  884: }
  885: 
  886: sub get_env_multiple {
  887:     my ($name) = @_;
  888:     my @values;
  889:     if (defined($env{$name})) {
  890:         # exists is it an array
  891:         if (ref($env{$name})) {
  892:             @values=@{ $env{$name} };
  893:         } else {
  894:             $values[0]=$env{$name};
  895:         }
  896:     }
  897:     return(@values);
  898: }
  899: 
  900: # ------------------------------------------------------------------- Locking
  901: 
  902: sub set_lock {
  903:     my ($text)=@_;
  904:     $locknum++;
  905:     my $id=$$.'-'.$locknum;
  906:     &appenv({'session.locks' => $env{'session.locks'}.','.$id,
  907:              'session.lock.'.$id => $text});
  908:     return $id;
  909: }
  910: 
  911: sub get_locks {
  912:     my $num=0;
  913:     my %texts=();
  914:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
  915:        if ($lock=~/\w/) {
  916:           $num++;
  917:           $texts{$lock}=$env{'session.lock.'.$lock};
  918:        }
  919:    }
  920:    return ($num,%texts);
  921: }
  922: 
  923: sub remove_lock {
  924:     my ($id)=@_;
  925:     my $newlocks='';
  926:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
  927:        if (($lock=~/\w/) && ($lock ne $id)) {
  928:           $newlocks.=','.$lock;
  929:        }
  930:     }
  931:     &appenv({'session.locks' => $newlocks});
  932:     &delenv('session.lock.'.$id);
  933: }
  934: 
  935: sub remove_all_locks {
  936:     my $activelocks=$env{'session.locks'};
  937:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
  938:        if ($lock=~/\w/) {
  939:           &remove_lock($lock);
  940:        }
  941:     }
  942: }
  943: 
  944: 
  945: # ------------------------------------------ Find out current server userload
  946: sub userload {
  947:     my $numusers=0;
  948:     {
  949: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
  950: 	my $filename;
  951: 	my $curtime=time;
  952: 	while ($filename=readdir(LONIDS)) {
  953: 	    next if ($filename eq '.' || $filename eq '..');
  954: 	    next if ($filename =~ /publicuser_\d+\.id/);
  955:             next if ($filename =~ /^[a-f0-9]+_linked\.id$/);
  956: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
  957: 	    if ($curtime-$mtime < 1800) { $numusers++; }
  958: 	}
  959: 	closedir(LONIDS);
  960:     }
  961:     my $userloadpercent=0;
  962:     my $maxuserload=$perlvar{'lonUserLoadLim'};
  963:     if ($maxuserload) {
  964: 	$userloadpercent=100*$numusers/$maxuserload;
  965:     }
  966:     $userloadpercent=sprintf("%.2f",$userloadpercent);
  967:     return $userloadpercent;
  968: }
  969: 
  970: # ------------------------------ Find server with least workload from spare.tab
  971: 
  972: sub spareserver {
  973:     my ($loadpercent,$userloadpercent,$want_server_name,$udom) = @_;
  974:     my $spare_server;
  975:     if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
  976:     my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent 
  977:                                                      :  $userloadpercent;
  978:     my ($uint_dom,$remotesessions);
  979:     if (($udom ne '') && (&domain($udom) ne '')) {
  980:         my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
  981:         $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
  982:         my %udomdefaults = &Apache::lonnet::get_domain_defaults($udom);
  983:         $remotesessions = $udomdefaults{'remotesessions'};
  984:     }
  985:     my $spareshash = &this_host_spares($udom);
  986:     if (ref($spareshash) eq 'HASH') {
  987:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
  988:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
  989:                 next unless (&spare_can_host($udom,$uint_dom,$remotesessions,
  990:                                              $try_server));
  991: 	        ($spare_server, $lowest_load) =
  992: 	            &compare_server_load($try_server, $spare_server, $lowest_load);
  993:             }
  994:         }
  995: 
  996:         my $found_server = ($spare_server ne '' && $lowest_load < 100);
  997: 
  998:         if (!$found_server) {
  999:             if (ref($spareshash->{'default'}) eq 'ARRAY') { 
 1000: 	        foreach my $try_server (@{ $spareshash->{'default'} }) {
 1001:                     next unless (&spare_can_host($udom,$uint_dom,
 1002:                                                  $remotesessions,$try_server));
 1003: 	            ($spare_server, $lowest_load) =
 1004: 		        &compare_server_load($try_server, $spare_server, $lowest_load);
 1005:                 }
 1006: 	    }
 1007:         }
 1008:     }
 1009: 
 1010:     if (!$want_server_name) {
 1011:         if (defined($spare_server)) {
 1012:             my $hostname = &hostname($spare_server);
 1013:             if (defined($hostname)) {
 1014:                 my $protocol = 'http';
 1015:                 if ($protocol{$spare_server} eq 'https') {
 1016:                     $protocol = $protocol{$spare_server};
 1017:                 }
 1018: 	        $spare_server = $protocol.'://'.$hostname;
 1019:             }
 1020:         }
 1021:     }
 1022:     return $spare_server;
 1023: }
 1024: 
 1025: sub compare_server_load {
 1026:     my ($try_server, $spare_server, $lowest_load, $required) = @_;
 1027: 
 1028:     if ($required) {
 1029:         my ($reqdmajor,$reqdminor) = ($required =~ /^(\d+)\.(\d+)$/);
 1030:         my $remoterev = &get_server_loncaparev(undef,$try_server);
 1031:         my ($major,$minor) = ($remoterev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
 1032:         if (($major eq '' && $minor eq '') ||
 1033:             (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)))) {
 1034:             return ($spare_server,$lowest_load);
 1035:         }
 1036:     }
 1037: 
 1038:     my $loadans     = &reply('load',    $try_server);
 1039:     my $userloadans = &reply('userload',$try_server);
 1040: 
 1041:     if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
 1042: 	return ($spare_server, $lowest_load); #didn't get a number from the server
 1043:     }
 1044: 
 1045:     my $load;
 1046:     if ($loadans =~ /\d/) {
 1047: 	if ($userloadans =~ /\d/) {
 1048: 	    #both are numbers, pick the bigger one
 1049: 	    $load = ($loadans > $userloadans) ? $loadans 
 1050: 		                              : $userloadans;
 1051: 	} else {
 1052: 	    $load = $loadans;
 1053: 	}
 1054:     } else {
 1055: 	$load = $userloadans;
 1056:     }
 1057: 
 1058:     if (($load =~ /\d/) && ($load < $lowest_load)) {
 1059: 	$spare_server = $try_server;
 1060: 	$lowest_load  = $load;
 1061:     }
 1062:     return ($spare_server,$lowest_load);
 1063: }
 1064: 
 1065: # --------------------------- ask offload servers if user already has a session
 1066: sub find_existing_session {
 1067:     my ($udom,$uname) = @_;
 1068:     my $spareshash = &this_host_spares($udom);
 1069:     if (ref($spareshash) eq 'HASH') {
 1070:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
 1071:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
 1072:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
 1073:             }
 1074:         }
 1075:         if (ref($spareshash->{'default'}) eq 'ARRAY') {
 1076:             foreach my $try_server (@{ $spareshash->{'default'} }) {
 1077:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
 1078:             }
 1079:         }
 1080:     }
 1081:     return;
 1082: }
 1083: 
 1084: # check if user's browser sent load balancer cookie and server still has session
 1085: # and is not overloaded.
 1086: sub check_for_balancer_cookie {
 1087:     my ($r,$update_mtime) = @_;
 1088:     my ($otherserver,$cookie);
 1089:     my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
 1090:     if (exists($cookies{'balanceID'})) {
 1091:         my $balid = $cookies{'balanceID'};
 1092:         $cookie=&LONCAPA::clean_handle($balid->value);
 1093:         my $balancedir=$r->dir_config('lonBalanceDir');
 1094:         if ((-d $balancedir) && (-e "$balancedir/$cookie.id")) {
 1095:             if ($cookie =~ /^($match_domain)_($match_username)_[a-f0-9]+$/) {
 1096:                 my ($possudom,$possuname) = ($1,$2);
 1097:                 my $has_session = 0;
 1098:                 if ((&domain($possudom) ne '') &&
 1099:                     (&homeserver($possuname,$possudom) ne 'no_host')) {
 1100:                     my $try_server;
 1101:                     my $opened = open(my $idf,'+<',"$balancedir/$cookie.id");
 1102:                     if ($opened) {
 1103:                         flock($idf,LOCK_SH);
 1104:                         while (my $line = <$idf>) {
 1105:                             chomp($line);
 1106:                             if (&hostname($line) ne '') {
 1107:                                 $try_server = $line;
 1108:                                 last;
 1109:                             }
 1110:                         }
 1111:                         close($idf);
 1112:                         if (($try_server) &&
 1113:                             (&has_user_session($try_server,$possudom,$possuname))) {
 1114:                             my $lowest_load = 30000;
 1115:                             ($otherserver,$lowest_load) =
 1116:                                 &compare_server_load($try_server,undef,$lowest_load);
 1117:                             if ($otherserver ne '' && $lowest_load < 100) {
 1118:                                 $has_session = 1;
 1119:                             } else {
 1120:                                 undef($otherserver);
 1121:                             }
 1122:                         }
 1123:                     }
 1124:                 }
 1125:                 if ($has_session) {
 1126:                     if ($update_mtime) {
 1127:                         my $atime = my $mtime = time;
 1128:                         utime($atime,$mtime,"$balancedir/$cookie.id");
 1129:                     }
 1130:                 } else {
 1131:                     unlink("$balancedir/$cookie.id");
 1132:                 }
 1133:             }
 1134:         }
 1135:     }
 1136:     return ($otherserver,$cookie);
 1137: }
 1138: 
 1139: sub delbalcookie {
 1140:     my ($cookie,$balancer) =@_;
 1141:     if ($cookie =~ /^($match_domain)\_($match_username)\_[a-f0-9]{32}$/) {
 1142:         my ($udom,$uname) = ($1,$2);
 1143:         my $uprimary_id = &domain($udom,'primary');
 1144:         my $uintdom = &internet_dom($uprimary_id);
 1145:         my $intdom = &internet_dom($balancer);
 1146:         my $serverhomedom = &host_domain($balancer);
 1147:         if (($uintdom ne '') && ($uintdom eq $intdom)) {
 1148:             return &reply("delbalcookie:$cookie",$balancer);
 1149:         }
 1150:     }
 1151: }
 1152: 
 1153: # -------------------------------- ask if server already has a session for user
 1154: sub has_user_session {
 1155:     my ($lonid,$udom,$uname) = @_;
 1156:     my $result = &reply(join(':','userhassession',
 1157: 			     map {&escape($_)} ($udom,$uname)),$lonid);
 1158:     return 1 if ($result eq 'ok');
 1159: 
 1160:     return 0;
 1161: }
 1162: 
 1163: # --------- determine least loaded server in a user's domain which allows login
 1164: 
 1165: sub choose_server {
 1166:     my ($udom,$checkloginvia,$required,$skiploadbal) = @_;
 1167:     my %domconfhash = &Apache::loncommon::get_domainconf($udom);
 1168:     my %servers = &get_servers($udom);
 1169:     my $lowest_load = 30000;
 1170:     my ($login_host,$hostname,$portal_path,$isredirect,$balancers);
 1171:     if ($skiploadbal) {
 1172:         ($balancers,my $cached)=&is_cached_new('loadbalancing',$udom);
 1173:         unless (defined($cached)) {
 1174:             my $cachetime = 60*60*24;
 1175:             my %domconfig =
 1176:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
 1177:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
 1178:                 $balancers = &do_cache_new('loadbalancing',$udom,$domconfig{'loadbalancing'},
 1179:                                            $cachetime);
 1180:             }
 1181:         }
 1182:     }
 1183:     foreach my $lonhost (keys(%servers)) {
 1184:         if ($skiploadbal) {
 1185:             if (ref($balancers) eq 'HASH') {
 1186:                 next if (exists($balancers->{$lonhost}));
 1187:             }
 1188:         }
 1189:         my $loginvia;
 1190:         if ($checkloginvia) {
 1191:             $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
 1192:             if ($loginvia) {
 1193:                 my ($server,$path) = split(/:/,$loginvia);
 1194:                 ($login_host, $lowest_load) =
 1195:                     &compare_server_load($server, $login_host, $lowest_load, $required);
 1196:                 if ($login_host eq $server) {
 1197:                     $portal_path = $path;
 1198:                     $isredirect = 1;
 1199:                 }
 1200:             } else {
 1201:                 ($login_host, $lowest_load) =
 1202:                     &compare_server_load($lonhost, $login_host, $lowest_load, $required);
 1203:                 if ($login_host eq $lonhost) {
 1204:                     $portal_path = '';
 1205:                     $isredirect = ''; 
 1206:                 }
 1207:             }
 1208:         } else {
 1209:             ($login_host, $lowest_load) =
 1210:                 &compare_server_load($lonhost, $login_host, $lowest_load, $required);
 1211:         }
 1212:     }
 1213:     if ($login_host ne '') {
 1214:         $hostname = &hostname($login_host);
 1215:     }
 1216:     return ($login_host,$hostname,$portal_path,$isredirect,$lowest_load);
 1217: }
 1218: 
 1219: # --------------------------------------------- Try to change a user's password
 1220: 
 1221: sub changepass {
 1222:     my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
 1223:     $currentpass = &escape($currentpass);
 1224:     $newpass     = &escape($newpass);
 1225:     my $lonhost = $perlvar{'lonHostID'};
 1226:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
 1227: 		       $server);
 1228:     if (! $answer) {
 1229: 	&logthis("No reply on password change request to $server ".
 1230: 		 "by $uname in domain $udom.");
 1231:     } elsif ($answer =~ "^ok") {
 1232:         &logthis("$uname in $udom successfully changed their password ".
 1233: 		 "on $server.");
 1234:     } elsif ($answer =~ "^pwchange_failure") {
 1235: 	&logthis("$uname in $udom was unable to change their password ".
 1236: 		 "on $server.  The action was blocked by either lcpasswd ".
 1237: 		 "or pwchange");
 1238:     } elsif ($answer =~ "^non_authorized") {
 1239:         &logthis("$uname in $udom did not get their password correct when ".
 1240: 		 "attempting to change it on $server.");
 1241:     } elsif ($answer =~ "^auth_mode_error") {
 1242:         &logthis("$uname in $udom attempted to change their password despite ".
 1243: 		 "not being locally or internally authenticated on $server.");
 1244:     } elsif ($answer =~ "^unknown_user") {
 1245:         &logthis("$uname in $udom attempted to change their password ".
 1246: 		 "on $server but were unable to because $server is not ".
 1247: 		 "their home server.");
 1248:     } elsif ($answer =~ "^refused") {
 1249: 	&logthis("$server refused to change $uname in $udom password because ".
 1250: 		 "it was sent an unencrypted request to change the password.");
 1251:     } elsif ($answer =~ "invalid_client") {
 1252:         &logthis("$server refused to change $uname in $udom password because ".
 1253:                  "it was a reset by e-mail originating from an invalid server.");
 1254:     }
 1255:     return $answer;
 1256: }
 1257: 
 1258: # ----------------------- Try to determine user's current authentication scheme
 1259: 
 1260: sub queryauthenticate {
 1261:     my ($uname,$udom)=@_;
 1262:     my $uhome=&homeserver($uname,$udom);
 1263:     if (!$uhome) {
 1264: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
 1265: 	return 'no_host';
 1266:     }
 1267:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
 1268:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
 1269: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
 1270:     }
 1271:     return $answer;
 1272: }
 1273: 
 1274: # --------- Try to authenticate user from domain's lib servers (first this one)
 1275: 
 1276: sub authenticate {
 1277:     my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
 1278:     $upass=&escape($upass);
 1279:     $uname= &LONCAPA::clean_username($uname);
 1280:     my $uhome=&homeserver($uname,$udom,1);
 1281:     my $newhome;
 1282:     if ((!$uhome) || ($uhome eq 'no_host')) {
 1283: # Maybe the machine was offline and only re-appeared again recently?
 1284:         &reconlonc();
 1285: # One more
 1286: 	$uhome=&homeserver($uname,$udom,1);
 1287:         if (($uhome eq 'no_host') && $checkdefauth) {
 1288:             if (defined(&domain($udom,'primary'))) {
 1289:                 $newhome=&domain($udom,'primary');
 1290:             }
 1291:             if ($newhome ne '') {
 1292:                 $uhome = $newhome;
 1293:             }
 1294:         }
 1295: 	if ((!$uhome) || ($uhome eq 'no_host')) {
 1296: 	    &logthis("User $uname at $udom is unknown in authenticate");
 1297: 	    return 'no_host';
 1298:         }
 1299:     }
 1300:     my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
 1301:     if ($answer eq 'authorized') {
 1302:         if ($newhome) {
 1303:             &logthis("User $uname at $udom authorized by $uhome, but needs account");
 1304:             return 'no_account_on_host'; 
 1305:         } else {
 1306:             &logthis("User $uname at $udom authorized by $uhome");
 1307:             return $uhome;
 1308:         }
 1309:     }
 1310:     if ($answer eq 'non_authorized') {
 1311: 	&logthis("User $uname at $udom rejected by $uhome");
 1312: 	return 'no_host'; 
 1313:     }
 1314:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
 1315:     return 'no_host';
 1316: }
 1317: 
 1318: sub can_host_session {
 1319:     my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
 1320:     my $canhost = 1;
 1321:     my $host_idn = &Apache::lonnet::internet_dom($lonhost);
 1322:     if (ref($remotesessions) eq 'HASH') {
 1323:         if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
 1324:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
 1325:                 $canhost = 0;
 1326:             } else {
 1327:                 $canhost = 1;
 1328:             }
 1329:         }
 1330:         if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
 1331:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
 1332:                 $canhost = 1;
 1333:             } else {
 1334:                 $canhost = 0;
 1335:             }
 1336:         }
 1337:         if ($canhost) {
 1338:             if ($remotesessions->{'version'} ne '') {
 1339:                 my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
 1340:                 if ($reqmajor ne '' && $reqminor ne '') {
 1341:                     if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
 1342:                         my $major = $1;
 1343:                         my $minor = $2;
 1344:                         if (($major < $reqmajor ) ||
 1345:                             (($major == $reqmajor) && ($minor < $reqminor))) {
 1346:                             $canhost = 0;
 1347:                         }
 1348:                     } else {
 1349:                         $canhost = 0;
 1350:                     }
 1351:                 }
 1352:             }
 1353:         }
 1354:     }
 1355:     if ($canhost) {
 1356:         if (ref($hostedsessions) eq 'HASH') {
 1357:             my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
 1358:             my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
 1359:             if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
 1360:                 if (($uint_dom ne '') && 
 1361:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'excludedomain'}}))) {
 1362:                     $canhost = 0;
 1363:                 } else {
 1364:                     $canhost = 1;
 1365:                 }
 1366:             }
 1367:             if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
 1368:                 if (($uint_dom ne '') && 
 1369:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'includedomain'}}))) {
 1370:                     $canhost = 1;
 1371:                 } else {
 1372:                     $canhost = 0;
 1373:                 }
 1374:             }
 1375:         }
 1376:     }
 1377:     return $canhost;
 1378: }
 1379: 
 1380: sub spare_can_host {
 1381:     my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
 1382:     my $canhost=1;
 1383:     my $try_server_hostname = &hostname($try_server);
 1384:     my $serverhomeID = &get_server_homeID($try_server_hostname);
 1385:     my $serverhomedom = &host_domain($serverhomeID);
 1386:     my %defdomdefaults = &get_domain_defaults($serverhomedom);
 1387:     if (ref($defdomdefaults{'offloadnow'}) eq 'HASH') {
 1388:         if ($defdomdefaults{'offloadnow'}{$try_server}) {
 1389:             $canhost = 0;
 1390:         }
 1391:     }
 1392:     if (($canhost) && ($uint_dom)) {
 1393:         my @intdoms;
 1394:         my $internet_names = &get_internet_names($try_server);
 1395:         if (ref($internet_names) eq 'ARRAY') {
 1396:             @intdoms = @{$internet_names};
 1397:         }
 1398:         unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
 1399:             my $remoterev = &get_server_loncaparev(undef,$try_server);
 1400:             $canhost = &can_host_session($udom,$try_server,$remoterev,
 1401:                                          $remotesessions,
 1402:                                          $defdomdefaults{'hostedsessions'});
 1403:         }
 1404:     }
 1405:     return $canhost;
 1406: }
 1407: 
 1408: sub this_host_spares {
 1409:     my ($dom) = @_;
 1410:     my ($dom_in_use,$lonhost_in_use,$result);
 1411:     my @hosts = &current_machine_ids();
 1412:     foreach my $lonhost (@hosts) {
 1413:         if (&host_domain($lonhost) eq $dom) {
 1414:             $dom_in_use = $dom;
 1415:             $lonhost_in_use = $lonhost;
 1416:             last;
 1417:         }
 1418:     }
 1419:     if ($dom_in_use ne '') {
 1420:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
 1421:     }
 1422:     if (ref($result) ne 'HASH') {
 1423:         $lonhost_in_use = $perlvar{'lonHostID'};
 1424:         $dom_in_use = &host_domain($lonhost_in_use);
 1425:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
 1426:         if (ref($result) ne 'HASH') {
 1427:             $result = \%spareid;
 1428:         }
 1429:     }
 1430:     return $result;
 1431: }
 1432: 
 1433: sub spares_for_offload  {
 1434:     my ($dom_in_use,$lonhost_in_use) = @_;
 1435:     my ($result,$cached)=&is_cached_new('spares',$dom_in_use);
 1436:     if (defined($cached)) {
 1437:         return $result;
 1438:     } else {
 1439:         my $cachetime = 60*60*24;
 1440:         my %domconfig =
 1441:             &Apache::lonnet::get_dom('configuration',['usersessions'],$dom_in_use);
 1442:         if (ref($domconfig{'usersessions'}) eq 'HASH') {
 1443:             if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
 1444:                 if (ref($domconfig{'usersessions'}{'spares'}{$lonhost_in_use}) eq 'HASH') {
 1445:                     return &do_cache_new('spares',$dom_in_use,$domconfig{'usersessions'}{'spares'}{$lonhost_in_use},$cachetime);
 1446:                 }
 1447:             }
 1448:         }
 1449:     }
 1450:     return;
 1451: }
 1452: 
 1453: sub get_lonbalancer_config {
 1454:     my ($servers) = @_;
 1455:     my ($currbalancer,$currtargets);
 1456:     if (ref($servers) eq 'HASH') {
 1457:         foreach my $server (keys(%{$servers})) {
 1458:             my %what = (
 1459:                          spareid => 1,
 1460:                          perlvar => 1,
 1461:                        );
 1462:             my ($result,$returnhash) = &get_remote_globals($server,\%what);
 1463:             if ($result eq 'ok') {
 1464:                 if (ref($returnhash) eq 'HASH') {
 1465:                     if (ref($returnhash->{'perlvar'}) eq 'HASH') {
 1466:                         if ($returnhash->{'perlvar'}->{'lonBalancer'} eq 'yes') {
 1467:                             $currbalancer = $server;
 1468:                             $currtargets = {};
 1469:                             if (ref($returnhash->{'spareid'}) eq 'HASH') {
 1470:                                 if (ref($returnhash->{'spareid'}->{'primary'}) eq 'ARRAY') {
 1471:                                     $currtargets->{'primary'} = $returnhash->{'spareid'}->{'primary'};
 1472:                                 }
 1473:                                 if (ref($returnhash->{'spareid'}->{'default'}) eq 'ARRAY') {
 1474:                                     $currtargets->{'default'} = $returnhash->{'spareid'}->{'default'};
 1475:                                 }
 1476:                             }
 1477:                             last;
 1478:                         }
 1479:                     }
 1480:                 }
 1481:             }
 1482:         }
 1483:     }
 1484:     return ($currbalancer,$currtargets);
 1485: }
 1486: 
 1487: sub check_loadbalancing {
 1488:     my ($uname,$udom,$caller) = @_;
 1489:     my ($is_balancer,$currtargets,$currrules,$dom_in_use,$homeintdom,
 1490:         $rule_in_effect,$offloadto,$otherserver,$setcookie,$dom_balancers);
 1491:     my $lonhost = $perlvar{'lonHostID'};
 1492:     my @hosts = &current_machine_ids();
 1493:     my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
 1494:     my $uintdom = &Apache::lonnet::internet_dom($uprimary_id);
 1495:     my $intdom = &Apache::lonnet::internet_dom($lonhost);
 1496:     my $serverhomedom = &host_domain($lonhost);
 1497:     my $domneedscache;
 1498:     my $cachetime = 60*60*24;
 1499: 
 1500:     if (($uintdom ne '') && ($uintdom eq $intdom)) {
 1501:         $dom_in_use = $udom;
 1502:         $homeintdom = 1;
 1503:     } else {
 1504:         $dom_in_use = $serverhomedom;
 1505:     }
 1506:     my ($result,$cached)=&is_cached_new('loadbalancing',$dom_in_use);
 1507:     unless (defined($cached)) {
 1508:         my %domconfig =
 1509:             &Apache::lonnet::get_dom('configuration',['loadbalancing'],$dom_in_use);
 1510:         if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
 1511:             $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
 1512:         } else {
 1513:             $domneedscache = $dom_in_use;
 1514:         }
 1515:     }
 1516:     if (ref($result) eq 'HASH') {
 1517:         ($is_balancer,$currtargets,$currrules,$setcookie,$dom_balancers) =
 1518:             &check_balancer_result($result,@hosts);
 1519:         if ($is_balancer) {
 1520:             if (ref($currrules) eq 'HASH') {
 1521:                 if ($homeintdom) {
 1522:                     if ($uname ne '') {
 1523:                         if (($currrules->{'_LC_adv'} ne '') || ($currrules->{'_LC_author'} ne '')) {
 1524:                             my ($is_adv,$is_author) = &is_advanced_user($udom,$uname);
 1525:                             if (($currrules->{'_LC_author'} ne '') && ($is_author)) {
 1526:                                 $rule_in_effect = $currrules->{'_LC_author'};
 1527:                             } elsif (($currrules->{'_LC_adv'} ne '') && ($is_adv)) {
 1528:                                 $rule_in_effect = $currrules->{'_LC_adv'}
 1529:                             }
 1530:                         }
 1531:                         if ($rule_in_effect eq '') {
 1532:                             my %userenv = &userenvironment($udom,$uname,'inststatus');
 1533:                             if ($userenv{'inststatus'} ne '') {
 1534:                                 my @statuses = map { &unescape($_); } split(/:/,$userenv{'inststatus'});
 1535:                                 my ($othertitle,$usertypes,$types) =
 1536:                                     &Apache::loncommon::sorted_inst_types($udom);
 1537:                                 if (ref($types) eq 'ARRAY') {
 1538:                                     foreach my $type (@{$types}) {
 1539:                                         if (grep(/^\Q$type\E$/,@statuses)) {
 1540:                                             if (exists($currrules->{$type})) {
 1541:                                                 $rule_in_effect = $currrules->{$type};
 1542:                                             }
 1543:                                         }
 1544:                                     }
 1545:                                 }
 1546:                             } else {
 1547:                                 if (exists($currrules->{'default'})) {
 1548:                                     $rule_in_effect = $currrules->{'default'};
 1549:                                 }
 1550:                             }
 1551:                         }
 1552:                     } else {
 1553:                         if (exists($currrules->{'default'})) {
 1554:                             $rule_in_effect = $currrules->{'default'};
 1555:                         }
 1556:                     }
 1557:                 } else {
 1558:                     if ($currrules->{'_LC_external'} ne '') {
 1559:                         $rule_in_effect = $currrules->{'_LC_external'};
 1560:                     }
 1561:                 }
 1562:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
 1563:                                                        $uname,$udom);
 1564:             }
 1565:         }
 1566:     } elsif (($homeintdom) && ($udom ne $serverhomedom)) {
 1567:         ($result,$cached)=&is_cached_new('loadbalancing',$serverhomedom);
 1568:         unless (defined($cached)) {
 1569:             my %domconfig =
 1570:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$serverhomedom);
 1571:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
 1572:                 $result = &do_cache_new('loadbalancing',$serverhomedom,$domconfig{'loadbalancing'},$cachetime);
 1573:             } else {
 1574:                 $domneedscache = $serverhomedom;
 1575:             }
 1576:         }
 1577:         if (ref($result) eq 'HASH') {
 1578:             ($is_balancer,$currtargets,$currrules,$setcookie,$dom_balancers) =
 1579:                 &check_balancer_result($result,@hosts);
 1580:             if ($is_balancer) {
 1581:                 if (ref($currrules) eq 'HASH') {
 1582:                     if ($currrules->{'_LC_internetdom'} ne '') {
 1583:                         $rule_in_effect = $currrules->{'_LC_internetdom'};
 1584:                     }
 1585:                 }
 1586:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
 1587:                                                        $uname,$udom);
 1588:             }
 1589:         } else {
 1590:             if ($perlvar{'lonBalancer'} eq 'yes') {
 1591:                 $is_balancer = 1;
 1592:                 $offloadto = &this_host_spares($dom_in_use);
 1593:             }
 1594:             unless (defined($cached)) {
 1595:                 $domneedscache = $serverhomedom;
 1596:             }
 1597:         }
 1598:     } else {
 1599:         if ($perlvar{'lonBalancer'} eq 'yes') {
 1600:             $is_balancer = 1;
 1601:             $offloadto = &this_host_spares($dom_in_use);
 1602:         }
 1603:         unless (defined($cached)) {
 1604:             $domneedscache = $serverhomedom;
 1605:         }
 1606:     }
 1607:     if ($domneedscache) {
 1608:         &do_cache_new('loadbalancing',$domneedscache,$is_balancer,$cachetime);
 1609:     }
 1610:     if ($is_balancer) {
 1611:         my $lowest_load = 30000;
 1612:         if (ref($offloadto) eq 'HASH') {
 1613:             if (ref($offloadto->{'primary'}) eq 'ARRAY') {
 1614:                 foreach my $try_server (@{$offloadto->{'primary'}}) {
 1615:                     ($otherserver,$lowest_load) =
 1616:                         &compare_server_load($try_server,$otherserver,$lowest_load);
 1617:                 }
 1618:             }
 1619:             my $found_server = ($otherserver ne '' && $lowest_load < 100);
 1620: 
 1621:             if (!$found_server) {
 1622:                 if (ref($offloadto->{'default'}) eq 'ARRAY') {
 1623:                     foreach my $try_server (@{$offloadto->{'default'}}) {
 1624:                         ($otherserver,$lowest_load) =
 1625:                             &compare_server_load($try_server,$otherserver,$lowest_load);
 1626:                     }
 1627:                 }
 1628:             }
 1629:         } elsif (ref($offloadto) eq 'ARRAY') {
 1630:             if (@{$offloadto} == 1) {
 1631:                 $otherserver = $offloadto->[0];
 1632:             } elsif (@{$offloadto} > 1) {
 1633:                 foreach my $try_server (@{$offloadto}) {
 1634:                     ($otherserver,$lowest_load) =
 1635:                         &compare_server_load($try_server,$otherserver,$lowest_load);
 1636:                 }
 1637:             }
 1638:         }
 1639:         unless ($caller eq 'login') {
 1640:             if (($otherserver ne '') && (grep(/^\Q$otherserver\E$/,@hosts))) {
 1641:                 $is_balancer = 0;
 1642:                 if ($uname ne '' && $udom ne '') {
 1643:                     if (($env{'user.name'} eq $uname) && ($env{'user.domain'} eq $udom)) {
 1644:                         &appenv({'user.loadbalexempt'     => $lonhost,
 1645:                                  'user.loadbalcheck.time' => time});
 1646:                     }
 1647:                 }
 1648:             }
 1649:         }
 1650:         unless ($homeintdom) {
 1651:             undef($setcookie);
 1652:         }
 1653:     }
 1654:     return ($is_balancer,$otherserver,$setcookie,$offloadto,$dom_balancers);
 1655: }
 1656: 
 1657: sub check_balancer_result {
 1658:     my ($result,@hosts) = @_;
 1659:     my ($is_balancer,$currtargets,$currrules,$setcookie,$dom_balancers);
 1660:     if (ref($result) eq 'HASH') {
 1661:         if ($result->{'lonhost'} ne '') {
 1662:             my $currbalancer = $result->{'lonhost'};
 1663:             if (grep(/^\Q$currbalancer\E$/,@hosts)) {
 1664:                 $is_balancer = 1;
 1665:                 $currtargets = $result->{'targets'};
 1666:                 $currrules = $result->{'rules'};
 1667:             }
 1668:             $dom_balancers = $currbalancer;
 1669:         } else {
 1670:             if (keys(%{$result})) {
 1671:                 foreach my $key (keys(%{$result})) {
 1672:                     if (($key ne '') && (grep(/^\Q$key\E$/,@hosts)) &&
 1673:                         (ref($result->{$key}) eq 'HASH')) {
 1674:                         $is_balancer = 1;
 1675:                         $currrules = $result->{$key}{'rules'};
 1676:                         $currtargets = $result->{$key}{'targets'};
 1677:                         $setcookie = $result->{$key}{'cookie'};
 1678:                         last;
 1679:                     }
 1680:                 }
 1681:                 $dom_balancers = join(',',sort(keys(%{$result})));
 1682:             }
 1683:         }
 1684:     }
 1685:     return ($is_balancer,$currtargets,$currrules,$setcookie,$dom_balancers);
 1686: }
 1687: 
 1688: sub get_loadbalancer_targets {
 1689:     my ($rule_in_effect,$currtargets,$uname,$udom) = @_;
 1690:     my $offloadto;
 1691:     if ($rule_in_effect eq 'none') {
 1692:         return [$perlvar{'lonHostID'}];
 1693:     } elsif ($rule_in_effect eq '') {
 1694:         $offloadto = $currtargets;
 1695:     } else {
 1696:         if ($rule_in_effect eq 'homeserver') {
 1697:             my $homeserver = &homeserver($uname,$udom);
 1698:             if ($homeserver ne 'no_host') {
 1699:                 $offloadto = [$homeserver];
 1700:             }
 1701:         } elsif ($rule_in_effect eq 'externalbalancer') {
 1702:             my %domconfig =
 1703:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
 1704:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
 1705:                 if ($domconfig{'loadbalancing'}{'lonhost'} ne '') {
 1706:                     if (&hostname($domconfig{'loadbalancing'}{'lonhost'}) ne '') {
 1707:                         $offloadto = [$domconfig{'loadbalancing'}{'lonhost'}];
 1708:                     }
 1709:                 }
 1710:             } else {
 1711:                 my %servers = &internet_dom_servers($udom);
 1712:                 my ($remotebalancer,$remotetargets) = &get_lonbalancer_config(\%servers);
 1713:                 if (&hostname($remotebalancer) ne '') {
 1714:                     $offloadto = [$remotebalancer];
 1715:                 }
 1716:             }
 1717:         } elsif (&hostname($rule_in_effect) ne '') {
 1718:             $offloadto = [$rule_in_effect];
 1719:         }
 1720:     }
 1721:     return $offloadto;
 1722: }
 1723: 
 1724: sub internet_dom_servers {
 1725:     my ($dom) = @_;
 1726:     my (%uniqservers,%servers);
 1727:     my $primaryserver = &hostname(&domain($dom,'primary'));
 1728:     my @machinedoms = &machine_domains($primaryserver);
 1729:     foreach my $mdom (@machinedoms) {
 1730:         my %currservers = %servers;
 1731:         my %server = &get_servers($mdom);
 1732:         %servers = (%currservers,%server);
 1733:     }
 1734:     my %by_hostname;
 1735:     foreach my $id (keys(%servers)) {
 1736:         push(@{$by_hostname{$servers{$id}}},$id);
 1737:     }
 1738:     foreach my $hostname (sort(keys(%by_hostname))) {
 1739:         if (@{$by_hostname{$hostname}} > 1) {
 1740:             my $match = 0;
 1741:             foreach my $id (@{$by_hostname{$hostname}}) {
 1742:                 if (&host_domain($id) eq $dom) {
 1743:                     $uniqservers{$id} = $hostname;
 1744:                     $match = 1;
 1745:                 }
 1746:             }
 1747:             unless ($match) {
 1748:                 $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
 1749:             }
 1750:         } else {
 1751:             $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
 1752:         }
 1753:     }
 1754:     return %uniqservers;
 1755: }
 1756: 
 1757: sub trusted_domains {
 1758:     my ($cmdtype,$calldom) = @_;
 1759:     my ($trusted,$untrusted);
 1760:     if (&domain($calldom) eq '') {
 1761:         return ($trusted,$untrusted);
 1762:     }
 1763:     unless ($cmdtype =~ /^(content|shared|enroll|coaurem|othcoau|domroles|catalog|reqcrs|msg)$/) {
 1764:         return ($trusted,$untrusted);
 1765:     }
 1766:     my $callprimary = &domain($calldom,'primary');
 1767:     my $intcalldom = &Apache::lonnet::internet_dom($callprimary);
 1768:     if ($intcalldom eq '') {
 1769:         return ($trusted,$untrusted);
 1770:     }
 1771: 
 1772:     my ($trustconfig,$cached)=&Apache::lonnet::is_cached_new('trust',$calldom);
 1773:     unless (defined($cached)) {
 1774:         my %domconfig = &Apache::lonnet::get_dom('configuration',['trust'],$calldom);
 1775:         &Apache::lonnet::do_cache_new('trust',$calldom,$domconfig{'trust'},3600);
 1776:         $trustconfig = $domconfig{'trust'};
 1777:     }
 1778:     if (ref($trustconfig)) {
 1779:         my (%possexc,%possinc,@allexc,@allinc); 
 1780:         if (ref($trustconfig->{$cmdtype}) eq 'HASH') {
 1781:             if (ref($trustconfig->{$cmdtype}->{'exc'}) eq 'ARRAY') {
 1782:                 map { $possexc{$_} = 1; } @{$trustconfig->{$cmdtype}->{'exc'}}; 
 1783:             }
 1784:             if (ref($trustconfig->{$cmdtype}->{'inc'}) eq 'ARRAY') {
 1785:                 $possinc{$intcalldom} = 1;
 1786:                 map { $possinc{$_} = 1; } @{$trustconfig->{$cmdtype}->{'inc'}};
 1787:             }
 1788:         }
 1789:         if (keys(%possexc)) {
 1790:             if (keys(%possinc)) {
 1791:                 foreach my $key (sort(keys(%possexc))) {
 1792:                     next if ($key eq $intcalldom);
 1793:                     unless ($possinc{$key}) {
 1794:                         push(@allexc,$key);
 1795:                     }
 1796:                 }
 1797:             } else {
 1798:                 @allexc = sort(keys(%possexc));
 1799:             }
 1800:         }
 1801:         if (keys(%possinc)) {
 1802:             $possinc{$intcalldom} = 1;
 1803:             @allinc = sort(keys(%possinc));
 1804:         }
 1805:         if ((@allexc > 0) || (@allinc > 0)) {
 1806:             my %doms_by_intdom;
 1807:             my %allintdoms = &all_host_intdom();
 1808:             my %alldoms = &all_host_domain();
 1809:             foreach my $key (%allintdoms) {
 1810:                 if (ref($doms_by_intdom{$allintdoms{$key}}) eq 'ARRAY') {
 1811:                     unless (grep(/^\Q$alldoms{$key}\E$/,@{$doms_by_intdom{$allintdoms{$key}}})) {
 1812:                         push(@{$doms_by_intdom{$allintdoms{$key}}},$alldoms{$key});
 1813:                     }
 1814:                 } else {
 1815:                     $doms_by_intdom{$allintdoms{$key}} = [$alldoms{$key}]; 
 1816:                 }
 1817:             }
 1818:             foreach my $exc (@allexc) {
 1819:                 if (ref($doms_by_intdom{$exc}) eq 'ARRAY') {
 1820:                     push(@{$untrusted},@{$doms_by_intdom{$exc}});
 1821:                 }
 1822:             }
 1823:             foreach my $inc (@allinc) {
 1824:                 if (ref($doms_by_intdom{$inc}) eq 'ARRAY') {
 1825:                     push(@{$trusted},@{$doms_by_intdom{$inc}});
 1826:                 }
 1827:             }
 1828:         }
 1829:     }
 1830:     return ($trusted,$untrusted);
 1831: }
 1832: 
 1833: sub will_trust {
 1834:     my ($cmdtype,$domain,$possdom) = @_;
 1835:     return 1 if ($domain eq $possdom);
 1836:     my ($trustedref,$untrustedref) = &trusted_domains($cmdtype,$possdom);
 1837:     my $willtrust; 
 1838:     if ((ref($trustedref) eq 'ARRAY') && (@{$trustedref} > 0)) {
 1839:         if (grep(/^\Q$domain\E$/,@{$trustedref})) {
 1840:             $willtrust = 1;
 1841:         }
 1842:     } elsif ((ref($untrustedref) eq 'ARRAY') && (@{$untrustedref} > 0)) {
 1843:         unless (grep(/^\Q$domain\E$/,@{$untrustedref})) {
 1844:             $willtrust = 1;
 1845:         }
 1846:     } else {
 1847:         $willtrust = 1;
 1848:     }
 1849:     return $willtrust;
 1850: }
 1851: 
 1852: # ---------------------- Find the homebase for a user from domain's lib servers
 1853: 
 1854: my %homecache;
 1855: sub homeserver {
 1856:     my ($uname,$udom,$ignoreBadCache)=@_;
 1857:     my $index="$uname:$udom";
 1858: 
 1859:     if (exists($homecache{$index})) { return $homecache{$index}; }
 1860: 
 1861:     my %servers = &get_servers($udom,'library');
 1862:     foreach my $tryserver (keys(%servers)) {
 1863:         next if ($ignoreBadCache ne 'true' && 
 1864: 		 exists($badServerCache{$tryserver}));
 1865: 
 1866: 	my $answer=reply("home:$udom:$uname",$tryserver);
 1867: 	if ($answer eq 'found') {
 1868: 	    delete($badServerCache{$tryserver}); 
 1869: 	    return $homecache{$index}=$tryserver;
 1870: 	} elsif ($answer eq 'no_host') {
 1871: 	    $badServerCache{$tryserver}=1;
 1872: 	}
 1873:     }    
 1874:     return 'no_host';
 1875: }
 1876: 
 1877: # ----- Find the usernames behind a list of student/employee IDs or clicker IDs
 1878: 
 1879: sub idget {
 1880:     my ($udom,$idsref,$namespace)=@_;
 1881:     my %returnhash=();
 1882:     my @ids=(); 
 1883:     if (ref($idsref) eq 'ARRAY') {
 1884:         @ids = @{$idsref};
 1885:     } else {
 1886:         return %returnhash; 
 1887:     }
 1888:     if ($namespace eq '') {
 1889:         $namespace = 'ids';
 1890:     }
 1891:     
 1892:     my %servers = &get_servers($udom,'library');
 1893:     foreach my $tryserver (keys(%servers)) {
 1894: 	my $idlist=join('&', map { &escape($_); } @ids);
 1895: 	if ($namespace eq 'ids') {
 1896: 	    $idlist=~tr/A-Z/a-z/;
 1897: 	}
 1898: 	my $reply;
 1899: 	if ($namespace eq 'ids') {
 1900: 	    $reply=&reply("idget:$udom:".$idlist,$tryserver);
 1901: 	} else {
 1902: 	    $reply=&reply("getdom:$udom:$namespace:$idlist",$tryserver);
 1903: 	}
 1904: 	my @answer=();
 1905: 	if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
 1906: 	    @answer=split(/\&/,$reply);
 1907: 	}                    ;
 1908: 	my $i;
 1909: 	for ($i=0;$i<=$#ids;$i++) {
 1910: 	    if ($answer[$i]) {
 1911: 		$returnhash{$ids[$i]}=&unescape($answer[$i]);
 1912: 	    }
 1913: 	}
 1914:     }
 1915:     return %returnhash;
 1916: }
 1917: 
 1918: # ------------------------------------- Find the IDs behind a list of usernames
 1919: 
 1920: sub idrget {
 1921:     my ($udom,@unames)=@_;
 1922:     my %returnhash=();
 1923:     foreach my $uname (@unames) {
 1924:         $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
 1925:     }
 1926:     return %returnhash;
 1927: }
 1928: 
 1929: # Store away a list of names and associated student/employee IDs or clicker IDs
 1930: 
 1931: sub idput {
 1932:     my ($udom,$idsref,$uhom,$namespace)=@_;
 1933:     my %servers=();
 1934:     my %ids=();
 1935:     my %byid = ();
 1936:     if (ref($idsref) eq 'HASH') {
 1937:         %ids=%{$idsref};
 1938:     }
 1939:     if ($namespace eq '') {
 1940:         $namespace = 'ids'; 
 1941:     }
 1942:     foreach my $uname (keys(%ids)) {
 1943: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
 1944:         if ($uhom eq '') {
 1945:             $uhom=&homeserver($uname,$udom);
 1946:         }
 1947:         if ($uhom ne 'no_host') {
 1948:             my $esc_unam=&escape($uname);
 1949:             if ($namespace eq 'ids') {
 1950:                 my $id=&escape($ids{$uname});
 1951:                 $id=~tr/A-Z/a-z/;
 1952:                 my $esc_unam=&escape($uname);
 1953:                 $servers{$uhom}.=$id.'='.$esc_unam.'&';
 1954:             } else {
 1955:                 my @currids = split(/,/,$ids{$uname});
 1956:                 foreach my $id (@currids) {
 1957:                     $byid{$uhom}{$id} .= $uname.',';
 1958:                 }
 1959:             }
 1960:         }
 1961:     }
 1962:     if ($namespace eq 'clickers') {
 1963:         foreach my $server (keys(%byid)) {
 1964:             if (ref($byid{$server}) eq 'HASH') {
 1965:                 foreach my $id (keys(%{$byid{$server}})) {
 1966:                     $byid{$server} =~ s/,$//;
 1967:                     $servers{$uhom}.=&escape($id).'='.&escape($byid{$server}).'&'; 
 1968:                 }
 1969:             }
 1970:         }
 1971:     }
 1972:     foreach my $server (keys(%servers)) {
 1973:         $servers{$server} =~ s/\&$//;
 1974:         if ($namespace eq 'ids') {     
 1975:             &critical('idput:'.$udom.':'.$servers{$server},$server);
 1976:         } else {
 1977:             &critical('updateclickers:'.$udom.':add:'.$servers{$server},$server);
 1978:         }
 1979:     }
 1980: }
 1981: 
 1982: # ------------- Delete unwanted student/employee IDs or clicker IDs from domain
 1983: 
 1984: sub iddel {
 1985:     my ($udom,$idshashref,$uhome,$namespace)=@_;
 1986:     my %result=();
 1987:     my %ids=();
 1988:     my %byid = ();
 1989:     if (ref($idshashref) eq 'HASH') {
 1990:         %ids=%{$idshashref};
 1991:     } else {
 1992:         return %result;
 1993:     }
 1994:     if ($namespace eq '') {
 1995:         $namespace = 'ids';
 1996:     }
 1997:     my %servers=();
 1998:     while (my ($id,$unamestr) = each(%ids)) {
 1999:         if ($namespace eq 'ids') {
 2000:             my $uhom = $uhome;
 2001:             if ($uhom eq '') { 
 2002:                 $uhom=&homeserver($unamestr,$udom);
 2003:             }
 2004:             if ($uhom ne 'no_host') {
 2005:                 $servers{$uhom}.='&'.&escape($id);
 2006:             }
 2007:          } else {
 2008:             my @curritems = split(/,/,$ids{$id});
 2009:             foreach my $uname (@curritems) {
 2010:                 my $uhom = $uhome;
 2011:                 if ($uhom eq '') {
 2012:                     $uhom=&homeserver($uname,$udom);
 2013:                 }
 2014:                 if ($uhom ne 'no_host') { 
 2015:                     $byid{$uhom}{$id} .= $uname.',';
 2016:                 }
 2017:             }
 2018:         }
 2019:     }
 2020:     if ($namespace eq 'clickers') {
 2021:         foreach my $server (keys(%byid)) {
 2022:             if (ref($byid{$server}) eq 'HASH') {
 2023:                 foreach my $id (keys(%{$byid{$server}})) {
 2024:                     $byid{$server}{$id} =~ s/,$//;
 2025:                     $servers{$server}.=&escape($id).'='.&escape($byid{$server}{$id}).'&';
 2026:                 }
 2027:             }
 2028:         }
 2029:     }
 2030:     foreach my $server (keys(%servers)) {
 2031:         $servers{$server} =~ s/\&$//;
 2032:         if ($namespace eq 'ids') {
 2033:             $result{$server} = &critical('iddel:'.$udom.':'.$servers{$server},$uhome);
 2034:         } elsif ($namespace eq 'clickers') {
 2035:             $result{$server} = &critical('updateclickers:'.$udom.':del:'.$servers{$server},$server);
 2036:         }
 2037:     }
 2038:     return %result;
 2039: }
 2040: 
 2041: # ----- Update clicker ID-to-username look-ups in clickers.db on library server 
 2042: 
 2043: sub updateclickers {
 2044:     my ($udom,$action,$idshashref,$uhome,$critical) = @_;
 2045:     my %clickers;
 2046:     if (ref($idshashref) eq 'HASH') {
 2047:         %clickers=%{$idshashref};
 2048:     } else {
 2049:         return;
 2050:     }
 2051:     my $items='';
 2052:     foreach my $item (keys(%clickers)) {
 2053:         $items.=&escape($item).'='.&escape($clickers{$item}).'&';
 2054:     }
 2055:     $items=~s/\&$//;
 2056:     my $request = "updateclickers:$udom:$action:$items";
 2057:     if ($critical) {
 2058:         return &critical($request,$uhome);
 2059:     } else {
 2060:         return &reply($request,$uhome);
 2061:     }
 2062: }
 2063: 
 2064: # ------------------------------dump from db file owned by domainconfig user
 2065: sub dump_dom {
 2066:     my ($namespace, $udom, $regexp) = @_;
 2067: 
 2068:     $udom ||= $env{'user.domain'};
 2069: 
 2070:     return () unless $udom;
 2071: 
 2072:     return &dump($namespace, $udom, &get_domainconfiguser($udom), $regexp);
 2073: }
 2074: 
 2075: # ------------------------------------------ get items from domain db files   
 2076: 
 2077: sub get_dom {
 2078:     my ($namespace,$storearr,$udom,$uhome)=@_;
 2079:     return if ($udom eq 'public');
 2080:     my $items='';
 2081:     foreach my $item (@$storearr) {
 2082:         $items.=&escape($item).'&';
 2083:     }
 2084:     $items=~s/\&$//;
 2085:     if (!$udom) {
 2086:         $udom=$env{'user.domain'};
 2087:         return if ($udom eq 'public');
 2088:         if (defined(&domain($udom,'primary'))) {
 2089:             $uhome=&domain($udom,'primary');
 2090:         } else {
 2091:             undef($uhome);
 2092:         }
 2093:     } else {
 2094:         if (!$uhome) {
 2095:             if (defined(&domain($udom,'primary'))) {
 2096:                 $uhome=&domain($udom,'primary');
 2097:             }
 2098:         }
 2099:     }
 2100:     if ($udom && $uhome && ($uhome ne 'no_host')) {
 2101:         my $rep;
 2102:         if ($namespace =~ /^enc/) {
 2103:             $rep=&reply("encrypt:egetdom:$udom:$namespace:$items",$uhome);
 2104:         } else {
 2105:             $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
 2106:         }
 2107:         my %returnhash;
 2108:         if ($rep eq '' || $rep =~ /^error: 2 /) {
 2109:             return %returnhash;
 2110:         }
 2111:         my @pairs=split(/\&/,$rep);
 2112:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
 2113:             return @pairs;
 2114:         }
 2115:         my $i=0;
 2116:         foreach my $item (@$storearr) {
 2117:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
 2118:             $i++;
 2119:         }
 2120:         return %returnhash;
 2121:     } else {
 2122:         &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
 2123:     }
 2124: }
 2125: 
 2126: # -------------------------------------------- put items in domain db files 
 2127: 
 2128: sub put_dom {
 2129:     my ($namespace,$storehash,$udom,$uhome)=@_;
 2130:     if (!$udom) {
 2131:         $udom=$env{'user.domain'};
 2132:         if (defined(&domain($udom,'primary'))) {
 2133:             $uhome=&domain($udom,'primary');
 2134:         } else {
 2135:             undef($uhome);
 2136:         }
 2137:     } else {
 2138:         if (!$uhome) {
 2139:             if (defined(&domain($udom,'primary'))) {
 2140:                 $uhome=&domain($udom,'primary');
 2141:             }
 2142:         }
 2143:     } 
 2144:     if ($udom && $uhome && ($uhome ne 'no_host')) {
 2145:         my $items='';
 2146:         foreach my $item (keys(%$storehash)) {
 2147:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 2148:         }
 2149:         $items=~s/\&$//;
 2150:         if ($namespace =~ /^enc/) {
 2151:             return &reply("encrypt:putdom:$udom:$namespace:$items",$uhome);
 2152:         } else {
 2153:             return &reply("putdom:$udom:$namespace:$items",$uhome);
 2154:         }
 2155:     } else {
 2156:         &logthis("put_dom failed - no homeserver and/or domain");
 2157:     }
 2158: }
 2159: 
 2160: # --------------------- newput for items in db file owned by domainconfig user
 2161: sub newput_dom {
 2162:     my ($namespace,$storehash,$udom) = @_;
 2163:     my $result;
 2164:     if (!$udom) {
 2165:         $udom=$env{'user.domain'};
 2166:     }
 2167:     if ($udom) {
 2168:         my $uname = &get_domainconfiguser($udom);
 2169:         $result = &newput($namespace,$storehash,$udom,$uname);
 2170:     }
 2171:     return $result;
 2172: }
 2173: 
 2174: # --------------------- delete for items in db file owned by domainconfig user
 2175: sub del_dom {
 2176:     my ($namespace,$storearr,$udom)=@_;
 2177:     if (ref($storearr) eq 'ARRAY') {
 2178:         if (!$udom) {
 2179:             $udom=$env{'user.domain'};
 2180:         }
 2181:         if ($udom) {
 2182:             my $uname = &get_domainconfiguser($udom); 
 2183:             return &del($namespace,$storearr,$udom,$uname);
 2184:         }
 2185:     }
 2186: }
 2187: 
 2188: # ----------------------------------construct domainconfig user for a domain 
 2189: sub get_domainconfiguser {
 2190:     my ($udom) = @_;
 2191:     return $udom.'-domainconfig';
 2192: }
 2193: 
 2194: sub retrieve_inst_usertypes {
 2195:     my ($udom) = @_;
 2196:     my (%returnhash,@order);
 2197:     my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
 2198:     if ((ref($domdefs{'inststatustypes'}) eq 'HASH') && 
 2199:         (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
 2200:         return ($domdefs{'inststatustypes'},$domdefs{'inststatusorder'});
 2201:     } else {
 2202:         if (defined(&domain($udom,'primary'))) {
 2203:             my $uhome=&domain($udom,'primary');
 2204:             my $rep=&reply("inst_usertypes:$udom",$uhome);
 2205:             if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
 2206:                 &logthis("retrieve_inst_usertypes failed - $rep returned from $uhome in domain: $udom");
 2207:                 return (\%returnhash,\@order);
 2208:             }
 2209:             my ($hashitems,$orderitems) = split(/:/,$rep); 
 2210:             my @pairs=split(/\&/,$hashitems);
 2211:             foreach my $item (@pairs) {
 2212:                 my ($key,$value)=split(/=/,$item,2);
 2213:                 $key = &unescape($key);
 2214:                 next if ($key =~ /^error: 2 /);
 2215:                 $returnhash{$key}=&thaw_unescape($value);
 2216:             }
 2217:             my @esc_order = split(/\&/,$orderitems);
 2218:             foreach my $item (@esc_order) {
 2219:                 push(@order,&unescape($item));
 2220:             }
 2221:         } else {
 2222:             &logthis("retrieve_inst_usertypes failed - no primary domain server for $udom");
 2223:         }
 2224:         return (\%returnhash,\@order);
 2225:     }
 2226: }
 2227: 
 2228: sub is_domainimage {
 2229:     my ($url) = @_;
 2230:     if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+[^/]-) {
 2231:         if (&domain($1) ne '') {
 2232:             return '1';
 2233:         }
 2234:     }
 2235:     return;
 2236: }
 2237: 
 2238: sub inst_directory_query {
 2239:     my ($srch) = @_;
 2240:     my $udom = $srch->{'srchdomain'};
 2241:     my %results;
 2242:     my $homeserver = &domain($udom,'primary');
 2243:     my $outcome;
 2244:     if ($homeserver ne '') {
 2245:         unless ($homeserver eq $perlvar{'lonHostID'}) {
 2246:             if ($srch->{'srchby'} eq 'email') {
 2247:                 my $lcrev = &get_server_loncaparev(undef,$homeserver);
 2248:                 my ($major,$minor) = ($lcrev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
 2249:                 if (($major eq '' && $minor eq '') || ($major < 2) ||
 2250:                     (($major == 2) && ($minor < 12))) {
 2251:                     return;
 2252:                 }
 2253:             }
 2254:         }
 2255: 	my $queryid=&reply("querysend:instdirsearch:".
 2256: 			   &escape($srch->{'srchby'}).':'.
 2257: 			   &escape($srch->{'srchterm'}).':'.
 2258: 			   &escape($srch->{'srchtype'}),$homeserver);
 2259: 	my $host=&hostname($homeserver);
 2260: 	if ($queryid !~/^\Q$host\E\_/) {
 2261: 	    &logthis('institutional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.' in domain '.$udom);
 2262: 	    return;
 2263: 	}
 2264: 	my $response = &get_query_reply($queryid);
 2265: 	my $maxtries = 5;
 2266: 	my $tries = 1;
 2267: 	while (($response=~/^timeout/) && ($tries < $maxtries)) {
 2268: 	    $response = &get_query_reply($queryid);
 2269: 	    $tries ++;
 2270: 	}
 2271: 
 2272:         if (!&error($response) && $response ne 'refused') {
 2273:             if ($response eq 'unavailable') {
 2274:                 $outcome = $response;
 2275:             } else {
 2276:                 $outcome = 'ok';
 2277:                 my @matches = split(/\n/,$response);
 2278:                 foreach my $match (@matches) {
 2279:                     my ($key,$value) = split(/=/,$match);
 2280:                     $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
 2281:                 }
 2282:             }
 2283:         }
 2284:     }
 2285:     return ($outcome,%results);
 2286: }
 2287: 
 2288: sub usersearch {
 2289:     my ($srch) = @_;
 2290:     my $dom = $srch->{'srchdomain'};
 2291:     my %results;
 2292:     my %libserv = &all_library();
 2293:     my $query = 'usersearch';
 2294:     foreach my $tryserver (keys(%libserv)) {
 2295:         if (&host_domain($tryserver) eq $dom) {
 2296:             unless ($tryserver eq $perlvar{'lonHostID'}) {
 2297:                 if ($srch->{'srchby'} eq 'email') {
 2298:                     my $lcrev = &get_server_loncaparev(undef,$tryserver);
 2299:                     my ($major,$minor) = ($lcrev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
 2300:                     next if (($major eq '' && $minor eq '') || ($major < 2) ||
 2301:                              (($major == 2) && ($minor < 12)));
 2302:                 }
 2303:             }
 2304:             my $host=&hostname($tryserver);
 2305:             my $queryid=
 2306:                 &reply("querysend:".&escape($query).':'.
 2307:                        &escape($srch->{'srchby'}).':'.
 2308:                        &escape($srch->{'srchtype'}).':'.
 2309:                        &escape($srch->{'srchterm'}),$tryserver);
 2310:             if ($queryid !~/^\Q$host\E\_/) {
 2311:                 &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
 2312:                 next;
 2313:             }
 2314:             my $reply = &get_query_reply($queryid);
 2315:             my $maxtries = 1;
 2316:             my $tries = 1;
 2317:             while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 2318:                 $reply = &get_query_reply($queryid);
 2319:                 $tries ++;
 2320:             }
 2321:             if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 2322:                 &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') -  maxtries: '.$maxtries.' tries: '.$tries);
 2323:             } else {
 2324:                 my @matches;
 2325:                 if ($reply =~ /\n/) {
 2326:                     @matches = split(/\n/,$reply);
 2327:                 } else {
 2328:                     @matches = split(/\&/,$reply);
 2329:                 }
 2330:                 foreach my $match (@matches) {
 2331:                     my ($uname,$udom,%userhash);
 2332:                     foreach my $entry (split(/:/,$match)) {
 2333:                         my ($key,$value) =
 2334:                             map {&unescape($_);} split(/=/,$entry);
 2335:                         $userhash{$key} = $value;
 2336:                         if ($key eq 'username') {
 2337:                             $uname = $value;
 2338:                         } elsif ($key eq 'domain') {
 2339:                             $udom = $value;
 2340:                         }
 2341:                     }
 2342:                     $results{$uname.':'.$udom} = \%userhash;
 2343:                 }
 2344:             }
 2345:         }
 2346:     }
 2347:     return %results;
 2348: }
 2349: 
 2350: sub get_instuser {
 2351:     my ($udom,$uname,$id) = @_;
 2352:     my $homeserver = &domain($udom,'primary');
 2353:     my ($outcome,%results);
 2354:     if ($homeserver ne '') {
 2355:         my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
 2356:                            &escape($id).':'.&escape($udom),$homeserver);
 2357:         my $host=&hostname($homeserver);
 2358:         if ($queryid !~/^\Q$host\E\_/) {
 2359:             &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
 2360:             return;
 2361:         }
 2362:         my $response = &get_query_reply($queryid);
 2363:         my $maxtries = 5;
 2364:         my $tries = 1;
 2365:         while (($response=~/^timeout/) && ($tries < $maxtries)) {
 2366:             $response = &get_query_reply($queryid);
 2367:             $tries ++;
 2368:         }
 2369:         if (!&error($response) && $response ne 'refused') {
 2370:             if ($response eq 'unavailable') {
 2371:                 $outcome = $response;
 2372:             } else {
 2373:                 $outcome = 'ok';
 2374:                 my @matches = split(/\n/,$response);
 2375:                 foreach my $match (@matches) {
 2376:                     my ($key,$value) = split(/=/,$match);
 2377:                     $results{&unescape($key)} = &thaw_unescape($value);
 2378:                 }
 2379:             }
 2380:         }
 2381:     }
 2382:     my %userinfo;
 2383:     if (ref($results{$uname}) eq 'HASH') {
 2384:         %userinfo = %{$results{$uname}};
 2385:     } 
 2386:     return ($outcome,%userinfo);
 2387: }
 2388: 
 2389: sub get_multiple_instusers {
 2390:     my ($udom,$users,$caller) = @_;
 2391:     my ($outcome,$results);
 2392:     if (ref($users) eq 'HASH') {
 2393:         my $count = keys(%{$users}); 
 2394:         my $requested = &freeze_escape($users);
 2395:         my $homeserver = &domain($udom,'primary');
 2396:         if ($homeserver ne '') {
 2397:             my $queryid=&reply('querysend:getmultinstusers:::'.$caller.'='.$requested,$homeserver);
 2398:             my $host=&hostname($homeserver);
 2399:             if ($queryid !~/^\Q$host\E\_/) {
 2400:                 &logthis('get_multiple_instusers invalid queryid: '.$queryid.
 2401:                          ' for host: '.$homeserver.'in domain '.$udom);
 2402:                 return ($outcome,$results);
 2403:             }
 2404:             my $response = &get_query_reply($queryid);
 2405:             my $maxtries = 5;
 2406:             if ($count > 100) {
 2407:                 $maxtries = 1+int($count/20);
 2408:             }
 2409:             my $tries = 1;
 2410:             while (($response=~/^timeout/) && ($tries <= $maxtries)) {
 2411:                 $response = &get_query_reply($queryid);
 2412:                 $tries ++;
 2413:             }
 2414:             if ($response eq '') {
 2415:                 $results = {};
 2416:                 foreach my $key (keys(%{$users})) {
 2417:                     my ($uname,$id);
 2418:                     if ($caller eq 'id') {
 2419:                         $id = $key;
 2420:                     } else {
 2421:                         $uname = $key;
 2422:                     }
 2423:                     my ($resp,%info) = &get_instuser($udom,$uname,$id);
 2424:                     $outcome = $resp;
 2425:                     if ($resp eq 'ok') {
 2426:                         %{$results} = (%{$results}, %info);
 2427:                     } else {
 2428:                         last;
 2429:                     }
 2430:                 }
 2431:             } elsif(!&error($response) && ($response ne 'refused')) {
 2432:                 if (($response eq 'unavailable') || ($response eq 'invalid') || ($response eq 'timeout')) {
 2433:                     $outcome = $response;
 2434:                 } else {
 2435:                     ($outcome,my $userdata) = split(/=/,$response,2);
 2436:                     if ($outcome eq 'ok') {
 2437:                         $results = &thaw_unescape($userdata); 
 2438:                     }
 2439:                 }
 2440:             }
 2441:         }
 2442:     }
 2443:     return ($outcome,$results);
 2444: }
 2445: 
 2446: sub inst_rulecheck {
 2447:     my ($udom,$uname,$id,$item,$rules) = @_;
 2448:     my %returnhash;
 2449:     if ($udom ne '') {
 2450:         if (ref($rules) eq 'ARRAY') {
 2451:             @{$rules} = map {&escape($_);} (@{$rules});
 2452:             my $rulestr = join(':',@{$rules});
 2453:             my $homeserver=&domain($udom,'primary');
 2454:             if (($homeserver ne '') && ($homeserver ne 'no_host')) {
 2455:                 my $response;
 2456:                 if ($item eq 'username') {                
 2457:                     $response=&unescape(&reply('instrulecheck:'.&escape($udom).
 2458:                                               ':'.&escape($uname).':'.$rulestr,
 2459:                                               $homeserver));
 2460:                 } elsif ($item eq 'id') {
 2461:                     $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
 2462:                                               ':'.&escape($id).':'.$rulestr,
 2463:                                               $homeserver));
 2464:                 } elsif ($item eq 'selfcreate') {
 2465:                     $response=&unescape(&reply('instselfcreatecheck:'.
 2466:                                                &escape($udom).':'.&escape($uname).
 2467:                                               ':'.$rulestr,$homeserver));
 2468:                 }
 2469:                 if ($response ne 'refused') {
 2470:                     my @pairs=split(/\&/,$response);
 2471:                     foreach my $item (@pairs) {
 2472:                         my ($key,$value)=split(/=/,$item,2);
 2473:                         $key = &unescape($key);
 2474:                         next if ($key =~ /^error: 2 /);
 2475:                         $returnhash{$key}=&thaw_unescape($value);
 2476:                     }
 2477:                 }
 2478:             }
 2479:         }
 2480:     }
 2481:     return %returnhash;
 2482: }
 2483: 
 2484: sub inst_userrules {
 2485:     my ($udom,$check) = @_;
 2486:     my (%ruleshash,@ruleorder);
 2487:     if ($udom ne '') {
 2488:         my $homeserver=&domain($udom,'primary');
 2489:         if (($homeserver ne '') && ($homeserver ne 'no_host')) {
 2490:             my $response;
 2491:             if ($check eq 'id') {
 2492:                 $response=&reply('instidrules:'.&escape($udom),
 2493:                                  $homeserver);
 2494:             } elsif ($check eq 'email') {
 2495:                 $response=&reply('instemailrules:'.&escape($udom),
 2496:                                  $homeserver);
 2497:             } else {
 2498:                 $response=&reply('instuserrules:'.&escape($udom),
 2499:                                  $homeserver);
 2500:             }
 2501:             if (($response ne 'refused') && ($response ne 'error') && 
 2502:                 ($response ne 'unknown_cmd') && 
 2503:                 ($response ne 'no_such_host')) {
 2504:                 my ($hashitems,$orderitems) = split(/:/,$response);
 2505:                 my @pairs=split(/\&/,$hashitems);
 2506:                 foreach my $item (@pairs) {
 2507:                     my ($key,$value)=split(/=/,$item,2);
 2508:                     $key = &unescape($key);
 2509:                     next if ($key =~ /^error: 2 /);
 2510:                     $ruleshash{$key}=&thaw_unescape($value);
 2511:                 }
 2512:                 my @esc_order = split(/\&/,$orderitems);
 2513:                 foreach my $item (@esc_order) {
 2514:                     push(@ruleorder,&unescape($item));
 2515:                 }
 2516:             }
 2517:         }
 2518:     }
 2519:     return (\%ruleshash,\@ruleorder);
 2520: }
 2521: 
 2522: # ------------- Get Authentication, Language and User Tools Defaults for Domain
 2523: 
 2524: sub get_domain_defaults {
 2525:     my ($domain,$ignore_cache) = @_;
 2526:     return if (($domain eq '') || ($domain eq 'public'));
 2527:     my $cachetime = 60*60*24;
 2528:     unless ($ignore_cache) {
 2529:         my ($result,$cached)=&is_cached_new('domdefaults',$domain);
 2530:         if (defined($cached)) {
 2531:             if (ref($result) eq 'HASH') {
 2532:                 return %{$result};
 2533:             }
 2534:         }
 2535:     }
 2536:     my %domdefaults;
 2537:     my %domconfig =
 2538:          &Apache::lonnet::get_dom('configuration',['defaults','quotas',
 2539:                                   'requestcourses','inststatus',
 2540:                                   'coursedefaults','usersessions',
 2541:                                   'requestauthor','selfenrollment',
 2542:                                   'coursecategories','ssl','autoenroll',
 2543:                                   'trust','helpsettings'],$domain);
 2544:     my @coursetypes = ('official','unofficial','community','textbook','placement');
 2545:     if (ref($domconfig{'defaults'}) eq 'HASH') {
 2546:         $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'}; 
 2547:         $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
 2548:         $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
 2549:         $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
 2550:         $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
 2551:         $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
 2552:         $domdefaults{'intauth_cost'} = $domconfig{'defaults'}{'intauth_cost'};
 2553:         $domdefaults{'intauth_switch'} = $domconfig{'defaults'}{'intauth_switch'};
 2554:         $domdefaults{'intauth_check'} = $domconfig{'defaults'}{'intauth_check'};
 2555:     } else {
 2556:         $domdefaults{'lang_def'} = &domain($domain,'lang_def');
 2557:         $domdefaults{'auth_def'} = &domain($domain,'auth_def');
 2558:         $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
 2559:     }
 2560:     if (ref($domconfig{'quotas'}) eq 'HASH') {
 2561:         if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
 2562:             $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
 2563:         } else {
 2564:             $domdefaults{'defaultquota'} = $domconfig{'quotas'};
 2565:         }
 2566:         my @usertools = ('aboutme','blog','webdav','portfolio');
 2567:         foreach my $item (@usertools) {
 2568:             if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
 2569:                 $domdefaults{$item} = $domconfig{'quotas'}{$item};
 2570:             }
 2571:         }
 2572:         if (ref($domconfig{'quotas'}{'authorquota'}) eq 'HASH') {
 2573:             $domdefaults{'authorquota'} = $domconfig{'quotas'}{'authorquota'};
 2574:         }
 2575:     }
 2576:     if (ref($domconfig{'requestcourses'}) eq 'HASH') {
 2577:         foreach my $item ('official','unofficial','community','textbook','placement') {
 2578:             $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
 2579:         }
 2580:     }
 2581:     if (ref($domconfig{'requestauthor'}) eq 'HASH') {
 2582:         $domdefaults{'requestauthor'} = $domconfig{'requestauthor'};
 2583:     }
 2584:     if (ref($domconfig{'inststatus'}) eq 'HASH') {
 2585:         foreach my $item ('inststatustypes','inststatusorder','inststatusguest') {
 2586:             $domdefaults{$item} = $domconfig{'inststatus'}{$item};
 2587:         }
 2588:     }
 2589:     if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
 2590:         $domdefaults{'canuse_pdfforms'} = $domconfig{'coursedefaults'}{'canuse_pdfforms'};
 2591:         $domdefaults{'usejsme'} = $domconfig{'coursedefaults'}{'usejsme'};
 2592:         $domdefaults{'uselcmath'} = $domconfig{'coursedefaults'}{'uselcmath'};
 2593:         if (ref($domconfig{'coursedefaults'}{'postsubmit'}) eq 'HASH') {
 2594:             $domdefaults{'postsubmit'} = $domconfig{'coursedefaults'}{'postsubmit'}{'client'};
 2595:         }
 2596:         foreach my $type (@coursetypes) {
 2597:             if (ref($domconfig{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
 2598:                 unless ($type eq 'community') {
 2599:                     $domdefaults{$type.'credits'} = $domconfig{'coursedefaults'}{'coursecredits'}{$type};
 2600:                 }
 2601:             }
 2602:             if (ref($domconfig{'coursedefaults'}{'uploadquota'}) eq 'HASH') {
 2603:                 $domdefaults{$type.'quota'} = $domconfig{'coursedefaults'}{'uploadquota'}{$type};
 2604:             }
 2605:             if ($domdefaults{'postsubmit'} eq 'on') {
 2606:                 if (ref($domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}) eq 'HASH') {
 2607:                     $domdefaults{$type.'postsubtimeout'} = 
 2608:                         $domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}{$type}; 
 2609:                 }
 2610:             }
 2611:         }
 2612:         if (ref($domconfig{'coursedefaults'}{'canclone'}) eq 'HASH') {
 2613:             if (ref($domconfig{'coursedefaults'}{'canclone'}{'instcode'}) eq 'ARRAY') {
 2614:                 my @clonecodes = @{$domconfig{'coursedefaults'}{'canclone'}{'instcode'}};
 2615:                 if (@clonecodes) {
 2616:                     $domdefaults{'canclone'} = join('+',@clonecodes);
 2617:                 }
 2618:             }
 2619:         } elsif ($domconfig{'coursedefaults'}{'canclone'}) {
 2620:             $domdefaults{'canclone'}=$domconfig{'coursedefaults'}{'canclone'};
 2621:         }
 2622:         if ($domconfig{'coursedefaults'}{'texengine'}) {
 2623:             $domdefaults{'texengine'} = $domconfig{'coursedefaults'}{'texengine'};
 2624:         } 
 2625:     }
 2626:     if (ref($domconfig{'usersessions'}) eq 'HASH') {
 2627:         if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
 2628:             $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
 2629:         }
 2630:         if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
 2631:             $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
 2632:         }
 2633:         if (ref($domconfig{'usersessions'}{'offloadnow'}) eq 'HASH') {
 2634:             $domdefaults{'offloadnow'} = $domconfig{'usersessions'}{'offloadnow'};
 2635:         }
 2636:     }
 2637:     if (ref($domconfig{'selfenrollment'}) eq 'HASH') {
 2638:         if (ref($domconfig{'selfenrollment'}{'admin'}) eq 'HASH') {
 2639:             my @settings = ('types','registered','enroll_dates','access_dates','section',
 2640:                             'approval','limit');
 2641:             foreach my $type (@coursetypes) {
 2642:                 if (ref($domconfig{'selfenrollment'}{'admin'}{$type}) eq 'HASH') {
 2643:                     my @mgrdc = ();
 2644:                     foreach my $item (@settings) {
 2645:                         if ($domconfig{'selfenrollment'}{'admin'}{$type}{$item} eq '0') {
 2646:                             push(@mgrdc,$item);
 2647:                         }
 2648:                     }
 2649:                     if (@mgrdc) {
 2650:                         $domdefaults{$type.'selfenrolladmdc'} = join(',',@mgrdc);
 2651:                     }
 2652:                 }
 2653:             }
 2654:         }
 2655:         if (ref($domconfig{'selfenrollment'}{'default'}) eq 'HASH') {
 2656:             foreach my $type (@coursetypes) {
 2657:                 if (ref($domconfig{'selfenrollment'}{'default'}{$type}) eq 'HASH') {
 2658:                     foreach my $item (keys(%{$domconfig{'selfenrollment'}{'default'}{$type}})) {
 2659:                         $domdefaults{$type.'selfenroll'.$item} = $domconfig{'selfenrollment'}{'default'}{$type}{$item};
 2660:                     }
 2661:                 }
 2662:             }
 2663:         }
 2664:     }
 2665:     if (ref($domconfig{'coursecategories'}) eq 'HASH') {
 2666:         $domdefaults{'catauth'} = 'std';
 2667:         $domdefaults{'catunauth'} = 'std';
 2668:         if ($domconfig{'coursecategories'}{'auth'}) { 
 2669:             $domdefaults{'catauth'} = $domconfig{'coursecategories'}{'auth'};
 2670:         }
 2671:         if ($domconfig{'coursecategories'}{'unauth'}) {
 2672:             $domdefaults{'catunauth'} = $domconfig{'coursecategories'}{'unauth'};
 2673:         }
 2674:     }
 2675:     if (ref($domconfig{'ssl'}) eq 'HASH') {
 2676:         if (ref($domconfig{'ssl'}{'replication'}) eq 'HASH') {
 2677:             $domdefaults{'replication'} = $domconfig{'ssl'}{'replication'};
 2678:         }
 2679:         if (ref($domconfig{'ssl'}{'connto'}) eq 'HASH') {
 2680:             $domdefaults{'connect'} = $domconfig{'ssl'}{'connto'};
 2681:         }
 2682:         if (ref($domconfig{'ssl'}{'connfrom'}) eq 'HASH') {
 2683:             $domdefaults{'connect'} = $domconfig{'ssl'}{'connfrom'};
 2684:         }
 2685:     }
 2686:     if (ref($domconfig{'trust'}) eq 'HASH') {
 2687:         my @prefixes = qw(content shared enroll othcoau coaurem domroles catalog reqcrs msg);
 2688:         foreach my $prefix (@prefixes) {
 2689:             if (ref($domconfig{'trust'}{$prefix}) eq 'HASH') {
 2690:                 $domdefaults{'trust'.$prefix} = $domconfig{'trust'}{$prefix};
 2691:             }
 2692:         }
 2693:     }
 2694:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
 2695:         $domdefaults{'autofailsafe'} = $domconfig{'autoenroll'}{'autofailsafe'};
 2696:     }
 2697:     if (ref($domconfig{'helpsettings'}) eq 'HASH') {
 2698:         $domdefaults{'submitbugs'} = $domconfig{'helpsettings'}{'submitbugs'};
 2699:         if (ref($domconfig{'helpsettings'}{'adhoc'}) eq 'HASH') {
 2700:             $domdefaults{'adhocroles'} = $domconfig{'helpsettings'}{'adhoc'};
 2701:         }
 2702:     }
 2703:     &do_cache_new('domdefaults',$domain,\%domdefaults,$cachetime);
 2704:     return %domdefaults;
 2705: }
 2706: 
 2707: sub course_portal_url {
 2708:     my ($cnum,$cdom) = @_;
 2709:     my $chome = &homeserver($cnum,$cdom);
 2710:     my $hostname = &hostname($chome);
 2711:     my $protocol = $protocol{$chome};
 2712:     $protocol = 'http' if ($protocol ne 'https');
 2713:     my %domdefaults = &get_domain_defaults($cdom);
 2714:     my $firsturl;
 2715:     if ($domdefaults{'portal_def'}) {
 2716:         $firsturl = $domdefaults{'portal_def'};
 2717:     } else {
 2718:         $firsturl = $protocol.'://'.$hostname;
 2719:     }
 2720:     return $firsturl;
 2721: }
 2722: 
 2723: # --------------------------------------------------- Assign a key to a student
 2724: 
 2725: sub assign_access_key {
 2726: #
 2727: # a valid key looks like uname:udom#comments
 2728: # comments are being appended
 2729: #
 2730:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
 2731:     $kdom=
 2732:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
 2733:     $knum=
 2734:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
 2735:     $cdom=
 2736:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 2737:     $cnum=
 2738:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 2739:     $udom=$env{'user.name'} unless (defined($udom));
 2740:     $uname=$env{'user.domain'} unless (defined($uname));
 2741:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
 2742:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
 2743:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
 2744:                                                   # assigned to this person
 2745:                                                   # - this should not happen,
 2746:                                                   # unless something went wrong
 2747:                                                   # the first time around
 2748: # ready to assign
 2749:         $logentry=$1.'; '.$logentry;
 2750:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
 2751:                                                  $kdom,$knum) eq 'ok') {
 2752: # key now belongs to user
 2753: 	    my $envkey='key.'.$cdom.'_'.$cnum;
 2754:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
 2755:                 &appenv({'environment.'.$envkey => $ckey});
 2756:                 return 'ok';
 2757:             } else {
 2758:                 return 
 2759:   'error: Count not permanently assign key, will need to be re-entered later.';
 2760: 	    }
 2761:         } else {
 2762:             return 'error: Could not assign key, try again later.';
 2763:         }
 2764:     } elsif (!$existing{$ckey}) {
 2765: # the key does not exist
 2766: 	return 'error: The key does not exist';
 2767:     } else {
 2768: # the key is somebody else's
 2769: 	return 'error: The key is already in use';
 2770:     }
 2771: }
 2772: 
 2773: # ------------------------------------------ put an additional comment on a key
 2774: 
 2775: sub comment_access_key {
 2776: #
 2777: # a valid key looks like uname:udom#comments
 2778: # comments are being appended
 2779: #
 2780:     my ($ckey,$cdom,$cnum,$logentry)=@_;
 2781:     $cdom=
 2782:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 2783:     $cnum=
 2784:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 2785:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
 2786:     if ($existing{$ckey}) {
 2787:         $existing{$ckey}.='; '.$logentry;
 2788: # ready to assign
 2789:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
 2790:                                                  $cdom,$cnum) eq 'ok') {
 2791: 	    return 'ok';
 2792:         } else {
 2793: 	    return 'error: Count not store comment.';
 2794:         }
 2795:     } else {
 2796: # the key does not exist
 2797: 	return 'error: The key does not exist';
 2798:     }
 2799: }
 2800: 
 2801: # ------------------------------------------------------ Generate a set of keys
 2802: 
 2803: sub generate_access_keys {
 2804:     my ($number,$cdom,$cnum,$logentry)=@_;
 2805:     $cdom=
 2806:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 2807:     $cnum=
 2808:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 2809:     unless (&allowed('mky',$cdom)) { return 0; }
 2810:     unless (($cdom) && ($cnum)) { return 0; }
 2811:     if ($number>10000) { return 0; }
 2812:     sleep(2); # make sure don't get same seed twice
 2813:     srand(time()^($$+($$<<15))); # from "Programming Perl"
 2814:     my $total=0;
 2815:     for (my $i=1;$i<=$number;$i++) {
 2816:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
 2817:                   sprintf("%lx",int(100000*rand)).'-'.
 2818:                   sprintf("%lx",int(100000*rand));
 2819:        $newkey=~s/1/g/g; # folks mix up 1 and l
 2820:        $newkey=~s/0/h/g; # and also 0 and O
 2821:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
 2822:        if ($existing{$newkey}) {
 2823:            $i--;
 2824:        } else {
 2825: 	  if (&put('accesskeys',
 2826:               { $newkey => '# generated '.localtime().
 2827:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
 2828:                            '; '.$logentry },
 2829: 		   $cdom,$cnum) eq 'ok') {
 2830:               $total++;
 2831: 	  }
 2832:        }
 2833:     }
 2834:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
 2835:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
 2836:     return $total;
 2837: }
 2838: 
 2839: # ------------------------------------------------------- Validate an accesskey
 2840: 
 2841: sub validate_access_key {
 2842:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
 2843:     $cdom=
 2844:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 2845:     $cnum=
 2846:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 2847:     $udom=$env{'user.domain'} unless (defined($udom));
 2848:     $uname=$env{'user.name'} unless (defined($uname));
 2849:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
 2850:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
 2851: }
 2852: 
 2853: # ------------------------------------- Find the section of student in a course
 2854: sub devalidate_getsection_cache {
 2855:     my ($udom,$unam,$courseid)=@_;
 2856:     my $hashid="$udom:$unam:$courseid";
 2857:     &devalidate_cache_new('getsection',$hashid);
 2858: }
 2859: 
 2860: sub courseid_to_courseurl {
 2861:     my ($courseid) = @_;
 2862:     #already url style courseid
 2863:     return $courseid if ($courseid =~ m{^/});
 2864: 
 2865:     if (exists($env{'course.'.$courseid.'.num'})) {
 2866: 	my $cnum = $env{'course.'.$courseid.'.num'};
 2867: 	my $cdom = $env{'course.'.$courseid.'.domain'};
 2868: 	return "/$cdom/$cnum";
 2869:     }
 2870: 
 2871:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
 2872:     if (exists($courseinfo{'num'})) {
 2873: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
 2874:     }
 2875: 
 2876:     return undef;
 2877: }
 2878: 
 2879: sub getsection {
 2880:     my ($udom,$unam,$courseid)=@_;
 2881:     my $cachetime=1800;
 2882: 
 2883:     my $hashid="$udom:$unam:$courseid";
 2884:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
 2885:     if (defined($cached)) { return $result; }
 2886: 
 2887:     my %Pending; 
 2888:     my %Expired;
 2889:     #
 2890:     # Each role can either have not started yet (pending), be active, 
 2891:     #    or have expired.
 2892:     #
 2893:     # If there is an active role, we are done.
 2894:     #
 2895:     # If there is more than one role which has not started yet, 
 2896:     #     choose the one which will start sooner
 2897:     # If there is one role which has not started yet, return it.
 2898:     #
 2899:     # If there is more than one expired role, choose the one which ended last.
 2900:     # If there is a role which has expired, return it.
 2901:     #
 2902:     $courseid = &courseid_to_courseurl($courseid);
 2903:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
 2904:     foreach my $key (keys(%roleshash)) {
 2905:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
 2906:         my $section=$1;
 2907:         if ($key eq $courseid.'_st') { $section=''; }
 2908:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
 2909:         my $now=time;
 2910:         if (defined($end) && $end && ($now > $end)) {
 2911:             $Expired{$end}=$section;
 2912:             next;
 2913:         }
 2914:         if (defined($start) && $start && ($now < $start)) {
 2915:             $Pending{$start}=$section;
 2916:             next;
 2917:         }
 2918:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
 2919:     }
 2920:     #
 2921:     # Presumedly there will be few matching roles from the above
 2922:     # loop and the sorting time will be negligible.
 2923:     if (scalar(keys(%Pending))) {
 2924:         my ($time) = sort {$a <=> $b} keys(%Pending);
 2925:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
 2926:     } 
 2927:     if (scalar(keys(%Expired))) {
 2928:         my @sorted = sort {$a <=> $b} keys(%Expired);
 2929:         my $time = pop(@sorted);
 2930:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
 2931:     }
 2932:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
 2933: }
 2934: 
 2935: sub save_cache {
 2936:     &purge_remembered();
 2937:     #&Apache::loncommon::validate_page();
 2938:     undef(%env);
 2939:     undef($env_loaded);
 2940: }
 2941: 
 2942: my $to_remember=-1;
 2943: my %remembered;
 2944: my %accessed;
 2945: my $kicks=0;
 2946: my $hits=0;
 2947: sub make_key {
 2948:     my ($name,$id) = @_;
 2949:     if (length($id) > 65 
 2950: 	&& length(&escape($id)) > 200) {
 2951: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
 2952:     }
 2953:     return &escape($name.':'.$id);
 2954: }
 2955: 
 2956: sub devalidate_cache_new {
 2957:     my ($name,$id,$debug) = @_;
 2958:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
 2959:     my $remembered_id=$name.':'.$id;
 2960:     $id=&make_key($name,$id);
 2961:     $memcache->delete($id);
 2962:     delete($remembered{$remembered_id});
 2963:     delete($accessed{$remembered_id});
 2964: }
 2965: 
 2966: sub is_cached_new {
 2967:     my ($name,$id,$debug) = @_;
 2968:     my $remembered_id=$name.':'.$id; # this is to avoid make_key (which is slow) whenever possible
 2969:     if (exists($remembered{$remembered_id})) {
 2970: 	if ($debug) { &Apache::lonnet::logthis("Early return $remembered_id of $remembered{$remembered_id} "); }
 2971: 	$accessed{$remembered_id}=[&gettimeofday()];
 2972: 	$hits++;
 2973: 	return ($remembered{$remembered_id},1);
 2974:     }
 2975:     $id=&make_key($name,$id);
 2976:     my $value = $memcache->get($id);
 2977:     if (!(defined($value))) {
 2978: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
 2979: 	return (undef,undef);
 2980:     }
 2981:     if ($value eq '__undef__') {
 2982: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
 2983: 	$value=undef;
 2984:     }
 2985:     &make_room($remembered_id,$value,$debug);
 2986:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
 2987:     return ($value,1);
 2988: }
 2989: 
 2990: sub do_cache_new {
 2991:     my ($name,$id,$value,$time,$debug) = @_;
 2992:     my $remembered_id=$name.':'.$id;
 2993:     $id=&make_key($name,$id);
 2994:     my $setvalue=$value;
 2995:     if (!defined($setvalue)) {
 2996: 	$setvalue='__undef__';
 2997:     }
 2998:     if (!defined($time) ) {
 2999: 	$time=600;
 3000:     }
 3001:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
 3002:     my $result = $memcache->set($id,$setvalue,$time);
 3003:     if (! $result) {
 3004: 	&logthis("caching of id -> $id  failed");
 3005: 	$memcache->disconnect_all();
 3006:     }
 3007:     # need to make a copy of $value
 3008:     &make_room($remembered_id,$value,$debug);
 3009:     return $value;
 3010: }
 3011: 
 3012: sub make_room {
 3013:     my ($remembered_id,$value,$debug)=@_;
 3014: 
 3015:     $remembered{$remembered_id}= (ref($value)) ? &Storable::dclone($value)
 3016:                                     : $value;
 3017:     if ($to_remember<0) { return; }
 3018:     $accessed{$remembered_id}=[&gettimeofday()];
 3019:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
 3020:     my $to_kick;
 3021:     my $max_time=0;
 3022:     foreach my $other (keys(%accessed)) {
 3023: 	if (&tv_interval($accessed{$other}) > $max_time) {
 3024: 	    $to_kick=$other;
 3025: 	    $max_time=&tv_interval($accessed{$other});
 3026: 	}
 3027:     }
 3028:     delete($remembered{$to_kick});
 3029:     delete($accessed{$to_kick});
 3030:     $kicks++;
 3031:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
 3032:     return;
 3033: }
 3034: 
 3035: sub purge_remembered {
 3036:     #&logthis("Tossing ".scalar(keys(%remembered)));
 3037:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
 3038:     undef(%remembered);
 3039:     undef(%accessed);
 3040: }
 3041: # ------------------------------------- Read an entry from a user's environment
 3042: 
 3043: sub userenvironment {
 3044:     my ($udom,$unam,@what)=@_;
 3045:     my $items;
 3046:     foreach my $item (@what) {
 3047:         $items.=&escape($item).'&';
 3048:     }
 3049:     $items=~s/\&$//;
 3050:     my %returnhash=();
 3051:     my $uhome = &homeserver($unam,$udom);
 3052:     unless ($uhome eq 'no_host') {
 3053:         my @answer=split(/\&/, 
 3054:             &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
 3055:         if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
 3056:             return %returnhash;
 3057:         }
 3058:         my $i;
 3059:         for ($i=0;$i<=$#what;$i++) {
 3060: 	    $returnhash{$what[$i]}=&unescape($answer[$i]);
 3061:         }
 3062:     }
 3063:     return %returnhash;
 3064: }
 3065: 
 3066: # ---------------------------------------------------------- Get a studentphoto
 3067: sub studentphoto {
 3068:     my ($udom,$unam,$ext) = @_;
 3069:     my $home=&Apache::lonnet::homeserver($unam,$udom);
 3070:     if (defined($env{'request.course.id'})) {
 3071:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
 3072:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
 3073:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
 3074:             } else {
 3075:                 my ($result,$perm_reqd)=
 3076: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
 3077:                 if ($result eq 'ok') {
 3078:                     if (!($perm_reqd eq 'yes')) {
 3079:                         return(&retrievestudentphoto($udom,$unam,$ext));
 3080:                     }
 3081:                 }
 3082:             }
 3083:         }
 3084:     } else {
 3085:         my ($result,$perm_reqd) = 
 3086: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
 3087:         if ($result eq 'ok') {
 3088:             if (!($perm_reqd eq 'yes')) {
 3089:                 return(&retrievestudentphoto($udom,$unam,$ext));
 3090:             }
 3091:         }
 3092:     }
 3093:     return '/adm/lonKaputt/lonlogo_broken.gif';
 3094: }
 3095: 
 3096: sub retrievestudentphoto {
 3097:     my ($udom,$unam,$ext,$type) = @_;
 3098:     my $home=&Apache::lonnet::homeserver($unam,$udom);
 3099:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
 3100:     if ($ret eq 'ok') {
 3101:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
 3102:         if ($type eq 'thumbnail') {
 3103:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
 3104:         }
 3105:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
 3106:         return $tokenurl;
 3107:     } else {
 3108:         if ($type eq 'thumbnail') {
 3109:             return '/adm/lonKaputt/genericstudent_tn.gif';
 3110:         } else { 
 3111:             return '/adm/lonKaputt/lonlogo_broken.gif';
 3112:         }
 3113:     }
 3114: }
 3115: 
 3116: # -------------------------------------------------------------------- New chat
 3117: 
 3118: sub chatsend {
 3119:     my ($newentry,$anon,$group)=@_;
 3120:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
 3121:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 3122:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
 3123:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
 3124: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
 3125: 		   &escape($newentry)).':'.$group,$chome);
 3126: }
 3127: 
 3128: # ------------------------------------------ Find current version of a resource
 3129: 
 3130: sub getversion {
 3131:     my $fname=&clutter(shift);
 3132:     unless ($fname=~m{^(/adm/wrapper|)/res/}) { return -1; }
 3133:     return &currentversion(&filelocation('',$fname));
 3134: }
 3135: 
 3136: sub currentversion {
 3137:     my $fname=shift;
 3138:     my $author=$fname;
 3139:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 3140:     my ($udom,$uname)=split(/\//,$author);
 3141:     my $home=&homeserver($uname,$udom);
 3142:     if ($home eq 'no_host') { 
 3143:         return -1; 
 3144:     }
 3145:     my $answer=&reply("currentversion:$fname",$home);
 3146:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
 3147: 	return -1;
 3148:     }
 3149:     return $answer;
 3150: }
 3151: 
 3152: #
 3153: # Return special version number of resource if set by override, empty otherwise
 3154: #
 3155: sub usedversion {
 3156:     my $fname=shift;
 3157:     unless ($fname) { $fname=$env{'request.uri'}; }
 3158:     my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
 3159:     if ($urlversion) { return $urlversion; }
 3160:     return '';
 3161: }
 3162: 
 3163: # ----------------------------- Subscribe to a resource, return URL if possible
 3164: 
 3165: sub subscribe {
 3166:     my $fname=shift;
 3167:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
 3168:     $fname=~s/[\n\r]//g;
 3169:     my $author=$fname;
 3170:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 3171:     my ($udom,$uname)=split(/\//,$author);
 3172:     my $home=homeserver($uname,$udom);
 3173:     if ($home eq 'no_host') {
 3174:         return 'not_found';
 3175:     }
 3176:     my $answer=reply("sub:$fname",$home);
 3177:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
 3178: 	$answer.=' by '.$home;
 3179:     }
 3180:     return $answer;
 3181: }
 3182:     
 3183: # -------------------------------------------------------------- Replicate file
 3184: 
 3185: sub repcopy {
 3186:     my $filename=shift;
 3187:     $filename=~s/\/+/\//g;
 3188:     my $londocroot = $perlvar{'lonDocRoot'};
 3189:     if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
 3190:     if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
 3191:     if ($filename=~m{^\Q$londocroot/userfiles/\E} or
 3192: 	$filename=~m{^/*(uploaded|editupload)/}) {
 3193: 	return &repcopy_userfile($filename);
 3194:     }
 3195:     $filename=~s/[\n\r]//g;
 3196:     my $transname="$filename.in.transfer";
 3197: # FIXME: this should flock
 3198:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
 3199:     my $remoteurl=subscribe($filename);
 3200:     if ($remoteurl =~ /^con_lost by/) {
 3201: 	   &logthis("Subscribe returned $remoteurl: $filename");
 3202:            return 'unavailable';
 3203:     } elsif ($remoteurl eq 'not_found') {
 3204: 	   #&logthis("Subscribe returned not_found: $filename");
 3205: 	   return 'not_found';
 3206:     } elsif ($remoteurl =~ /^rejected by/) {
 3207: 	   &logthis("Subscribe returned $remoteurl: $filename");
 3208:            return 'forbidden';
 3209:     } elsif ($remoteurl eq 'directory') {
 3210:            return 'ok';
 3211:     } else {
 3212:         my $author=$filename;
 3213:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 3214:         my ($udom,$uname)=split(/\//,$author);
 3215:         my $home=homeserver($uname,$udom);
 3216:         unless ($home eq $perlvar{'lonHostID'}) {
 3217:            my @parts=split(/\//,$filename);
 3218:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
 3219:            if ($path ne "$londocroot/res") {
 3220:                &logthis("Malconfiguration for replication: $filename");
 3221: 	       return 'bad_request';
 3222:            }
 3223:            my $count;
 3224:            for ($count=5;$count<$#parts;$count++) {
 3225:                $path.="/$parts[$count]";
 3226:                if ((-e $path)!=1) {
 3227: 		   mkdir($path,0777);
 3228:                }
 3229:            }
 3230:            my $request=new HTTP::Request('GET',"$remoteurl");
 3231:            my $response;
 3232:            if ($remoteurl =~ m{/raw/}) {
 3233:                $response=&LONCAPA::LWPReq::makerequest($home,$request,$transname,\%perlvar,'',0,1);
 3234:            } else {
 3235:                $response=&LONCAPA::LWPReq::makerequest($home,$request,$transname,\%perlvar,'',1);
 3236:            }
 3237:            if ($response->is_error()) {
 3238: 	       unlink($transname);
 3239:                my $message=$response->status_line;
 3240:                &logthis("<font color=\"blue\">WARNING:"
 3241:                        ." LWP get: $message: $filename</font>");
 3242:                return 'unavailable';
 3243:            } else {
 3244: 	       if ($remoteurl!~/\.meta$/) {
 3245:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
 3246:                   my $mresponse;
 3247:                   if ($remoteurl =~ m{/raw/}) {
 3248:                       $mresponse = &LONCAPA::LWPReq::makerequest($home,$mrequest,$filename.'.meta',\%perlvar,'',0,1);
 3249:                   } else {
 3250:                       $mresponse = &LONCAPA::LWPReq::makerequest($home,$mrequest,$filename.'.meta',\%perlvar,'',1);
 3251:                   }
 3252:                   if ($mresponse->is_error()) {
 3253: 		      unlink($filename.'.meta');
 3254:                       &logthis(
 3255:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
 3256:                   }
 3257: 	       }
 3258:                rename($transname,$filename);
 3259:                return 'ok';
 3260:            }
 3261:        }
 3262:     }
 3263: }
 3264: 
 3265: # ------------------------------------------------ Get server side include body
 3266: sub ssi_body {
 3267:     my ($filelink,%form)=@_;
 3268:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
 3269:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
 3270:     }
 3271:     my $output='';
 3272:     my $response;
 3273:     if ($filelink=~/^https?\:/) {
 3274:        ($output,$response)=&externalssi($filelink);
 3275:     } else {
 3276:        $filelink .= $filelink=~/\?/ ? '&' : '?';
 3277:        $filelink .= 'inhibitmenu=yes';
 3278:        ($output,$response)=&ssi($filelink,%form);
 3279:     }
 3280:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
 3281:     $output=~s/^.*?\<body[^\>]*\>//si;
 3282:     $output=~s/\<\/body\s*\>.*?$//si;
 3283:     if (wantarray) {
 3284:         return ($output, $response);
 3285:     } else {
 3286:         return $output;
 3287:     }
 3288: }
 3289: 
 3290: # --------------------------------------------------------- Server Side Include
 3291: 
 3292: sub absolute_url {
 3293:     my ($host_name) = @_;
 3294:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
 3295:     if ($host_name eq '') {
 3296: 	$host_name = $ENV{'SERVER_NAME'};
 3297:     }
 3298:     return $protocol.$host_name;
 3299: }
 3300: 
 3301: #
 3302: #   Server side include.
 3303: # Parameters:
 3304: #  fn     Possibly encrypted resource name/id.
 3305: #  form   Hash that describes how the rendering should be done
 3306: #         and other things.
 3307: # Returns:
 3308: #   Scalar context: The content of the response.
 3309: #   Array context:  2 element list of the content and the full response object.
 3310: #     
 3311: sub ssi {
 3312: 
 3313:     my ($fn,%form)=@_;
 3314:     my $request;
 3315: 
 3316:     $form{'no_update_last_known'}=1;
 3317:     &Apache::lonenc::check_encrypt(\$fn);
 3318:     if (%form) {
 3319:       $request=new HTTP::Request('POST',&absolute_url().$fn);
 3320:       $request->content(join('&',map { 
 3321:             my $name = escape($_);
 3322:             "$name=" . ( ref($form{$_}) eq 'ARRAY' 
 3323:             ? join("&$name=", map {escape($_) } @{$form{$_}}) 
 3324:             : &escape($form{$_}) );    
 3325:         } keys(%form)));
 3326:     } else {
 3327:       $request=new HTTP::Request('GET',&absolute_url().$fn);
 3328:     }
 3329: 
 3330:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
 3331:     my $lonhost = $perlvar{'lonHostID'};
 3332:     my $islocal;
 3333:     if (($env{'request.course.id'}) &&
 3334:         ($form{'grade_courseid'} eq $env{'request.course.id'}) &&
 3335:         ($form{'grade_username'} ne '') && ($form{'grade_domain'} ne '') &&
 3336:         ($form{'grade_symb'} ne '') &&
 3337:         (&Apache::lonnet::allowed('mgr',$env{'request.course.id'}.
 3338:                                  ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:'')))) {
 3339:         $islocal = 1;
 3340:     }
 3341:     my $response= &LONCAPA::LWPReq::makerequest($lonhost,$request,'',\%perlvar,
 3342:                                                 '','','',$islocal);
 3343: 
 3344:     if (wantarray) {
 3345: 	return ($response->content, $response);
 3346:     } else {
 3347: 	return $response->content;
 3348:     }
 3349: }
 3350: 
 3351: sub externalssi {
 3352:     my ($url)=@_;
 3353:     my $request=new HTTP::Request('GET',$url);
 3354:     my $response = &LONCAPA::LWPReq::makerequest('',$request,'',\%perlvar);
 3355:     if (wantarray) {
 3356:         return ($response->content, $response);
 3357:     } else {
 3358:         return $response->content;
 3359:     }
 3360: }
 3361: 
 3362: 
 3363: # If the local copy of a replicated resource is outdated, trigger a  
 3364: # connection from the homeserver to flush the delayed queue. If no update 
 3365: # happens, remove local copies of outdated resource (and corresponding
 3366: # metadata file).
 3367: 
 3368: sub remove_stale_resfile {
 3369:     my ($url) = @_;
 3370:     my $removed;
 3371:     if ($url=~m{^/res/($match_domain)/($match_username)/}) {
 3372:         my $audom = $1;
 3373:         my $auname = $2;
 3374:         unless (($url =~ /\.\d+\.\w+$/) || ($url =~ m{^/res/lib/templates/})) {
 3375:             my $homeserver = &homeserver($auname,$audom);
 3376:             unless (($homeserver eq 'no_host') ||
 3377:                     (grep { $_ eq $homeserver } &current_machine_ids())) {
 3378:                 my $fname = &filelocation('',$url);
 3379:                 if (-e $fname) {
 3380:                     my $hostname = &hostname($homeserver);
 3381:                     if ($hostname) {
 3382:                         my $protocol = $protocol{$homeserver};
 3383:                         $protocol = 'http' if ($protocol ne 'https');
 3384:                         my $uri = &declutter($url);
 3385:                         my $request=new HTTP::Request('HEAD',$protocol.'://'.$hostname.'/raw/'.$uri);
 3386:                         my $response = &LONCAPA::LWPReq::makerequest($homeserver,$request,'',\%perlvar,5,0,1);
 3387:                         if ($response->is_success()) {
 3388:                             my $remmodtime = &HTTP::Date::str2time( $response->header('Last-modified') );
 3389:                             my $locmodtime = (stat($fname))[9];
 3390:                             if ($locmodtime < $remmodtime) {
 3391:                                 my $stale;
 3392:                                 my $answer = &reply('pong',$homeserver);
 3393:                                 if ($answer eq $homeserver.':'.$perlvar{'lonHostID'}) {
 3394:                                     sleep(0.2);
 3395:                                     $locmodtime = (stat($fname))[9];
 3396:                                     if ($locmodtime < $remmodtime) {
 3397:                                         my $posstransfer = $fname.'.in.transfer';
 3398:                                         if ((-e $posstransfer) && ($remmodtime < (stat($posstransfer))[9])) {
 3399:                                             $removed = 1;
 3400:                                         } else {
 3401:                                             $stale = 1;
 3402:                                         }
 3403:                                     } else {
 3404:                                         $removed = 1;
 3405:                                     }
 3406:                                 } else {
 3407:                                     $stale = 1;
 3408:                                 }
 3409:                                 if ($stale) {
 3410:                                     unlink($fname);
 3411:                                     if ($uri!~/\.meta$/) {
 3412:                                         unlink($fname.'.meta');
 3413:                                     }
 3414:                                     &reply("unsub:$fname",$homeserver);
 3415:                                     $removed = 1;
 3416:                                 }
 3417:                             }
 3418:                         }
 3419:                     }
 3420:                 }
 3421:             }
 3422:         }
 3423:     }
 3424:     return $removed;
 3425: }
 3426: 
 3427: # -------------------------------- Allow a /uploaded/ URI to be vouched for
 3428: 
 3429: sub allowuploaded {
 3430:     my ($srcurl,$url)=@_;
 3431:     $url=&clutter(&declutter($url));
 3432:     my $dir=$url;
 3433:     $dir=~s/\/[^\/]+$//;
 3434:     my %httpref=();
 3435:     my $httpurl=&hreflocation('',$url);
 3436:     $httpref{'httpref.'.$httpurl}=$srcurl;
 3437:     &Apache::lonnet::appenv(\%httpref);
 3438: }
 3439: 
 3440: #
 3441: # Determine if the current user should be able to edit a particular resource,
 3442: # when viewing in course context.
 3443: # (a) When viewing resource used to determine if "Edit" item is included in 
 3444: #     Functions.
 3445: # (b) When displaying folder contents in course editor, used to determine if
 3446: #     "Edit" link will be displayed alongside resource.
 3447: #
 3448: #  input: six args -- filename (decluttered), course number, course domain,
 3449: #                   url, symb (if registered) and group (if this is a group
 3450: #                   item -- e.g., bulletin board, group page etc.).
 3451: #  output: array of five scalars -- 
 3452: #          $cfile -- url for file editing if editable on current server
 3453: #          $home -- homeserver of resource (i.e., for author if published,
 3454: #                                           or course if uploaded.).
 3455: #          $switchserver --  1 if server switch will be needed.
 3456: #          $forceedit -- 1 if icon/link should be to go to edit mode 
 3457: #          $forceview -- 1 if icon/link should be to go to view mode
 3458: #
 3459: 
 3460: sub can_edit_resource {
 3461:     my ($file,$cnum,$cdom,$resurl,$symb,$group) = @_;
 3462:     my ($cfile,$home,$switchserver,$forceedit,$forceview,$uploaded,$incourse);
 3463: #
 3464: # For aboutme pages user can only edit his/her own.
 3465: #
 3466:     if ($resurl =~ m{^/?adm/($match_domain)/($match_username)/aboutme$}) {
 3467:         my ($sdom,$sname) = ($1,$2);
 3468:         if (($sdom eq $env{'user.domain'}) && ($sname eq $env{'user.name'})) {
 3469:             $home = $env{'user.home'};
 3470:             $cfile = $resurl;
 3471:             if ($env{'form.forceedit'}) {
 3472:                 $forceview = 1;
 3473:             } else {
 3474:                 $forceedit = 1;
 3475:             }
 3476:             return ($cfile,$home,$switchserver,$forceedit,$forceview);
 3477:         } else {
 3478:             return;
 3479:         }
 3480:     }
 3481: 
 3482:     if ($env{'request.course.id'}) {
 3483:         my $crsedit = &Apache::lonnet::allowed('mdc',$env{'request.course.id'});
 3484:         if ($group ne '') {
 3485: # if this is a group homepage or group bulletin board, check group privs
 3486:             my $allowed = 0;
 3487:             if ($resurl =~ m{^/?adm/$cdom/$cnum/$group/smppg$}) {
 3488:                 if ((&allowed('mdg',$env{'request.course.id'}.
 3489:                               ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
 3490:                         (&allowed('mgh',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
 3491:                     $allowed = 1;
 3492:                 }
 3493:             } elsif ($resurl =~ m{^/?adm/$cdom/$cnum/\d+/bulletinboard$}) {
 3494:                 if ((&allowed('mdg',$env{'request.course.id'}.($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
 3495:                         (&allowed('cgb',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
 3496:                     $allowed = 1;
 3497:                 }
 3498:             }
 3499:             if ($allowed) {
 3500:                 $home=&homeserver($cnum,$cdom);
 3501:                 if ($env{'form.forceedit'}) {
 3502:                     $forceview = 1;
 3503:                 } else {
 3504:                     $forceedit = 1;
 3505:                 }
 3506:                 $cfile = $resurl;
 3507:             } else {
 3508:                 return;
 3509:             }
 3510:         } else {
 3511:             if ($resurl =~ m{^/?adm/viewclasslist$}) {
 3512:                 unless (&Apache::lonnet::allowed('opa',$env{'request.course.id'})) {
 3513:                     return;
 3514:                 }
 3515:             } elsif (!$crsedit) {
 3516: #
 3517: # No edit allowed where CC has switched to student role.
 3518: #
 3519:                 return;
 3520:             }
 3521:         }
 3522:     }
 3523: 
 3524:     if ($file ne '') {
 3525:         if (($cnum =~ /$match_courseid/) && ($cdom =~ /$match_domain/)) {
 3526:             if (&is_course_upload($file,$cnum,$cdom)) {
 3527:                 $uploaded = 1;
 3528:                 $incourse = 1;
 3529:                 if ($file =~/\.(htm|html|css|js|txt)$/) {
 3530:                     $cfile = &hreflocation('',$file);
 3531:                     if ($env{'form.forceedit'}) {
 3532:                         $forceview = 1;
 3533:                     } else {
 3534:                         $forceedit = 1;
 3535:                     }
 3536:                 }
 3537:             } elsif ($resurl =~ m{^/public/$cdom/$cnum/syllabus}) {
 3538:                 $incourse = 1;
 3539:                 if ($env{'form.forceedit'}) {
 3540:                     $forceview = 1;
 3541:                 } else {
 3542:                     $forceedit = 1;
 3543:                 }
 3544:                 $cfile = $resurl;
 3545:             } elsif (($resurl ne '') && (&is_on_map($resurl))) { 
 3546:                 if ($resurl =~ m{^/adm/$match_domain/$match_username/\d+/smppg|bulletinboard$}) {
 3547:                     $incourse = 1;
 3548:                     if ($env{'form.forceedit'}) {
 3549:                         $forceview = 1;
 3550:                     } else {
 3551:                         $forceedit = 1;
 3552:                     }
 3553:                     $cfile = $resurl;
 3554:                 } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem') {
 3555:                     $incourse = 1;
 3556:                     $cfile = $resurl.'/smpedit';
 3557:                 } elsif ($resurl =~ m{^/adm/wrapper/ext/}) {
 3558:                     $incourse = 1;
 3559:                     if ($env{'form.forceedit'}) {
 3560:                         $forceview = 1;
 3561:                     } else {
 3562:                         $forceedit = 1;
 3563:                     }
 3564:                     $cfile = $resurl;
 3565:                 } elsif ($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/ext\.tool$}) {
 3566:                     $incourse = 1;
 3567:                     if ($env{'form.forceedit'}) {
 3568:                         $forceview = 1;
 3569:                     } else {
 3570:                         $forceedit = 1;
 3571:                     }
 3572:                     $cfile = $resurl;
 3573:                 } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
 3574:                     $incourse = 1;
 3575:                     if ($env{'form.forceedit'}) {
 3576:                         $forceview = 1;
 3577:                     } else {
 3578:                         $forceedit = 1;
 3579:                     }
 3580:                     $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
 3581:                 }
 3582:             } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem/smpedit') {
 3583:                 my $template = '/res/lib/templates/simpleproblem.problem';
 3584:                 if (&is_on_map($template)) { 
 3585:                     $incourse = 1;
 3586:                     $forceview = 1;
 3587:                     $cfile = $template;
 3588:                 }
 3589:             } elsif (($resurl =~ m{^/adm/wrapper/ext/}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
 3590:                     $incourse = 1;
 3591:                     if ($env{'form.forceedit'}) {
 3592:                         $forceview = 1;
 3593:                     } else {
 3594:                         $forceedit = 1;
 3595:                     }
 3596:                     $cfile = $resurl;
 3597:             } elsif (($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/ext\.tool$}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
 3598:                 $incourse = 1;
 3599:                 if ($env{'form.forceedit'}) {
 3600:                     $forceview = 1;
 3601:                 } else {
 3602:                     $forceedit = 1;
 3603:                 }
 3604:                 $cfile = $resurl;
 3605:             } elsif (($resurl eq '/adm/extresedit') && ($symb || $env{'form.folderpath'})) {
 3606:                 $incourse = 1;
 3607:                 $forceview = 1;
 3608:                 if ($symb) {
 3609:                     my ($map,$id,$res)=&decode_symb($symb);
 3610:                     $env{'request.symb'} = $symb;
 3611:                     $cfile = &clutter($res);
 3612:                 } else {
 3613:                     $cfile = $env{'form.suppurl'};
 3614:                     my $escfile = &unescape($cfile);
 3615:                     if ($escfile =~ m{^/adm/$cdom/$cnum/\d+/ext\.tool$}) {
 3616:                         $cfile = '/adm/wrapper'.$escfile;
 3617:                     } else {
 3618:                         $escfile =~ s{^http://}{};
 3619:                         $cfile = &escape("/adm/wrapper/ext/$escfile");
 3620:                     }
 3621:                 }
 3622:             } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
 3623:                 if ($env{'form.forceedit'}) {
 3624:                     $forceview = 1;
 3625:                 } else {
 3626:                     $forceedit = 1;
 3627:                 }
 3628:                 $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
 3629:             }
 3630:         }
 3631:         if ($uploaded || $incourse) {
 3632:             $home=&homeserver($cnum,$cdom);
 3633:         } elsif ($file !~ m{/$}) {
 3634:             $file=~s{^(priv/$match_domain/$match_username)}{/$1};
 3635:             $file=~s{^($match_domain/$match_username)}{/priv/$1};
 3636:             # Check that the user has permission to edit this resource
 3637:             my $setpriv = 1;
 3638:             my ($cfuname,$cfudom)=&constructaccess($file,$setpriv);
 3639:             if (defined($cfudom)) {
 3640:                 $home=&homeserver($cfuname,$cfudom);
 3641:                 $cfile=$file;
 3642:             }
 3643:         }
 3644:         if (($cfile ne '') && (!$incourse || $uploaded) && 
 3645:             (($home ne '') && ($home ne 'no_host'))) {
 3646:             my @ids=&current_machine_ids();
 3647:             unless (grep(/^\Q$home\E$/,@ids)) {
 3648:                 $switchserver=1;
 3649:             }
 3650:         }
 3651:     }
 3652:     return ($cfile,$home,$switchserver,$forceedit,$forceview);
 3653: }
 3654: 
 3655: sub is_course_upload {
 3656:     my ($file,$cnum,$cdom) = @_;
 3657:     my $uploadpath = &LONCAPA::propath($cdom,$cnum);
 3658:     $uploadpath =~ s{^\/}{};
 3659:     if (($file =~ m{^\Q$uploadpath\E/userfiles/(docs|supplemental)/}) ||
 3660:         ($file =~ m{^userfiles/\Q$cdom\E/\Q$cnum\E/(docs|supplemental)/})) {
 3661:         return 1;
 3662:     }
 3663:     return;
 3664: }
 3665: 
 3666: sub in_course {
 3667:     my ($udom,$uname,$cdom,$cnum,$type,$hideprivileged) = @_;
 3668:     if ($hideprivileged) {
 3669:         my $skipuser;
 3670:         my %coursehash = &coursedescription($cdom.'_'.$cnum);
 3671:         my @possdoms = ($cdom);  
 3672:         if ($coursehash{'checkforpriv'}) { 
 3673:             push(@possdoms,split(/,/,$coursehash{'checkforpriv'})); 
 3674:         }
 3675:         if (&privileged($uname,$udom,\@possdoms)) {
 3676:             $skipuser = 1;
 3677:             if ($coursehash{'nothideprivileged'}) {
 3678:                 foreach my $item (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 3679:                     my $user;
 3680:                     if ($item =~ /:/) {
 3681:                         $user = $item;
 3682:                     } else {
 3683:                         $user = join(':',split(/[\@]/,$item));
 3684:                     }
 3685:                     if ($user eq $uname.':'.$udom) {
 3686:                         undef($skipuser);
 3687:                         last;
 3688:                     }
 3689:                 }
 3690:             }
 3691:             if ($skipuser) {
 3692:                 return 0;
 3693:             }
 3694:         }
 3695:     }
 3696:     $type ||= 'any';
 3697:     if (!defined($cdom) || !defined($cnum)) {
 3698:         my $cid  = $env{'request.course.id'};
 3699:         $cdom = $env{'course.'.$cid.'.domain'};
 3700:         $cnum = $env{'course.'.$cid.'.num'};
 3701:     }
 3702:     my $typesref;
 3703:     if (($type eq 'any') || ($type eq 'all')) {
 3704:         $typesref = ['active','previous','future'];
 3705:     } elsif ($type eq 'previous' || $type eq 'future') {
 3706:         $typesref = [$type];
 3707:     }
 3708:     my %roles = &get_my_roles($uname,$udom,'userroles',
 3709:                               $typesref,undef,[$cdom]);
 3710:     my ($tmp) = keys(%roles);
 3711:     return 0 if ($tmp =~ /^(con_lost|error|no_such_host)/i);
 3712:     my @course_roles = grep(/^\Q$cnum\E:\Q$cdom\E:/, keys(%roles));
 3713:     if (@course_roles > 0) {
 3714:         return 1;
 3715:     }
 3716:     return 0;
 3717: }
 3718: 
 3719: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
 3720: # input: action, courseID, current domain, intended
 3721: #        path to file, source of file, instruction to parse file for objects,
 3722: #        ref to hash for embedded objects,
 3723: #        ref to hash for codebase of java objects.
 3724: #        reference to scalar to accommodate mime type determined
 3725: #          from File::MMagic if $parser = parse.
 3726: #
 3727: # output: url to file (if action was uploaddoc), 
 3728: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
 3729: #
 3730: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
 3731: # course.
 3732: #
 3733: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 3734: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
 3735: #          course's home server.
 3736: #
 3737: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
 3738: #          be copied from $source (current location) to 
 3739: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 3740: #         and will then be copied to
 3741: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
 3742: #         course's home server.
 3743: #
 3744: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 3745: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
 3746: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 3747: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
 3748: #         in course's home server.
 3749: #
 3750: 
 3751: sub process_coursefile {
 3752:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
 3753:         $mimetype)=@_;
 3754:     my $fetchresult;
 3755:     my $home=&homeserver($docuname,$docudom);
 3756:     if ($action eq 'propagate') {
 3757:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 3758: 			     $home);
 3759:     } else {
 3760:         my $fpath = '';
 3761:         my $fname = $file;
 3762:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 3763:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 3764:         my $filepath = &build_filepath($fpath);
 3765:         if ($action eq 'copy') {
 3766:             if ($source eq '') {
 3767:                 $fetchresult = 'no source file';
 3768:                 return $fetchresult;
 3769:             } else {
 3770:                 my $destination = $filepath.'/'.$fname;
 3771:                 rename($source,$destination);
 3772:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 3773:                                  $home);
 3774:             }
 3775:         } elsif ($action eq 'uploaddoc') {
 3776:             open(my $fh,'>',$filepath.'/'.$fname);
 3777:             print $fh $env{'form.'.$source};
 3778:             close($fh);
 3779:             if ($parser eq 'parse') {
 3780:                 my $mm = new File::MMagic;
 3781:                 my $type = $mm->checktype_filename($filepath.'/'.$fname);
 3782:                 if ($type eq 'text/html') {
 3783:                     my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
 3784:                     unless ($parse_result eq 'ok') {
 3785:                         &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
 3786:                     }
 3787:                 }
 3788:                 if (ref($mimetype)) {
 3789:                     $$mimetype = $type;
 3790:                 } 
 3791:             }
 3792:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 3793:                                  $home);
 3794:             if ($fetchresult eq 'ok') {
 3795:                 return '/uploaded/'.$fpath.'/'.$fname;
 3796:             } else {
 3797:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 3798:                         ' to host '.$home.': '.$fetchresult);
 3799:                 return '/adm/notfound.html';
 3800:             }
 3801:         }
 3802:     }
 3803:     unless ( $fetchresult eq 'ok') {
 3804:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 3805:              ' to host '.$home.': '.$fetchresult);
 3806:     }
 3807:     return $fetchresult;
 3808: }
 3809: 
 3810: sub build_filepath {
 3811:     my ($fpath) = @_;
 3812:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
 3813:     unless ($fpath eq '') {
 3814:         my @parts=split('/',$fpath);
 3815:         foreach my $part (@parts) {
 3816:             $filepath.= '/'.$part;
 3817:             if ((-e $filepath)!=1) {
 3818:                 mkdir($filepath,0777);
 3819:             }
 3820:         }
 3821:     }
 3822:     return $filepath;
 3823: }
 3824: 
 3825: sub store_edited_file {
 3826:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
 3827:     my $file = $primary_url;
 3828:     $file =~ s#^/uploaded/$docudom/$docuname/##;
 3829:     my $fpath = '';
 3830:     my $fname = $file;
 3831:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 3832:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 3833:     my $filepath = &build_filepath($fpath);
 3834:     open(my $fh,'>',$filepath.'/'.$fname);
 3835:     print $fh $content;
 3836:     close($fh);
 3837:     my $home=&homeserver($docuname,$docudom);
 3838:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 3839: 			  $home);
 3840:     if ($$fetchresult eq 'ok') {
 3841:         return '/uploaded/'.$fpath.'/'.$fname;
 3842:     } else {
 3843:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 3844: 		 ' to host '.$home.': '.$$fetchresult);
 3845:         return '/adm/notfound.html';
 3846:     }
 3847: }
 3848: 
 3849: sub clean_filename {
 3850:     my ($fname,$args)=@_;
 3851: # Replace Windows backslashes by forward slashes
 3852:     $fname=~s/\\/\//g;
 3853:     if (!$args->{'keep_path'}) {
 3854:         # Get rid of everything but the actual filename
 3855: 	$fname=~s/^.*\/([^\/]+)$/$1/;
 3856:     }
 3857: # Replace spaces by underscores
 3858:     $fname=~s/\s+/\_/g;
 3859: # Replace all other weird characters by nothing
 3860:     $fname=~s{[^/\w\.\-]}{}g;
 3861: # Replace all .\d. sequences with _\d. so they no longer look like version
 3862: # numbers
 3863:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
 3864:     return $fname;
 3865: }
 3866: # This Function checks if an Image's dimensions exceed either $resizewidth (width) 
 3867: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an 
 3868: # image with the same aspect ratio as the original, but with dimensions which do 
 3869: # not exceed $resizewidth and $resizeheight.
 3870:  
 3871: sub resizeImage {
 3872:     my ($img_path,$resizewidth,$resizeheight) = @_;
 3873:     my $ima = Image::Magick->new;
 3874:     my $resized;
 3875:     if (-e $img_path) {
 3876:         $ima->Read($img_path);
 3877:         if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
 3878:             my $width = $ima->Get('width');
 3879:             my $height = $ima->Get('height');
 3880:             if ($width > $resizewidth) {
 3881: 	        my $factor = $width/$resizewidth;
 3882:                 my $newheight = $height/$factor;
 3883:                 $ima->Scale(width=>$resizewidth,height=>$newheight);
 3884:                 $resized = 1;
 3885:             }
 3886:         }
 3887:         if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
 3888:             my $width = $ima->Get('width');
 3889:             my $height = $ima->Get('height');
 3890:             if ($height > $resizeheight) {
 3891:                 my $factor = $height/$resizeheight;
 3892:                 my $newwidth = $width/$factor;
 3893:                 $ima->Scale(width=>$newwidth,height=>$resizeheight);
 3894:                 $resized = 1;
 3895:             }
 3896:         }
 3897:         if ($resized) {
 3898:             $ima->Write($img_path);
 3899:         }
 3900:     }
 3901:     return;
 3902: }
 3903: 
 3904: # --------------- Take an uploaded file and put it into the userfiles directory
 3905: # input: $formname - the contents of the file are in $env{"form.$formname"}
 3906: #                    the desired filename is in $env{"form.$formname.filename"}
 3907: #        $context - possible values: coursedoc, existingfile, overwrite, 
 3908: #                                    canceloverwrite, scantron or ''.
 3909: #                   if 'coursedoc': upload to the current course
 3910: #                   if 'existingfile': write file to tmp/overwrites directory 
 3911: #                   if 'canceloverwrite': delete file written to tmp/overwrites directory
 3912: #                   $context is passed as argument to &finishuserfileupload
 3913: #        $subdir - directory in userfile to store the file into
 3914: #        $parser - instruction to parse file for objects ($parser = parse) or
 3915: #                  if context is 'scantron', $parser is hashref of csv column mapping
 3916: #                  (e.g.,{ PaperID => 0, LastName => 1, FirstName => 2, ID => 3, 
 3917: #                          Section => 4, CODE => 5, FirstQuestion => 9 }).
 3918: #        $allfiles - reference to hash for embedded objects
 3919: #        $codebase - reference to hash for codebase of java objects
 3920: #        $desuname - username for permanent storage of uploaded file
 3921: #        $dsetudom - domain for permanaent storage of uploaded file
 3922: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
 3923: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
 3924: #        $resizewidth - width (pixels) to which to resize uploaded image
 3925: #        $resizeheight - height (pixels) to which to resize uploaded image
 3926: #        $mimetype - reference to scalar to accommodate mime type determined
 3927: #                    from File::MMagic.
 3928: # 
 3929: # output: url of file in userspace, or error: <message> 
 3930: #             or /adm/notfound.html if failure to upload occurse
 3931: 
 3932: sub userfileupload {
 3933:     my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
 3934:         $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
 3935:     if (!defined($subdir)) { $subdir='unknown'; }
 3936:     my $fname=$env{'form.'.$formname.'.filename'};
 3937:     $fname=&clean_filename($fname);
 3938:     # See if there is anything left
 3939:     unless ($fname) { return 'error: no uploaded file'; }
 3940:     # Files uploaded to help request form, or uploaded to "create course" page are handled differently
 3941:     if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
 3942:         (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
 3943:          ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
 3944:         my $now = time;
 3945:         my $filepath;
 3946:         if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
 3947:              $filepath = 'tmp/helprequests/'.$now;
 3948:         } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
 3949:              $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
 3950:                          '_'.$env{'user.domain'}.'/pending';
 3951:         } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
 3952:             my ($docuname,$docudom);
 3953:             if ($destudom =~ /^$match_domain$/) {
 3954:                 $docudom = $destudom;
 3955:             } else {
 3956:                 $docudom = $env{'user.domain'};
 3957:             }
 3958:             if ($destuname =~ /^$match_username$/) {
 3959:                 $docuname = $destuname;
 3960:             } else {
 3961:                 $docuname = $env{'user.name'};
 3962:             }
 3963:             if (exists($env{'form.group'})) {
 3964:                 $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 3965:                 $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 3966:             }
 3967:             $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
 3968:             if ($context eq 'canceloverwrite') {
 3969:                 my $tempfile =  $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
 3970:                 if (-e  $tempfile) {
 3971:                     my @info = stat($tempfile);
 3972:                     if ($info[9] eq $env{'form.timestamp'}) {
 3973:                         unlink($tempfile);
 3974:                     }
 3975:                 }
 3976:                 return;
 3977:             }
 3978:         }
 3979:         # Create the directory if not present
 3980:         my @parts=split(/\//,$filepath);
 3981:         my $fullpath = $perlvar{'lonDaemons'};
 3982:         for (my $i=0;$i<@parts;$i++) {
 3983:             $fullpath .= '/'.$parts[$i];
 3984:             if ((-e $fullpath)!=1) {
 3985:                 mkdir($fullpath,0777);
 3986:             }
 3987:         }
 3988:         open(my $fh,'>',$fullpath.'/'.$fname);
 3989:         print $fh $env{'form.'.$formname};
 3990:         close($fh);
 3991:         if ($context eq 'existingfile') {
 3992:             my @info = stat($fullpath.'/'.$fname);
 3993:             return ($fullpath.'/'.$fname,$info[9]);
 3994:         } else {
 3995:             return $fullpath.'/'.$fname;
 3996:         }
 3997:     }
 3998:     if ($subdir eq 'scantron') {
 3999:         $fname = 'scantron_orig_'.$fname;
 4000:     } else {
 4001:         $fname="$subdir/$fname";
 4002:     }
 4003:     if ($context eq 'coursedoc') {
 4004: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 4005: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 4006:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
 4007:             return &finishuserfileupload($docuname,$docudom,
 4008: 					 $formname,$fname,$parser,$allfiles,
 4009: 					 $codebase,$thumbwidth,$thumbheight,
 4010:                                          $resizewidth,$resizeheight,$context,$mimetype);
 4011:         } else {
 4012:             if ($env{'form.folder'}) {
 4013:                 $fname=$env{'form.folder'}.'/'.$fname;
 4014:             }
 4015:             return &process_coursefile('uploaddoc',$docuname,$docudom,
 4016: 				       $fname,$formname,$parser,
 4017: 				       $allfiles,$codebase,$mimetype);
 4018:         }
 4019:     } elsif (defined($destuname)) {
 4020:         my $docuname=$destuname;
 4021:         my $docudom=$destudom;
 4022: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
 4023: 				     $parser,$allfiles,$codebase,
 4024:                                      $thumbwidth,$thumbheight,
 4025:                                      $resizewidth,$resizeheight,$context,$mimetype);
 4026:     } else {
 4027:         my $docuname=$env{'user.name'};
 4028:         my $docudom=$env{'user.domain'};
 4029:         if ((exists($env{'form.group'})) || ($context eq 'syllabus')) {
 4030:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 4031:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 4032:         }
 4033: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
 4034: 				     $parser,$allfiles,$codebase,
 4035:                                      $thumbwidth,$thumbheight,
 4036:                                      $resizewidth,$resizeheight,$context,$mimetype);
 4037:     }
 4038: }
 4039: 
 4040: sub finishuserfileupload {
 4041:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
 4042:         $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
 4043:     my $path=$docudom.'/'.$docuname.'/';
 4044:     my $filepath=$perlvar{'lonDocRoot'};
 4045:   
 4046:     my ($fnamepath,$file,$fetchthumb);
 4047:     $file=$fname;
 4048:     if ($fname=~m|/|) {
 4049:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
 4050: 	$path.=$fnamepath.'/';
 4051:     }
 4052:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
 4053:     my $count;
 4054:     for ($count=4;$count<=$#parts;$count++) {
 4055:         $filepath.="/$parts[$count]";
 4056:         if ((-e $filepath)!=1) {
 4057: 	    mkdir($filepath,0777);
 4058:         }
 4059:     }
 4060: 
 4061: # Save the file
 4062:     {
 4063: 	if (!open(FH,'>',$filepath.'/'.$file)) {
 4064: 	    &logthis('Failed to create '.$filepath.'/'.$file);
 4065: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
 4066: 	    return '/adm/notfound.html';
 4067: 	}
 4068:         if ($context eq 'overwrite') {
 4069:             my $source =  LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
 4070:             my $target = $filepath.'/'.$file;
 4071:             if (-e $source) {
 4072:                 my @info = stat($source);
 4073:                 if ($info[9] eq $env{'form.timestamp'}) {   
 4074:                     unless (&File::Copy::move($source,$target)) {
 4075:                         &logthis('Failed to overwrite '.$filepath.'/'.$file);
 4076:                         return "Moving from $source failed";
 4077:                     }
 4078:                 } else {
 4079:                     return "Temporary file: $source had unexpected date/time for last modification";
 4080:                 }
 4081:             } else {
 4082:                 return "Temporary file: $source missing";
 4083:             }
 4084:         } elsif (!print FH ($env{'form.'.$formname})) {
 4085: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
 4086: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
 4087: 	    return '/adm/notfound.html';
 4088: 	}
 4089: 	close(FH);
 4090:         if ($resizewidth && $resizeheight) {
 4091:             my $mm = new File::MMagic;
 4092:             my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
 4093:             if ($mime_type =~ m{^image/}) {
 4094: 	        &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
 4095:             }  
 4096: 	}
 4097:     }
 4098:     if (($context eq 'coursedoc') || ($parser eq 'parse')) {
 4099:         if (ref($mimetype)) {
 4100:             if ($$mimetype eq '') {
 4101:                 my $mm = new File::MMagic;
 4102:                 my $type = $mm->checktype_filename($filepath.'/'.$file);
 4103:                 $$mimetype = $type;
 4104:             }
 4105:         }
 4106:     }
 4107:     if (($context ne 'scantron') && ($parser eq 'parse')) {
 4108:         if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
 4109:             my $parse_result = &extract_embedded_items($filepath.'/'.$file,
 4110:                                                        $allfiles,$codebase);
 4111:             unless ($parse_result eq 'ok') {
 4112:                 &logthis('Failed to parse '.$filepath.$file.
 4113: 	   	         ' for embedded media: '.$parse_result); 
 4114:             }
 4115:         }
 4116:     } elsif (($context eq 'scantron') && (ref($parser) eq 'HASH')) {
 4117:         my $format = $env{'form.scantron_format'};
 4118:         &bubblesheet_converter($docudom,$filepath.'/'.$file,$parser,$format);
 4119:     }
 4120:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
 4121:         my $input = $filepath.'/'.$file;
 4122:         my $output = $filepath.'/'.'tn-'.$file;
 4123:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
 4124:         my @args = ('convert','-sample',$thumbsize,$input,$output);
 4125:         system({$args[0]} @args);
 4126:         if (-e $filepath.'/'.'tn-'.$file) {
 4127:             $fetchthumb  = 1; 
 4128:         }
 4129:     }
 4130:  
 4131: # Notify homeserver to grep it
 4132: #
 4133:     my $docuhome=&homeserver($docuname,$docudom);	
 4134:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
 4135:     if ($fetchresult eq 'ok') {
 4136:         if ($fetchthumb) {
 4137:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
 4138:             if ($thumbresult ne 'ok') {
 4139:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
 4140:                          $docuhome.': '.$thumbresult);
 4141:             }
 4142:         }
 4143: #
 4144: # Return the URL to it
 4145:         return '/uploaded/'.$path.$file;
 4146:     } else {
 4147:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
 4148: 		 ': '.$fetchresult);
 4149:         return '/adm/notfound.html';
 4150:     }
 4151: }
 4152: 
 4153: sub extract_embedded_items {
 4154:     my ($fullpath,$allfiles,$codebase,$content) = @_;
 4155:     my @state = ();
 4156:     my (%lastids,%related,%shockwave,%flashvars);
 4157:     my %javafiles = (
 4158:                       codebase => '',
 4159:                       code => '',
 4160:                       archive => ''
 4161:                     );
 4162:     my %mediafiles = (
 4163:                       src => '',
 4164:                       movie => '',
 4165:                      );
 4166:     my $p;
 4167:     if ($content) {
 4168:         $p = HTML::LCParser->new($content);
 4169:     } else {
 4170:         $p = HTML::LCParser->new($fullpath);
 4171:     }
 4172:     while (my $t=$p->get_token()) {
 4173: 	if ($t->[0] eq 'S') {
 4174: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
 4175: 	    push(@state, $tagname);
 4176:             if (lc($tagname) eq 'allow') {
 4177:                 &add_filetype($allfiles,$attr->{'src'},'src');
 4178:             }
 4179: 	    if (lc($tagname) eq 'img') {
 4180: 		&add_filetype($allfiles,$attr->{'src'},'src');
 4181: 	    }
 4182: 	    if (lc($tagname) eq 'a') {
 4183:                 unless (($attr->{'href'} =~ /^#/) || ($attr->{'href'} eq '')) {
 4184:                     &add_filetype($allfiles,$attr->{'href'},'href');
 4185:                 }
 4186: 	    }
 4187:             if (lc($tagname) eq 'script') {
 4188:                 my $src;
 4189:                 if ($attr->{'archive'} =~ /\.jar$/i) {
 4190:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
 4191:                 } else {
 4192:                     if ($attr->{'src'} ne '') {
 4193:                         $src = $attr->{'src'};
 4194:                         &add_filetype($allfiles,$src,'src');
 4195:                     }
 4196:                 }
 4197:                 my $text = $p->get_trimmed_text();
 4198:                 if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
 4199:                     my @swfargs = split(/,/,$1);
 4200:                     foreach my $item (@swfargs) {
 4201:                         $item =~ s/["']//g;
 4202:                         $item =~ s/^\s+//;
 4203:                         $item =~ s/\s+$//;
 4204:                     }
 4205:                     if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
 4206:                         if (ref($related{$swfargs[0]}) eq 'ARRAY') {
 4207:                             push(@{$related{$swfargs[0]}},$swfargs[2]);
 4208:                         } else {
 4209:                             $related{$swfargs[0]} = [$swfargs[2]];
 4210:                         }
 4211:                     }
 4212:                 }
 4213:             }
 4214:             if (lc($tagname) eq 'link') {
 4215:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
 4216:                     &add_filetype($allfiles,$attr->{'href'},'href');
 4217:                 }
 4218:             }
 4219: 	    if (lc($tagname) eq 'object' ||
 4220: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
 4221: 		foreach my $item (keys(%javafiles)) {
 4222: 		    $javafiles{$item} = '';
 4223: 		}
 4224:                 if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
 4225:                     $lastids{lc($tagname)} = $attr->{'id'};
 4226:                 }
 4227: 	    }
 4228: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
 4229: 		my $name = lc($attr->{'name'});
 4230: 		foreach my $item (keys(%javafiles)) {
 4231: 		    if ($name eq $item) {
 4232: 			$javafiles{$item} = $attr->{'value'};
 4233: 			last;
 4234: 		    }
 4235: 		}
 4236:                 my $pathfrom;
 4237: 		foreach my $item (keys(%mediafiles)) {
 4238: 		    if ($name eq $item) {
 4239:                         $pathfrom = $attr->{'value'};
 4240:                         $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
 4241: 			&add_filetype($allfiles,$pathfrom,$name);
 4242: 			last;
 4243: 		    }
 4244: 		}
 4245:                 if ($name eq 'flashvars') {
 4246:                     $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
 4247:                 }
 4248:                 if ($pathfrom ne '') {
 4249:                     &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
 4250:                                          $pathfrom);
 4251:                 }
 4252: 	    }
 4253: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
 4254: 		foreach my $item (keys(%javafiles)) {
 4255: 		    if ($attr->{$item}) {
 4256: 			$javafiles{$item} = $attr->{$item};
 4257: 			last;
 4258: 		    }
 4259: 		}
 4260: 		foreach my $item (keys(%mediafiles)) {
 4261: 		    if ($attr->{$item}) {
 4262: 			&add_filetype($allfiles,$attr->{$item},$item);
 4263: 			last;
 4264: 		    }
 4265: 		}
 4266:                 if (lc($tagname) eq 'embed') {
 4267:                     if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
 4268:                         &embedded_dependency($allfiles,\%related,$attr->{'name'},
 4269:                                              $attr->{'src'});
 4270:                     }
 4271:                 }
 4272: 	    }
 4273:             if (lc($tagname) eq 'iframe') {
 4274:                 my $src = $attr->{'src'} ;
 4275:                 if (($src ne '') && ($src !~ m{^(/|https?://)})) {
 4276:                     &add_filetype($allfiles,$src,'src');
 4277:                 } elsif ($src =~ m{^/}) {
 4278:                     if ($env{'request.course.id'}) {
 4279:                         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 4280:                         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 4281:                         my $url = &hreflocation('',$fullpath);
 4282:                         if ($url =~ m{^/uploaded/$cdom/$cnum/docs/(\w+/\d+)/}) {
 4283:                             my $relpath = $1;
 4284:                             if ($src =~ m{^/uploaded/$cdom/$cnum/docs/\Q$relpath\E/(.+)$}) {
 4285:                                 &add_filetype($allfiles,$1,'src');
 4286:                             }
 4287:                         }
 4288:                     }
 4289:                 }
 4290:             }
 4291:             if ($t->[4] =~ m{/>$}) {
 4292:                 pop(@state);
 4293:             }
 4294: 	} elsif ($t->[0] eq 'E') {
 4295: 	    my ($tagname) = ($t->[1]);
 4296: 	    if ($javafiles{'codebase'} ne '') {
 4297: 		$javafiles{'codebase'} .= '/';
 4298: 	    }  
 4299: 	    if (lc($tagname) eq 'applet' ||
 4300: 		lc($tagname) eq 'object' ||
 4301: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
 4302: 		) {
 4303: 		foreach my $item (keys(%javafiles)) {
 4304: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
 4305: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
 4306: 			&add_filetype($allfiles,$file,$item);
 4307: 		    }
 4308: 		}
 4309: 	    } 
 4310: 	    pop @state;
 4311: 	}
 4312:     }
 4313:     foreach my $id (sort(keys(%flashvars))) {
 4314:         if ($shockwave{$id} ne '') {
 4315:             my @pairs = split(/\&/,$flashvars{$id});
 4316:             foreach my $pair (@pairs) {
 4317:                 my ($key,$value) = split(/\=/,$pair);
 4318:                 if ($key eq 'thumb') {
 4319:                     &add_filetype($allfiles,$value,$key);
 4320:                 } elsif ($key eq 'content') {
 4321:                     my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
 4322:                     my ($ext) = ($value =~ /\.([^.]+)$/);
 4323:                     if ($ext ne '') {
 4324:                         &add_filetype($allfiles,$path.$value,$ext);
 4325:                     }
 4326:                 }
 4327:             }
 4328:         }
 4329:     }
 4330:     return 'ok';
 4331: }
 4332: 
 4333: sub add_filetype {
 4334:     my ($allfiles,$file,$type)=@_;
 4335:     if (exists($allfiles->{$file})) {
 4336: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
 4337: 	    push(@{$allfiles->{$file}}, &escape($type));
 4338: 	}
 4339:     } else {
 4340: 	@{$allfiles->{$file}} = (&escape($type));
 4341:     }
 4342: }
 4343: 
 4344: sub embedded_dependency {
 4345:     my ($allfiles,$related,$identifier,$pathfrom) = @_;
 4346:     if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
 4347:         if (($identifier ne '') &&
 4348:             (ref($related->{$identifier}) eq 'ARRAY') &&
 4349:             ($pathfrom ne '')) {
 4350:             my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
 4351:             foreach my $dep (@{$related->{$identifier}}) {
 4352:                 &add_filetype($allfiles,$path.$dep,'object');
 4353:             }
 4354:         }
 4355:     }
 4356:     return;
 4357: }
 4358: 
 4359: sub bubblesheet_converter {
 4360:     my ($cdom,$fullpath,$config,$format) = @_;
 4361:     if ((&domain($cdom) ne '') &&
 4362:         ($fullpath =~ m{^\Q$perlvar{'lonDocRoot'}/userfiles/$cdom/$match_courseid/scantron_orig}) &&
 4363:         (-e $fullpath) && (ref($config) eq 'HASH') && ($format ne '')) {
 4364:         my %csvcols = %{$config};
 4365:         my %csvbynum = reverse(%csvcols);
 4366:         my %scantronconf = &get_scantron_config($format,$cdom);
 4367:         if (keys(%scantronconf)) {
 4368:             my %bynum = (
 4369:                           $scantronconf{CODEstart} => 'CODEstart',
 4370:                           $scantronconf{IDstart}   => 'IDstart',
 4371:                           $scantronconf{PaperID}   => 'PaperID',
 4372:                           $scantronconf{FirstName} => 'FirstName',
 4373:                           $scantronconf{LastName}  => 'LastName',
 4374:                           $scantronconf{Qstart}    => 'Qstart',
 4375:                         );
 4376:             my @ordered;
 4377:             foreach my $item (sort { $a <=> $b } keys(%bynum)) {
 4378:                 push (@ordered,$bynum{$item}));
 4379:             }
 4380:             my %mapstart = (
 4381:                               CODEstart => 'CODE',
 4382:                               IDstart   => 'ID',
 4383:                               PaperID   => 'PaperID',
 4384:                               FirstName => 'FirstName',
 4385:                               LastName  => 'LastName',
 4386:                               Qstart    => 'FirstQuestion',
 4387:                            );
 4388:             my %maplength = (
 4389:                               CODEstart => 'CODElength',
 4390:                               IDstart   => 'IDlength',
 4391:                               PaperID   => 'PaperIDlength',
 4392:                               FirstName => 'FirstNamelength',
 4393:                               LastName  => 'LastNamelength',
 4394:             );
 4395:             if (open(my $fh,'<',$fullpath)) {
 4396:                 my $output;
 4397:                 while (my $line=<$fh>) {
 4398:                     $line =~ s{[\r\n]+$}{};
 4399:                     my %found;
 4400:                     my @values = split(/,/,$line);
 4401:                     my ($qstart,$record);
 4402:                     for (my $i=0; $i<@values; $i++) {
 4403:                         if (($qstart ne '') && ($i > $qstart)) {
 4404:                             $found{'FirstQuestion'} .= $values[$i];
 4405:                         } elsif (exists($csvbynum{$i})) {
 4406:                             if ($csvbynum{$i} eq 'FirstQuestion') {
 4407:                                 $qstart = $i;
 4408:                             } else {
 4409:                                 $values[$i] =~ s/^\s+//;
 4410:                                 if ($csvbynum{$i} eq 'PaperID') {
 4411:                                     while (length($values[$i]) < $scantronconf{$maplength{$csvbynum{$i}}}) {
 4412:                                         $values[$i] = '0'.$values[$i];
 4413:                                     }
 4414:                                 }
 4415:                             }
 4416:                             $found{$csvbynum{$i}} = $values[$i];
 4417:                         }
 4418:                     }
 4419:                     foreach my $item (@ordered) {
 4420:                         my $currlength = 1+length($record);
 4421:                         my $numspaces = $scantronconf{$item} - $currlength;
 4422:                         if ($numspaces > 0) {
 4423:                             $record .= (' ' x $numspaces);
 4424:                         }
 4425:                         if (($mapstart{$item} ne '') && (exists($found{$mapstart{$item}}))) {
 4426:                             unless ($item eq 'Qstart') {
 4427:                                 if (length($found{$mapstart{$item}}) > $scantronconf{$maplength{$item}}) {
 4428:                                     $found{$mapstart{$item}} = substr($found{$mapstart{$item}},0,$scantronconf{$maplength{$item}});
 4429:                                 }
 4430:                             }
 4431:                             $record .= $found{$mapstart{$item}};
 4432:                         }
 4433:                     }
 4434:                     $output .= "$record\n";
 4435:                 }
 4436:                 close($fh);
 4437:                 if ($output) {
 4438:                     if (open(my $fh,'>',$fullpath)) {
 4439:                         print $fh $output;
 4440:                         close($fh);
 4441:                     }
 4442:                 }
 4443:             }
 4444:         }
 4445:         return;
 4446:     }
 4447: }
 4448: 
 4449: sub get_scantron_config {
 4450:     my ($which,$cdom) = @_;
 4451:     my @lines = &get_scantronformat_file($cdom);
 4452:     my %config;
 4453:     #FIXME probably should move to XML it has already gotten a bit much now
 4454:     foreach my $line (@lines) {
 4455:         my ($name,$descrip)=split(/:/,$line);
 4456:         if ($name ne $which ) { next; }
 4457:         chomp($line);
 4458:         my @config=split(/:/,$line);
 4459:         $config{'name'}=$config[0];
 4460:         $config{'description'}=$config[1];
 4461:         $config{'CODElocation'}=$config[2];
 4462:         $config{'CODEstart'}=$config[3];
 4463:         $config{'CODElength'}=$config[4];
 4464:         $config{'IDstart'}=$config[5];
 4465:         $config{'IDlength'}=$config[6];
 4466:         $config{'Qstart'}=$config[7];
 4467:         $config{'Qlength'}=$config[8];
 4468:         $config{'Qoff'}=$config[9];
 4469:         $config{'Qon'}=$config[10];
 4470:         $config{'PaperID'}=$config[11];
 4471:         $config{'PaperIDlength'}=$config[12];
 4472:         $config{'FirstName'}=$config[13];
 4473:         $config{'FirstNamelength'}=$config[14];
 4474:         $config{'LastName'}=$config[15];
 4475:         $config{'LastNamelength'}=$config[16];
 4476:         $config{'BubblesPerRow'}=$config[17];
 4477:         last;
 4478:     }
 4479:     return %config;
 4480: }
 4481: 
 4482: sub get_scantronformat_file {
 4483:     my ($cdom) = @_;
 4484:     if ($cdom eq '') {
 4485:         $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
 4486:     }
 4487:     my %domconfig = &get_dom('configuration',['scantron'],$cdom);
 4488:     my $gottab = 0;
 4489:     my @lines;
 4490:     if (ref($domconfig{'scantron'}) eq 'HASH') {
 4491:         if ($domconfig{'scantron'}{'scantronformat'} ne '') {
 4492:             my $formatfile = &getfile($perlvar{'lonDocRoot'}.$domconfig{'scantron'}{'scantronformat'});
 4493:             if ($formatfile ne '-1') {
 4494:                 @lines = split("\n",$formatfile,-1);
 4495:                 $gottab = 1;
 4496:             }
 4497:         }
 4498:     }
 4499:     if (!$gottab) {
 4500:         my $confname = $cdom.'-domainconfig';
 4501:         my $default = $perlvar{'lonDocRoot'}.'/res/'.$cdom.'/'.$confname.'/default.tab';
 4502:         my $formatfile = &getfile($default);
 4503:         if ($formatfile ne '-1') {
 4504:             @lines = split("\n",$formatfile,-1);
 4505:             $gottab = 1;
 4506:         }
 4507:     }
 4508:     if (!$gottab) {
 4509:         my @domains = &current_machine_domains();
 4510:         if (grep(/^\Q$cdom\E$/,@domains)) {
 4511:             if (open(my $fh,'<',$perlvar{'lonTabDir'}.'/scantronformat.tab')) {
 4512:                 @lines = <$fh>;
 4513:                 close($fh);
 4514:             }  
 4515:         } else {
 4516:             if (open(my $fh,'<',$perlvar{'lonTabDir'}.'/default_scantronformat.tab')) {
 4517:                 @lines = <$fh>;
 4518:                 close($fh);
 4519:             }
 4520:         }
 4521:     }
 4522:     return @lines;
 4523: }
 4524: 
 4525: sub removeuploadedurl {
 4526:     my ($url)=@_;	
 4527:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);    
 4528:     return &removeuserfile($uname,$udom,$fname);
 4529: }
 4530: 
 4531: sub removeuserfile {
 4532:     my ($docuname,$docudom,$fname)=@_;
 4533:     my $home=&homeserver($docuname,$docudom);    
 4534:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
 4535:     if ($result eq 'ok') {	
 4536:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
 4537:             my $metafile = $fname.'.meta';
 4538:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
 4539: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
 4540:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];	   
 4541:             my $sqlresult = 
 4542:                 &update_portfolio_table($docuname,$docudom,$file,
 4543:                                         'portfolio_metadata',$group,
 4544:                                         'delete');
 4545:         }
 4546:     }
 4547:     return $result;
 4548: }
 4549: 
 4550: sub mkdiruserfile {
 4551:     my ($docuname,$docudom,$dir)=@_;
 4552:     my $home=&homeserver($docuname,$docudom);
 4553:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
 4554: }
 4555: 
 4556: sub renameuserfile {
 4557:     my ($docuname,$docudom,$old,$new)=@_;
 4558:     my $home=&homeserver($docuname,$docudom);
 4559:     my $result = &reply("renameuserfile:$docudom:$docuname:".
 4560:                         &escape("$old").':'.&escape("$new"),$home);
 4561:     if ($result eq 'ok') {
 4562:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
 4563:             my $oldmeta = $old.'.meta';
 4564:             my $newmeta = $new.'.meta';
 4565:             my $metaresult = 
 4566:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
 4567: 	    my $url = "/uploaded/$docudom/$docuname/$old";
 4568:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
 4569:             my $sqlresult = 
 4570:                 &update_portfolio_table($docuname,$docudom,$file,
 4571:                                         'portfolio_metadata',$group,
 4572:                                         'delete');
 4573:         }
 4574:     }
 4575:     return $result;
 4576: }
 4577: 
 4578: # ------------------------------------------------------------------------- Log
 4579: 
 4580: sub log {
 4581:     my ($dom,$nam,$hom,$what)=@_;
 4582:     return critical("log:$dom:$nam:$what",$hom);
 4583: }
 4584: 
 4585: # ------------------------------------------------------------------ Course Log
 4586: #
 4587: # This routine flushes several buffers of non-mission-critical nature
 4588: #
 4589: 
 4590: sub flushcourselogs {
 4591:     &logthis('Flushing log buffers');
 4592: #
 4593: # course logs
 4594: # This is a log of all transactions in a course, which can be used
 4595: # for data mining purposes
 4596: #
 4597: # It also collects the courseid database, which lists last transaction
 4598: # times and course titles for all courseids
 4599: #
 4600:     my %courseidbuffer=();
 4601:     foreach my $crsid (keys(%courselogs)) {
 4602:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
 4603: 		          &escape($courselogs{$crsid}),
 4604: 		          $coursehombuf{$crsid}) eq 'ok') {
 4605: 	    delete $courselogs{$crsid};
 4606:         } else {
 4607:             &logthis('Failed to flush log buffer for '.$crsid);
 4608:             if (length($courselogs{$crsid})>40000) {
 4609:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
 4610:                         " exceeded maximum size, deleting.</font>");
 4611:                delete $courselogs{$crsid};
 4612:             }
 4613:         }
 4614:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
 4615:             'description' => $coursedescrbuf{$crsid},
 4616:             'inst_code'    => $courseinstcodebuf{$crsid},
 4617:             'type'        => $coursetypebuf{$crsid},
 4618:             'owner'       => $courseownerbuf{$crsid},
 4619:         };
 4620:     }
 4621: #
 4622: # Write course id database (reverse lookup) to homeserver of courses 
 4623: # Is used in pickcourse
 4624: #
 4625:     foreach my $crs_home (keys(%courseidbuffer)) {
 4626:         my $response = &courseidput(&host_domain($crs_home),
 4627:                                     $courseidbuffer{$crs_home},
 4628:                                     $crs_home,'timeonly');
 4629:     }
 4630: #
 4631: # File accesses
 4632: # Writes to the dynamic metadata of resources to get hit counts, etc.
 4633: #
 4634:     foreach my $entry (keys(%accesshash)) {
 4635:         if ($entry =~ /___count$/) {
 4636:             my ($dom,$name);
 4637:             ($dom,$name,undef)=
 4638: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
 4639:             if (! defined($dom) || $dom eq '' || 
 4640:                 ! defined($name) || $name eq '') {
 4641:                 my $cid = $env{'request.course.id'};
 4642:                 $dom  = $env{'request.'.$cid.'.domain'};
 4643:                 $name = $env{'request.'.$cid.'.num'};
 4644:             }
 4645:             my $value = $accesshash{$entry};
 4646:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
 4647:             my %temphash=($url => $value);
 4648:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
 4649:             if ($result eq 'ok') {
 4650:                 delete $accesshash{$entry};
 4651:             }
 4652:         } else {
 4653:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
 4654:             if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
 4655:             my %temphash=($entry => $accesshash{$entry});
 4656:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
 4657:                 delete $accesshash{$entry};
 4658:             }
 4659:         }
 4660:     }
 4661: #
 4662: # Roles
 4663: # Reverse lookup of user roles for course faculty/staff and co-authorship
 4664: #
 4665:     foreach my $entry (keys(%userrolehash)) {
 4666:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
 4667: 	    split(/\:/,$entry);
 4668:         if (&Apache::lonnet::put('nohist_userroles',
 4669:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
 4670:                 $rudom,$runame) eq 'ok') {
 4671: 	    delete $userrolehash{$entry};
 4672:         }
 4673:     }
 4674: #
 4675: # Reverse lookup of domain roles (dc, ad, li, sc, dh, da, au)
 4676: #
 4677:     my %domrolebuffer = ();
 4678:     foreach my $entry (keys(%domainrolehash)) {
 4679:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
 4680:         if ($domrolebuffer{$rudom}) {
 4681:             $domrolebuffer{$rudom}.='&'.&escape($entry).
 4682:                       '='.&escape($domainrolehash{$entry});
 4683:         } else {
 4684:             $domrolebuffer{$rudom}.=&escape($entry).
 4685:                       '='.&escape($domainrolehash{$entry});
 4686:         }
 4687:         delete $domainrolehash{$entry};
 4688:     }
 4689:     foreach my $dom (keys(%domrolebuffer)) {
 4690: 	my %servers;
 4691: 	if (defined(&domain($dom,'primary'))) {
 4692: 	    my $primary=&domain($dom,'primary');
 4693: 	    my $hostname=&hostname($primary);
 4694: 	    $servers{$primary} = $hostname;
 4695: 	} else { 
 4696: 	    %servers = &get_servers($dom,'library');
 4697: 	}
 4698: 	foreach my $tryserver (keys(%servers)) {
 4699: 	    if (&reply('domroleput:'.$dom.':'.
 4700: 		       $domrolebuffer{$dom},$tryserver) eq 'ok') {
 4701: 		last;
 4702: 	    } else {  
 4703: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
 4704: 	    }
 4705:         }
 4706:     }
 4707:     $dumpcount++;
 4708: }
 4709: 
 4710: sub courselog {
 4711:     my $what=shift;
 4712:     $what=time.':'.$what;
 4713:     unless ($env{'request.course.id'}) { return ''; }
 4714:     $coursedombuf{$env{'request.course.id'}}=
 4715:        $env{'course.'.$env{'request.course.id'}.'.domain'};
 4716:     $coursenumbuf{$env{'request.course.id'}}=
 4717:        $env{'course.'.$env{'request.course.id'}.'.num'};
 4718:     $coursehombuf{$env{'request.course.id'}}=
 4719:        $env{'course.'.$env{'request.course.id'}.'.home'};
 4720:     $coursedescrbuf{$env{'request.course.id'}}=
 4721:        $env{'course.'.$env{'request.course.id'}.'.description'};
 4722:     $courseinstcodebuf{$env{'request.course.id'}}=
 4723:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
 4724:     $courseownerbuf{$env{'request.course.id'}}=
 4725:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
 4726:     $coursetypebuf{$env{'request.course.id'}}=
 4727:        $env{'course.'.$env{'request.course.id'}.'.type'};
 4728:     if (defined $courselogs{$env{'request.course.id'}}) {
 4729: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
 4730:     } else {
 4731: 	$courselogs{$env{'request.course.id'}}.=$what;
 4732:     }
 4733:     if (length($courselogs{$env{'request.course.id'}})>4048) {
 4734: 	&flushcourselogs();
 4735:     }
 4736: }
 4737: 
 4738: sub courseacclog {
 4739:     my $fnsymb=shift;
 4740:     unless ($env{'request.course.id'}) { return ''; }
 4741:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
 4742:     if ($fnsymb=~/$LONCAPA::assess_re/) {
 4743:         $what.=':POST';
 4744:         # FIXME: Probably ought to escape things....
 4745: 	foreach my $key (keys(%env)) {
 4746:             if ($key=~/^form\.(.*)/) {
 4747:                 my $formitem = $1;
 4748:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
 4749:                     $what.=':'.$formitem.'='.$env{$key};
 4750:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
 4751:                     $what.=':'.$formitem.'='.$env{$key};
 4752:                 }
 4753:             }
 4754:         }
 4755:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
 4756:         # FIXME: We should not be depending on a form parameter that someone
 4757:         # editing lonsearchcat.pm might change in the future.
 4758:         if ($env{'form.phase'} eq 'course_search') {
 4759:             $what.= ':POST';
 4760:             # FIXME: Probably ought to escape things....
 4761:             foreach my $element ('courseexp','crsfulltext','crsrelated',
 4762:                                  'crsdiscuss') {
 4763:                 $what.=':'.$element.'='.$env{'form.'.$element};
 4764:             }
 4765:         }
 4766:     }
 4767:     &courselog($what);
 4768: }
 4769: 
 4770: sub countacc {
 4771:     my $url=&declutter(shift);
 4772:     return if (! defined($url) || $url eq '');
 4773:     unless ($env{'request.course.id'}) { return ''; }
 4774: #
 4775: # Mark that this url was used in this course
 4776: #
 4777:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
 4778: #
 4779: # Increase the access count for this resource in this child process
 4780: #
 4781:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
 4782:     $accesshash{$key}++;
 4783: }
 4784: 
 4785: sub linklog {
 4786:     my ($from,$to)=@_;
 4787:     $from=&declutter($from);
 4788:     $to=&declutter($to);
 4789:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
 4790:     $accesshash{$to.'___'.$from.'___goto'}=1;
 4791: }
 4792: 
 4793: sub statslog {
 4794:     my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
 4795:     if ($users<2) { return; }
 4796:     my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
 4797:             'course'       => $env{'request.course.id'},
 4798:             'sections'     => '"all"',
 4799:             'num_students' => $users,
 4800:             'part'         => $part,
 4801:             'symb'         => $symb,
 4802:             'mean_tries'   => $av_attempts,
 4803:             'deg_of_diff'  => $degdiff});
 4804:     foreach my $key (keys(%dynstore)) {
 4805:         $accesshash{$key}=$dynstore{$key};
 4806:     }
 4807: }
 4808:   
 4809: sub userrolelog {
 4810:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
 4811:     if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
 4812:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 4813:        $userrolehash
 4814:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 4815:                     =$tend.':'.$tstart;
 4816:     }
 4817:     if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
 4818:        $userrolehash
 4819:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
 4820:                     =$tend.':'.$tstart;
 4821:     }
 4822:     if ($trole =~ /^(dc|ad|li|au|dg|sc|dh|da)/ ) {
 4823:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 4824:        $domainrolehash
 4825:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 4826:                     = $tend.':'.$tstart;
 4827:     }
 4828: }
 4829: 
 4830: sub courserolelog {
 4831:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
 4832:     if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
 4833:         my $cdom = $1;
 4834:         my $cnum = $2;
 4835:         my $sec = $3;
 4836:         my $namespace = 'rolelog';
 4837:         my %storehash = (
 4838:                            role    => $trole,
 4839:                            start   => $tstart,
 4840:                            end     => $tend,
 4841:                            selfenroll => $selfenroll,
 4842:                            context    => $context,
 4843:                         );
 4844:         if ($trole eq 'gr') {
 4845:             $namespace = 'groupslog';
 4846:             $storehash{'group'} = $sec;
 4847:         } else {
 4848:             $storehash{'section'} = $sec;
 4849:         }
 4850:         &write_log('course',$namespace,\%storehash,$delflag,$username,
 4851:                    $domain,$cnum,$cdom);
 4852:         if (($trole ne 'st') || ($sec ne '')) {
 4853:             &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
 4854:         }
 4855:     }
 4856:     return;
 4857: }
 4858: 
 4859: sub domainrolelog {
 4860:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
 4861:     if ($area =~ m{^/($match_domain)/$}) {
 4862:         my $cdom = $1;
 4863:         my $domconfiguser = &Apache::lonnet::get_domainconfiguser($cdom);
 4864:         my $namespace = 'rolelog';
 4865:         my %storehash = (
 4866:                            role    => $trole,
 4867:                            start   => $tstart,
 4868:                            end     => $tend,
 4869:                            context => $context,
 4870:                         );
 4871:         &write_log('domain',$namespace,\%storehash,$delflag,$username,
 4872:                    $domain,$domconfiguser,$cdom);
 4873:     }
 4874:     return;
 4875: 
 4876: }
 4877: 
 4878: sub coauthorrolelog {
 4879:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
 4880:     if ($area =~ m{^/($match_domain)/($match_username)$}) {
 4881:         my $audom = $1;
 4882:         my $auname = $2;
 4883:         my $namespace = 'rolelog';
 4884:         my %storehash = (
 4885:                            role    => $trole,
 4886:                            start   => $tstart,
 4887:                            end     => $tend,
 4888:                            context => $context,
 4889:                         );
 4890:         &write_log('author',$namespace,\%storehash,$delflag,$username,
 4891:                    $domain,$auname,$audom);
 4892:     }
 4893:     return;
 4894: }
 4895: 
 4896: sub get_course_adv_roles {
 4897:     my ($cid,$codes) = @_;
 4898:     $cid=$env{'request.course.id'} unless (defined($cid));
 4899:     my %coursehash=&coursedescription($cid);
 4900:     my $crstype = &Apache::loncommon::course_type($cid);
 4901:     my %nothide=();
 4902:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 4903:         if ($user !~ /:/) {
 4904: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
 4905:         } else {
 4906:             $nothide{$user}=1;
 4907:         }
 4908:     }
 4909:     my @possdoms = ($coursehash{'domain'});
 4910:     if ($coursehash{'checkforpriv'}) {
 4911:         push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
 4912:     }
 4913:     my %returnhash=();
 4914:     my %dumphash=
 4915:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
 4916:     my $now=time;
 4917:     my %privileged;
 4918:     foreach my $entry (keys(%dumphash)) {
 4919: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
 4920:         if (($tstart) && ($tstart<0)) { next; }
 4921:         if (($tend) && ($tend<$now)) { next; }
 4922:         if (($tstart) && ($now<$tstart)) { next; }
 4923:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
 4924: 	if ($username eq '' || $domain eq '') { next; }
 4925:         if ((&privileged($username,$domain,\@possdoms)) &&
 4926:             (!$nothide{$username.':'.$domain})) { next; }
 4927: 	if ($role eq 'cr') { next; }
 4928:         if ($codes) {
 4929:             if ($section) { $role .= ':'.$section; }
 4930:             if ($returnhash{$role}) {
 4931:                 $returnhash{$role}.=','.$username.':'.$domain;
 4932:             } else {
 4933:                 $returnhash{$role}=$username.':'.$domain;
 4934:             }
 4935:         } else {
 4936:             my $key=&plaintext($role,$crstype);
 4937:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
 4938:             if ($returnhash{$key}) {
 4939: 	        $returnhash{$key}.=','.$username.':'.$domain;
 4940:             } else {
 4941:                 $returnhash{$key}=$username.':'.$domain;
 4942:             }
 4943:         }
 4944:     }
 4945:     return %returnhash;
 4946: }
 4947: 
 4948: sub get_my_roles {
 4949:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
 4950:     unless (defined($uname)) { $uname=$env{'user.name'}; }
 4951:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
 4952:     my (%dumphash,%nothide);
 4953:     if ($context eq 'userroles') {
 4954:         %dumphash = &dump('roles',$udom,$uname);
 4955:     } else {
 4956:         %dumphash = &dump('nohist_userroles',$udom,$uname);
 4957:         if ($hidepriv) {
 4958:             my %coursehash=&coursedescription($udom.'_'.$uname);
 4959:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 4960:                 if ($user !~ /:/) {
 4961:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
 4962:                 } else {
 4963:                     $nothide{$user} = 1;
 4964:                 }
 4965:             }
 4966:         }
 4967:     }
 4968:     my %returnhash=();
 4969:     my $now=time;
 4970:     my %privileged;
 4971:     foreach my $entry (keys(%dumphash)) {
 4972:         my ($role,$tend,$tstart);
 4973:         if ($context eq 'userroles') {
 4974:             next if ($entry =~ /^rolesdef/);
 4975: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
 4976:         } else {
 4977:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
 4978:         }
 4979:         if (($tstart) && ($tstart<0)) { next; }
 4980:         my $status = 'active';
 4981:         if (($tend) && ($tend<=$now)) {
 4982:             $status = 'previous';
 4983:         } 
 4984:         if (($tstart) && ($now<$tstart)) {
 4985:             $status = 'future';
 4986:         }
 4987:         if (ref($types) eq 'ARRAY') {
 4988:             if (!grep(/^\Q$status\E$/,@{$types})) {
 4989:                 next;
 4990:             } 
 4991:         } else {
 4992:             if ($status ne 'active') {
 4993:                 next;
 4994:             }
 4995:         }
 4996:         my ($rolecode,$username,$domain,$section,$area);
 4997:         if ($context eq 'userroles') {
 4998:             ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
 4999:             (undef,$domain,$username,$section) = split(/\//,$area);
 5000:         } else {
 5001:             ($role,$username,$domain,$section) = split(/\:/,$entry);
 5002:         }
 5003:         if (ref($roledoms) eq 'ARRAY') {
 5004:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
 5005:                 next;
 5006:             }
 5007:         }
 5008:         if (ref($roles) eq 'ARRAY') {
 5009:             if (!grep(/^\Q$role\E$/,@{$roles})) {
 5010:                 if ($role =~ /^cr\//) {
 5011:                     if (!grep(/^cr$/,@{$roles})) {
 5012:                         next;
 5013:                     }
 5014:                 } elsif ($role =~ /^gr\//) {
 5015:                     if (!grep(/^gr$/,@{$roles})) {
 5016:                         next;
 5017:                     }
 5018:                 } else {
 5019:                     next;
 5020:                 }
 5021:             }
 5022:         }
 5023:         if ($hidepriv) {
 5024:             my @privroles = ('dc','su');
 5025:             if ($context eq 'userroles') {
 5026:                 next if (grep(/^\Q$role\E$/,@privroles));
 5027:             } else {
 5028:                 my $possdoms = [$domain];
 5029:                 if (ref($roledoms) eq 'ARRAY') {
 5030:                    push(@{$possdoms},@{$roledoms}); 
 5031:                 }
 5032:                 if (&privileged($username,$domain,$possdoms,\@privroles)) {
 5033:                     if (!$nothide{$username.':'.$domain}) {
 5034:                         next;
 5035:                     }
 5036:                 }
 5037:             }
 5038:         }
 5039:         if ($withsec) {
 5040:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
 5041:                 $tstart.':'.$tend;
 5042:         } else {
 5043:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
 5044:         }
 5045:     }
 5046:     return %returnhash;
 5047: }
 5048: 
 5049: sub get_all_adhocroles {
 5050:     my ($dom) = @_;
 5051:     my @roles_by_num = ();
 5052:     my %domdefaults = &get_domain_defaults($dom);
 5053:     my (%description,%access_in_dom,%access_info);
 5054:     if (ref($domdefaults{'adhocroles'}) eq 'HASH') {
 5055:         my $count = 0;
 5056:         my %domcurrent = %{$domdefaults{'adhocroles'}};
 5057:         my %ordered;
 5058:         foreach my $role (sort(keys(%domcurrent))) {
 5059:             my ($order,$desc,$access_in_dom);
 5060:             if (ref($domcurrent{$role}) eq 'HASH') {
 5061:                 $order = $domcurrent{$role}{'order'};
 5062:                 $desc = $domcurrent{$role}{'desc'};
 5063:                 $access_in_dom{$role} = $domcurrent{$role}{'access'};
 5064:                 $access_info{$role} = $domcurrent{$role}{$access_in_dom{$role}};
 5065:             }
 5066:             if ($order eq '') {
 5067:                 $order = $count;
 5068:             }
 5069:             $ordered{$order} = $role;
 5070:             if ($desc ne '') {
 5071:                 $description{$role} = $desc;
 5072:             } else {
 5073:                 $description{$role}= $role;
 5074:             }
 5075:             $count++;
 5076:         }
 5077:         foreach my $item (sort {$a <=> $b } (keys(%ordered))) {
 5078:             push(@roles_by_num,$ordered{$item});
 5079:         }
 5080:     }
 5081:     return (\@roles_by_num,\%description,\%access_in_dom,\%access_info);
 5082: }
 5083: 
 5084: sub get_my_adhocroles {
 5085:     my ($cid,$checkreg) = @_;
 5086:     my ($cdom,$cnum,%info,@possroles,$description,$roles_by_num);
 5087:     if ($env{'request.course.id'} eq $cid) {
 5088:         $cdom = $env{'course.'.$cid.'.domain'};
 5089:         $cnum = $env{'course.'.$cid.'.num'};
 5090:         $info{'internal.coursecode'} = $env{'course.'.$cid.'.internal.coursecode'};
 5091:     } elsif ($cid =~ /^($match_domain)_($match_courseid)$/) {
 5092:         $cdom = $1;
 5093:         $cnum = $2;
 5094:         %info = &Apache::lonnet::get('environment',['internal.coursecode'],
 5095:                                      $cdom,$cnum);
 5096:     }
 5097:     if (($info{'internal.coursecode'} ne '') && ($checkreg)) {
 5098:         my $user = $env{'user.name'}.':'.$env{'user.domain'};
 5099:         my %rosterhash = &get('classlist',[$user],$cdom,$cnum);
 5100:         if ($rosterhash{$user} ne '') {
 5101:             my $type = (split(/:/,$rosterhash{$user}))[5];
 5102:             return ([],{}) if ($type eq 'auto');
 5103:         }
 5104:     }
 5105:     if (($cdom ne '') && ($cnum ne ''))  {
 5106:         if (($env{"user.role.dh./$cdom/"}) || ($env{"user.role.da./$cdom/"})) {
 5107:             my $then=$env{'user.login.time'};
 5108:             my $update=$env{'user.update.time'};
 5109:             if (!$update) {
 5110:                 $update = $then;
 5111:             }
 5112:             my @liveroles;
 5113:             foreach my $role ('dh','da') {
 5114:                 if ($env{"user.role.$role./$cdom/"}) {
 5115:                     my ($tstart,$tend)=split(/\./,$env{"user.role.$role./$cdom/"});
 5116:                     my $limit = $update;
 5117:                     if ($env{'request.role'} eq "$role./$cdom/") {
 5118:                         $limit = $then;
 5119:                     }
 5120:                     my $activerole = 1;
 5121:                     if ($tstart && $tstart>$limit) { $activerole = 0; }
 5122:                     if ($tend   && $tend  <$limit) { $activerole = 0; }
 5123:                     if ($activerole) {
 5124:                         push(@liveroles,$role);
 5125:                     }
 5126:                 }
 5127:             }
 5128:             if (@liveroles) {
 5129:                 if (&homeserver($cnum,$cdom) ne 'no_host') {
 5130:                     my ($accessref,$accessinfo,%access_in_dom);
 5131:                     ($roles_by_num,$description,$accessref,$accessinfo) = &get_all_adhocroles($cdom);
 5132:                     if (ref($roles_by_num) eq 'ARRAY') {
 5133:                         if (@{$roles_by_num}) {
 5134:                             my %settings;
 5135:                             if ($env{'request.course.id'} eq $cid) {
 5136:                                 foreach my $envkey (keys(%env)) {
 5137:                                     if ($envkey =~ /^\Qcourse.$cid.\E(internal\.adhoc.+)$/) {
 5138:                                         $settings{$1} = $env{$envkey};
 5139:                                     }
 5140:                                 }
 5141:                             } else {
 5142:                                 %settings = &dump('environment',$cdom,$cnum,'internal\.adhoc');
 5143:                             }
 5144:                             my %setincrs;
 5145:                             if ($settings{'internal.adhocaccess'}) {
 5146:                                 map { $setincrs{$_} = 1; } split(/,/,$settings{'internal.adhocaccess'});
 5147:                             }
 5148:                             my @statuses;
 5149:                             if ($env{'environment.inststatus'}) {
 5150:                                 @statuses = split(/,/,$env{'environment.inststatus'});
 5151:                             }
 5152:                             my $user = $env{'user.name'}.':'.$env{'user.domain'};
 5153:                             if (ref($accessref) eq 'HASH') {
 5154:                                 %access_in_dom = %{$accessref};
 5155:                             }
 5156:                             foreach my $role (@{$roles_by_num}) {
 5157:                                 my ($curraccess,@okstatus,@personnel);
 5158:                                 if ($setincrs{$role}) {
 5159:                                     ($curraccess,my $rest) = split(/=/,$settings{'internal.adhoc.'.$role});
 5160:                                     if ($curraccess eq 'status') {
 5161:                                         @okstatus = split(/\&/,$rest);
 5162:                                     } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
 5163:                                         @personnel = split(/\&/,$rest);
 5164:                                     }
 5165:                                 } else {
 5166:                                     $curraccess = $access_in_dom{$role};
 5167:                                     if (ref($accessinfo) eq 'HASH') {
 5168:                                         if ($curraccess eq 'status') {
 5169:                                             if (ref($accessinfo->{$role}) eq 'ARRAY') {
 5170:                                                 @okstatus = @{$accessinfo->{$role}};
 5171:                                             }
 5172:                                         } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
 5173:                                             if (ref($accessinfo->{$role}) eq 'ARRAY') {
 5174:                                                 @personnel = @{$accessinfo->{$role}};
 5175:                                             }
 5176:                                         }
 5177:                                     }
 5178:                                 }
 5179:                                 if ($curraccess eq 'none') {
 5180:                                     next;
 5181:                                 } elsif ($curraccess eq 'all') {
 5182:                                     push(@possroles,$role);
 5183:                                 } elsif ($curraccess eq 'dh') {
 5184:                                     if (grep(/^dh$/,@liveroles)) {
 5185:                                         push(@possroles,$role);
 5186:                                     } else {
 5187:                                         next;
 5188:                                     }
 5189:                                 } elsif ($curraccess eq 'da') {
 5190:                                     if (grep(/^da$/,@liveroles)) {
 5191:                                         push(@possroles,$role);
 5192:                                     } else {
 5193:                                         next;
 5194:                                     }
 5195:                                 } elsif ($curraccess eq 'status') {
 5196:                                     if (@okstatus) {
 5197:                                         if (!@statuses) {
 5198:                                             if (grep(/^default$/,@okstatus)) {
 5199:                                                 push(@possroles,$role);
 5200:                                             }
 5201:                                         } else {
 5202:                                             foreach my $status (@okstatus) {
 5203:                                                 if (grep(/^\Q$status\E$/,@statuses)) {
 5204:                                                     push(@possroles,$role);
 5205:                                                     last;
 5206:                                                 }
 5207:                                             }
 5208:                                         }
 5209:                                     }
 5210:                                 } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
 5211:                                     if (grep(/^\Q$user\E$/,@personnel)) {
 5212:                                         if ($curraccess eq 'exc') {
 5213:                                             push(@possroles,$role);
 5214:                                         }
 5215:                                     } elsif ($curraccess eq 'inc') {
 5216:                                         push(@possroles,$role);
 5217:                                     }
 5218:                                 }
 5219:                             }
 5220:                         }
 5221:                     }
 5222:                 }
 5223:             }
 5224:         }
 5225:     }
 5226:     unless (ref($description) eq 'HASH') {
 5227:         if (ref($roles_by_num) eq 'ARRAY') {
 5228:             my %desc;
 5229:             map { $desc{$_} = $_; } (@{$roles_by_num});
 5230:             $description = \%desc;
 5231:         } else {
 5232:             $description = {};
 5233:         }
 5234:     }
 5235:     return (\@possroles,$description);
 5236: }
 5237: 
 5238: # ----------------------------------------------------- Frontpage Announcements
 5239: #
 5240: #
 5241: 
 5242: sub postannounce {
 5243:     my ($server,$text)=@_;
 5244:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
 5245:     unless ($text=~/\w/) { $text=''; }
 5246:     return &reply('setannounce:'.&escape($text),$server);
 5247: }
 5248: 
 5249: sub getannounce {
 5250: 
 5251:     if (open(my $fh,"<",$perlvar{'lonDocRoot'}.'/announcement.txt')) {
 5252: 	my $announcement='';
 5253: 	while (my $line = <$fh>) { $announcement .= $line; }
 5254: 	close($fh);
 5255: 	if ($announcement=~/\w/) { 
 5256: 	    return 
 5257:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
 5258:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
 5259: 	} else {
 5260: 	    return '';
 5261: 	}
 5262:     } else {
 5263: 	return '';
 5264:     }
 5265: }
 5266: 
 5267: # ---------------------------------------------------------- Course ID routines
 5268: # Deal with domain's nohist_courseid.db files
 5269: #
 5270: 
 5271: sub courseidput {
 5272:     my ($domain,$storehash,$coursehome,$caller) = @_;
 5273:     return unless (ref($storehash) eq 'HASH');
 5274:     my $outcome;
 5275:     if ($caller eq 'timeonly') {
 5276:         my $cids = '';
 5277:         foreach my $item (keys(%$storehash)) {
 5278:             $cids.=&escape($item).'&';
 5279:         }
 5280:         $cids=~s/\&$//;
 5281:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
 5282:                           $coursehome);       
 5283:     } else {
 5284:         my $items = '';
 5285:         foreach my $item (keys(%$storehash)) {
 5286:             $items.= &escape($item).'='.
 5287:                      &freeze_escape($$storehash{$item}).'&';
 5288:         }
 5289:         $items=~s/\&$//;
 5290:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
 5291:                           $coursehome);
 5292:     }
 5293:     if ($outcome eq 'unknown_cmd') {
 5294:         my $what;
 5295:         foreach my $cid (keys(%$storehash)) {
 5296:             $what .= &escape($cid).'=';
 5297:             foreach my $item ('description','inst_code','owner','type') {
 5298:                 $what .= &escape($storehash->{$cid}{$item}).':';
 5299:             }
 5300:             $what =~ s/\:$/&/;
 5301:         }
 5302:         $what =~ s/\&$//;  
 5303:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
 5304:     } else {
 5305:         return $outcome;
 5306:     }
 5307: }
 5308: 
 5309: sub courseiddump {
 5310:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
 5311:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
 5312:         $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
 5313:         $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner,
 5314:         $hasuniquecode,$reqcrsdom,$reqinstcode)=@_;
 5315:     my $as_hash = 1;
 5316:     my %returnhash;
 5317:     if (!$domfilter) { $domfilter=''; }
 5318:     my %libserv = &all_library();
 5319:     foreach my $tryserver (keys(%libserv)) {
 5320:         if ( (  $hostidflag == 1 
 5321: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
 5322: 	     || (!defined($hostidflag)) ) {
 5323: 
 5324: 	    if (($domfilter eq '') ||
 5325: 		(&host_domain($tryserver) eq $domfilter)) {
 5326:                 my $rep;
 5327:                 if (grep { $_ eq $tryserver } current_machine_ids()) {
 5328:                     $rep = LONCAPA::Lond::dump_course_id_handler(
 5329:                         join(":", (&host_domain($tryserver), $sincefilter, 
 5330:                                 &escape($descfilter), &escape($instcodefilter), 
 5331:                                 &escape($ownerfilter), &escape($coursefilter),
 5332:                                 &escape($typefilter), &escape($regexp_ok), 
 5333:                                 $as_hash, &escape($selfenrollonly), 
 5334:                                 &escape($catfilter), $showhidden, $caller, 
 5335:                                 &escape($cloner), &escape($cc_clone), $cloneonly, 
 5336:                                 &escape($createdbefore), &escape($createdafter), 
 5337:                                 &escape($creationcontext),$domcloner,$hasuniquecode,
 5338:                                 $reqcrsdom,&escape($reqinstcode))));
 5339:                 } else {
 5340:                     $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
 5341:                              $sincefilter.':'.&escape($descfilter).':'.
 5342:                              &escape($instcodefilter).':'.&escape($ownerfilter).
 5343:                              ':'.&escape($coursefilter).':'.&escape($typefilter).
 5344:                              ':'.&escape($regexp_ok).':'.$as_hash.':'.
 5345:                              &escape($selfenrollonly).':'.&escape($catfilter).':'.
 5346:                              $showhidden.':'.$caller.':'.&escape($cloner).':'.
 5347:                              &escape($cc_clone).':'.$cloneonly.':'.
 5348:                              &escape($createdbefore).':'.&escape($createdafter).':'.
 5349:                              &escape($creationcontext).':'.$domcloner.':'.$hasuniquecode.
 5350:                              ':'.$reqcrsdom.':'.&escape($reqinstcode),$tryserver);
 5351:                 }
 5352:                      
 5353:                 my @pairs=split(/\&/,$rep);
 5354:                 foreach my $item (@pairs) {
 5355:                     my ($key,$value)=split(/\=/,$item,2);
 5356:                     $key = &unescape($key);
 5357:                     next if ($key =~ /^error: 2 /);
 5358:                     my $result = &thaw_unescape($value);
 5359:                     if (ref($result) eq 'HASH') {
 5360:                         $returnhash{$key}=$result;
 5361:                     } else {
 5362:                         my @responses = split(/:/,$value);
 5363:                         my @items = ('description','inst_code','owner','type');
 5364:                         for (my $i=0; $i<@responses; $i++) {
 5365:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
 5366:                         }
 5367:                     }
 5368:                 }
 5369:             }
 5370:         }
 5371:     }
 5372:     return %returnhash;
 5373: }
 5374: 
 5375: sub courselastaccess {
 5376:     my ($cdom,$cnum,$hostidref) = @_;
 5377:     my %returnhash;
 5378:     if ($cdom && $cnum) {
 5379:         my $chome = &homeserver($cnum,$cdom);
 5380:         if ($chome ne 'no_host') {
 5381:             my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
 5382:             &extract_lastaccess(\%returnhash,$rep);
 5383:         }
 5384:     } else {
 5385:         if (!$cdom) { $cdom=''; }
 5386:         my %libserv = &all_library();
 5387:         foreach my $tryserver (keys(%libserv)) {
 5388:             if (ref($hostidref) eq 'ARRAY') {
 5389:                 next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
 5390:             } 
 5391:             if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
 5392:                 my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
 5393:                 &extract_lastaccess(\%returnhash,$rep);
 5394:             }
 5395:         }
 5396:     }
 5397:     return %returnhash;
 5398: }
 5399: 
 5400: sub extract_lastaccess {
 5401:     my ($returnhash,$rep) = @_;
 5402:     if (ref($returnhash) eq 'HASH') {
 5403:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' || 
 5404:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
 5405:                  $rep eq '') {
 5406:             my @pairs=split(/\&/,$rep);
 5407:             foreach my $item (@pairs) {
 5408:                 my ($key,$value)=split(/\=/,$item,2);
 5409:                 $key = &unescape($key);
 5410:                 next if ($key =~ /^error: 2 /);
 5411:                 $returnhash->{$key} = &thaw_unescape($value);
 5412:             }
 5413:         }
 5414:     }
 5415:     return;
 5416: }
 5417: 
 5418: # ---------------------------------------------------------- DC e-mail
 5419: 
 5420: sub dcmailput {
 5421:     my ($domain,$msgid,$message,$server)=@_;
 5422:     my $status = &Apache::lonnet::critical(
 5423:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
 5424:        &escape($message),$server);
 5425:     return $status;
 5426: }
 5427: 
 5428: sub dcmaildump {
 5429:     my ($dom,$startdate,$enddate,$senders) = @_;
 5430:     my %returnhash=();
 5431: 
 5432:     if (defined(&domain($dom,'primary'))) {
 5433:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
 5434:                                                          &escape($enddate).':';
 5435: 	my @esc_senders=map { &escape($_)} @$senders;
 5436: 	$cmd.=&escape(join('&',@esc_senders));
 5437: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
 5438:             my ($key,$value) = split(/\=/,$line,2);
 5439:             if (($key) && ($value)) {
 5440:                 $returnhash{&unescape($key)} = &unescape($value);
 5441:             }
 5442:         }
 5443:     }
 5444:     return %returnhash;
 5445: }
 5446: # ---------------------------------------------------------- Domain roles
 5447: 
 5448: sub get_domain_roles {
 5449:     my ($dom,$roles,$startdate,$enddate)=@_;
 5450:     if ((!defined($startdate)) || ($startdate eq '')) {
 5451:         $startdate = '.';
 5452:     }
 5453:     if ((!defined($enddate)) || ($enddate eq '')) {
 5454:         $enddate = '.';
 5455:     }
 5456:     my $rolelist;
 5457:     if (ref($roles) eq 'ARRAY') {
 5458:         $rolelist = join('&',@{$roles});
 5459:     }
 5460:     my %personnel = ();
 5461: 
 5462:     my %servers = &get_servers($dom,'library');
 5463:     foreach my $tryserver (keys(%servers)) {
 5464: 	%{$personnel{$tryserver}}=();
 5465: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
 5466: 					    &escape($startdate).':'.
 5467: 					    &escape($enddate).':'.
 5468: 					    &escape($rolelist), $tryserver))) {
 5469: 	    my ($key,$value) = split(/\=/,$line,2);
 5470: 	    if (($key) && ($value)) {
 5471: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
 5472: 	    }
 5473: 	}
 5474:     }
 5475:     return %personnel;
 5476: }
 5477: 
 5478: sub get_active_domroles {
 5479:     my ($dom,$roles) = @_;
 5480:     return () unless (ref($roles) eq 'ARRAY');
 5481:     my $now = time;
 5482:     my %dompersonnel = &get_domain_roles($dom,$roles,$now,$now);
 5483:     my %domroles;
 5484:     foreach my $server (keys(%dompersonnel)) {
 5485:         foreach my $user (sort(keys(%{$dompersonnel{$server}}))) {
 5486:             my ($trole,$uname,$udom,$runame,$rudom,$rsec) = split(/:/,$user);
 5487:             $domroles{$uname.':'.$udom} = $dompersonnel{$server}{$user};
 5488:         }
 5489:     }
 5490:     return %domroles;
 5491: }
 5492: 
 5493: # ----------------------------------------------------------- Interval timing 
 5494: 
 5495: {
 5496: # Caches needed for speedup of navmaps
 5497: # We don't want to cache this for very long at all (5 seconds at most)
 5498: # 
 5499: # The user for whom we cache
 5500: my $cachedkey='';
 5501: # The cached times for this user
 5502: my %cachedtimes=();
 5503: # When this was last done
 5504: my $cachedtime='';
 5505: 
 5506: sub load_all_first_access {
 5507:     my ($uname,$udom,$ignorecache)=@_;
 5508:     if (($cachedkey eq $uname.':'.$udom) &&
 5509:         (abs($cachedtime-time)<5) && (!$env{'form.markaccess'}) &&
 5510:         (!$ignorecache)) {
 5511:         return;
 5512:     }
 5513:     $cachedtime=time;
 5514:     $cachedkey=$uname.':'.$udom;
 5515:     %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
 5516: }
 5517: 
 5518: sub get_first_access {
 5519:     my ($type,$argsymb,$argmap,$ignorecache)=@_;
 5520:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 5521:     if ($argsymb) { $symb=$argsymb; }
 5522:     my ($map,$id,$res)=&decode_symb($symb);
 5523:     if ($argmap) { $map = $argmap; }
 5524:     if ($type eq 'course') {
 5525: 	$res='course';
 5526:     } elsif ($type eq 'map') {
 5527: 	$res=&symbread($map);
 5528:     } else {
 5529: 	$res=$symb;
 5530:     }
 5531:     &load_all_first_access($uname,$udom,$ignorecache);
 5532:     return $cachedtimes{"$courseid\0$res"};
 5533: }
 5534: 
 5535: sub set_first_access {
 5536:     my ($type,$interval)=@_;
 5537:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 5538:     my ($map,$id,$res)=&decode_symb($symb);
 5539:     if ($type eq 'course') {
 5540: 	$res='course';
 5541:     } elsif ($type eq 'map') {
 5542: 	$res=&symbread($map);
 5543:     } else {
 5544: 	$res=$symb;
 5545:     }
 5546:     $cachedkey='';
 5547:     my $firstaccess=&get_first_access($type,$symb,$map);
 5548:     if ($firstaccess) {
 5549:         &logthis("First access time already set ($firstaccess) when attempting ".
 5550:                  "to set new value (type: $type, extent: $res) for $uname:$udom ".
 5551:                  "in $courseid");
 5552:         return 'already_set';
 5553:     } else {
 5554:         my $start = time;
 5555: 	my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
 5556:                           $udom,$uname);
 5557:         if ($putres eq 'ok') {
 5558:             &put('timerinterval',{"$courseid\0$res"=>$interval},
 5559:                  $udom,$uname); 
 5560:             &appenv(
 5561:                      {
 5562:                         'course.'.$courseid.'.firstaccess.'.$res   => $start,
 5563:                         'course.'.$courseid.'.timerinterval.'.$res => $interval,
 5564:                      }
 5565:                   );
 5566:             if (($cachedtime) && (abs($start-$cachedtime) < 5)) {
 5567:                 $cachedtimes{"$courseid\0$res"} = $start;
 5568:             }
 5569:         } elsif ($putres ne 'refused') {
 5570:             &logthis("Result: $putres when attempting to set first access time ".
 5571:                      "(type: $type, extent: $res) for $uname:$udom in $courseid");
 5572:         }
 5573:         return $putres;
 5574:     }
 5575:     return 'already_set';
 5576: }
 5577: }
 5578: 
 5579: # --------------------------------------------- Set Expire Date for Spreadsheet
 5580: 
 5581: sub expirespread {
 5582:     my ($uname,$udom,$stype,$usymb)=@_;
 5583:     my $cid=$env{'request.course.id'}; 
 5584:     if ($cid) {
 5585:        my $now=time;
 5586:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
 5587:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
 5588:                             $env{'course.'.$cid.'.num'}.
 5589: 	        	    ':nohist_expirationdates:'.
 5590:                             &escape($key).'='.$now,
 5591:                             $env{'course.'.$cid.'.home'})
 5592:     }
 5593:     return 'ok';
 5594: }
 5595: 
 5596: # ----------------------------------------------------- Devalidate Spreadsheets
 5597: 
 5598: sub devalidate {
 5599:     my ($symb,$uname,$udom)=@_;
 5600:     my $cid=$env{'request.course.id'}; 
 5601:     if ($cid) {
 5602:         # delete the stored spreadsheets for
 5603:         # - the student level sheet of this user in course's homespace
 5604:         # - the assessment level sheet for this resource 
 5605:         #   for this user in user's homespace
 5606: 	# - current conditional state info
 5607: 	my $key=$uname.':'.$udom.':';
 5608:         my $status=
 5609: 	    &del('nohist_calculatedsheets',
 5610: 		 [$key.'studentcalc:'],
 5611: 		 $env{'course.'.$cid.'.domain'},
 5612: 		 $env{'course.'.$cid.'.num'})
 5613: 		.' '.
 5614: 	    &del('nohist_calculatedsheets_'.$cid,
 5615: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
 5616:         unless ($status eq 'ok ok') {
 5617:            &logthis('Could not devalidate spreadsheet '.
 5618:                     $uname.' at '.$udom.' for '.
 5619: 		    $symb.': '.$status);
 5620:         }
 5621: 	&delenv('user.state.'.$cid);
 5622:     }
 5623: }
 5624: 
 5625: sub get_scalar {
 5626:     my ($string,$end) = @_;
 5627:     my $value;
 5628:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
 5629: 	$value = $1;
 5630:     } elsif ($$string =~ s/^([^&]*?)&//) {
 5631: 	$value = $1;
 5632:     }
 5633:     return &unescape($value);
 5634: }
 5635: 
 5636: sub array2str {
 5637:   my (@array) = @_;
 5638:   my $result=&arrayref2str(\@array);
 5639:   $result=~s/^__ARRAY_REF__//;
 5640:   $result=~s/__END_ARRAY_REF__$//;
 5641:   return $result;
 5642: }
 5643: 
 5644: sub arrayref2str {
 5645:   my ($arrayref) = @_;
 5646:   my $result='__ARRAY_REF__';
 5647:   foreach my $elem (@$arrayref) {
 5648:     if(ref($elem) eq 'ARRAY') {
 5649:       $result.=&arrayref2str($elem).'&';
 5650:     } elsif(ref($elem) eq 'HASH') {
 5651:       $result.=&hashref2str($elem).'&';
 5652:     } elsif(ref($elem)) {
 5653:       #print("Got a ref of ".(ref($elem))." skipping.");
 5654:     } else {
 5655:       $result.=&escape($elem).'&';
 5656:     }
 5657:   }
 5658:   $result=~s/\&$//;
 5659:   $result .= '__END_ARRAY_REF__';
 5660:   return $result;
 5661: }
 5662: 
 5663: sub hash2str {
 5664:   my (%hash) = @_;
 5665:   my $result=&hashref2str(\%hash);
 5666:   $result=~s/^__HASH_REF__//;
 5667:   $result=~s/__END_HASH_REF__$//;
 5668:   return $result;
 5669: }
 5670: 
 5671: sub hashref2str {
 5672:   my ($hashref)=@_;
 5673:   my $result='__HASH_REF__';
 5674:   foreach my $key (sort(keys(%$hashref))) {
 5675:     if (ref($key) eq 'ARRAY') {
 5676:       $result.=&arrayref2str($key).'=';
 5677:     } elsif (ref($key) eq 'HASH') {
 5678:       $result.=&hashref2str($key).'=';
 5679:     } elsif (ref($key)) {
 5680:       $result.='=';
 5681:       #print("Got a ref of ".(ref($key))." skipping.");
 5682:     } else {
 5683: 	if (defined($key)) {$result.=&escape($key).'=';} else { last; }
 5684:     }
 5685: 
 5686:     if(ref($hashref->{$key}) eq 'ARRAY') {
 5687:       $result.=&arrayref2str($hashref->{$key}).'&';
 5688:     } elsif(ref($hashref->{$key}) eq 'HASH') {
 5689:       $result.=&hashref2str($hashref->{$key}).'&';
 5690:     } elsif(ref($hashref->{$key})) {
 5691:        $result.='&';
 5692:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
 5693:     } else {
 5694:       $result.=&escape($hashref->{$key}).'&';
 5695:     }
 5696:   }
 5697:   $result=~s/\&$//;
 5698:   $result .= '__END_HASH_REF__';
 5699:   return $result;
 5700: }
 5701: 
 5702: sub str2hash {
 5703:     my ($string)=@_;
 5704:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
 5705:     return %$hash;
 5706: }
 5707: 
 5708: sub str2hashref {
 5709:   my ($string) = @_;
 5710: 
 5711:   my %hash;
 5712: 
 5713:   if($string !~ /^__HASH_REF__/) {
 5714:       if (! ($string eq '' || !defined($string))) {
 5715: 	  $hash{'error'}='Not hash reference';
 5716:       }
 5717:       return (\%hash, $string);
 5718:   }
 5719: 
 5720:   $string =~ s/^__HASH_REF__//;
 5721: 
 5722:   while($string !~ /^__END_HASH_REF__/) {
 5723:       #key
 5724:       my $key='';
 5725:       if($string =~ /^__HASH_REF__/) {
 5726:           ($key, $string)=&str2hashref($string);
 5727:           if(defined($key->{'error'})) {
 5728:               $hash{'error'}='Bad data';
 5729:               return (\%hash, $string);
 5730:           }
 5731:       } elsif($string =~ /^__ARRAY_REF__/) {
 5732:           ($key, $string)=&str2arrayref($string);
 5733:           if($key->[0] eq 'Array reference error') {
 5734:               $hash{'error'}='Bad data';
 5735:               return (\%hash, $string);
 5736:           }
 5737:       } else {
 5738:           $string =~ s/^(.*?)=//;
 5739: 	  $key=&unescape($1);
 5740:       }
 5741:       $string =~ s/^=//;
 5742: 
 5743:       #value
 5744:       my $value='';
 5745:       if($string =~ /^__HASH_REF__/) {
 5746:           ($value, $string)=&str2hashref($string);
 5747:           if(defined($value->{'error'})) {
 5748:               $hash{'error'}='Bad data';
 5749:               return (\%hash, $string);
 5750:           }
 5751:       } elsif($string =~ /^__ARRAY_REF__/) {
 5752:           ($value, $string)=&str2arrayref($string);
 5753:           if($value->[0] eq 'Array reference error') {
 5754:               $hash{'error'}='Bad data';
 5755:               return (\%hash, $string);
 5756:           }
 5757:       } else {
 5758: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
 5759:       }
 5760:       $string =~ s/^&//;
 5761: 
 5762:       $hash{$key}=$value;
 5763:   }
 5764: 
 5765:   $string =~ s/^__END_HASH_REF__//;
 5766: 
 5767:   return (\%hash, $string);
 5768: }
 5769: 
 5770: sub str2array {
 5771:     my ($string)=@_;
 5772:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
 5773:     return @$array;
 5774: }
 5775: 
 5776: sub str2arrayref {
 5777:   my ($string) = @_;
 5778:   my @array;
 5779: 
 5780:   if($string !~ /^__ARRAY_REF__/) {
 5781:       if (! ($string eq '' || !defined($string))) {
 5782: 	  $array[0]='Array reference error';
 5783:       }
 5784:       return (\@array, $string);
 5785:   }
 5786: 
 5787:   $string =~ s/^__ARRAY_REF__//;
 5788: 
 5789:   while($string !~ /^__END_ARRAY_REF__/) {
 5790:       my $value='';
 5791:       if($string =~ /^__HASH_REF__/) {
 5792:           ($value, $string)=&str2hashref($string);
 5793:           if(defined($value->{'error'})) {
 5794:               $array[0] ='Array reference error';
 5795:               return (\@array, $string);
 5796:           }
 5797:       } elsif($string =~ /^__ARRAY_REF__/) {
 5798:           ($value, $string)=&str2arrayref($string);
 5799:           if($value->[0] eq 'Array reference error') {
 5800:               $array[0] ='Array reference error';
 5801:               return (\@array, $string);
 5802:           }
 5803:       } else {
 5804: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
 5805:       }
 5806:       $string =~ s/^&//;
 5807: 
 5808:       push(@array, $value);
 5809:   }
 5810: 
 5811:   $string =~ s/^__END_ARRAY_REF__//;
 5812: 
 5813:   return (\@array, $string);
 5814: }
 5815: 
 5816: # -------------------------------------------------------------------Temp Store
 5817: 
 5818: sub tmpreset {
 5819:   my ($symb,$namespace,$domain,$stuname) = @_;
 5820:   if (!$symb) {
 5821:     $symb=&symbread();
 5822:     if (!$symb) { $symb= $env{'request.url'}; }
 5823:   }
 5824:   $symb=escape($symb);
 5825: 
 5826:   if (!$namespace) { $namespace=$env{'request.state'}; }
 5827:   $namespace=~s/\//\_/g;
 5828:   $namespace=~s/\W//g;
 5829: 
 5830:   if (!$domain) { $domain=$env{'user.domain'}; }
 5831:   if (!$stuname) { $stuname=$env{'user.name'}; }
 5832:   if ($domain eq 'public' && $stuname eq 'public') {
 5833:       $stuname=$ENV{'REMOTE_ADDR'};
 5834:   }
 5835:   my $path=LONCAPA::tempdir();
 5836:   my %hash;
 5837:   if (tie(%hash,'GDBM_File',
 5838: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 5839: 	  &GDBM_WRCREAT(),0640)) {
 5840:     foreach my $key (keys(%hash)) {
 5841:       if ($key=~ /:$symb/) {
 5842: 	delete($hash{$key});
 5843:       }
 5844:     }
 5845:   }
 5846: }
 5847: 
 5848: sub tmpstore {
 5849:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 5850: 
 5851:   if (!$symb) {
 5852:     $symb=&symbread();
 5853:     if (!$symb) { $symb= $env{'request.url'}; }
 5854:   }
 5855:   $symb=escape($symb);
 5856: 
 5857:   if (!$namespace) {
 5858:     # I don't think we would ever want to store this for a course.
 5859:     # it seems this will only be used if we don't have a course.
 5860:     #$namespace=$env{'request.course.id'};
 5861:     #if (!$namespace) {
 5862:       $namespace=$env{'request.state'};
 5863:     #}
 5864:   }
 5865:   $namespace=~s/\//\_/g;
 5866:   $namespace=~s/\W//g;
 5867:   if (!$domain) { $domain=$env{'user.domain'}; }
 5868:   if (!$stuname) { $stuname=$env{'user.name'}; }
 5869:   if ($domain eq 'public' && $stuname eq 'public') {
 5870:       $stuname=$ENV{'REMOTE_ADDR'};
 5871:   }
 5872:   my $now=time;
 5873:   my %hash;
 5874:   my $path=LONCAPA::tempdir();
 5875:   if (tie(%hash,'GDBM_File',
 5876: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 5877: 	  &GDBM_WRCREAT(),0640)) {
 5878:     $hash{"version:$symb"}++;
 5879:     my $version=$hash{"version:$symb"};
 5880:     my $allkeys=''; 
 5881:     foreach my $key (keys(%$storehash)) {
 5882:       $allkeys.=$key.':';
 5883:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
 5884:     }
 5885:     $hash{"$version:$symb:timestamp"}=$now;
 5886:     $allkeys.='timestamp';
 5887:     $hash{"$version:keys:$symb"}=$allkeys;
 5888:     if (untie(%hash)) {
 5889:       return 'ok';
 5890:     } else {
 5891:       return "error:$!";
 5892:     }
 5893:   } else {
 5894:     return "error:$!";
 5895:   }
 5896: }
 5897: 
 5898: # -----------------------------------------------------------------Temp Restore
 5899: 
 5900: sub tmprestore {
 5901:   my ($symb,$namespace,$domain,$stuname) = @_;
 5902: 
 5903:   if (!$symb) {
 5904:     $symb=&symbread();
 5905:     if (!$symb) { $symb= $env{'request.url'}; }
 5906:   }
 5907:   $symb=escape($symb);
 5908: 
 5909:   if (!$namespace) { $namespace=$env{'request.state'}; }
 5910: 
 5911:   if (!$domain) { $domain=$env{'user.domain'}; }
 5912:   if (!$stuname) { $stuname=$env{'user.name'}; }
 5913:   if ($domain eq 'public' && $stuname eq 'public') {
 5914:       $stuname=$ENV{'REMOTE_ADDR'};
 5915:   }
 5916:   my %returnhash;
 5917:   $namespace=~s/\//\_/g;
 5918:   $namespace=~s/\W//g;
 5919:   my %hash;
 5920:   my $path=LONCAPA::tempdir();
 5921:   if (tie(%hash,'GDBM_File',
 5922: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 5923: 	  &GDBM_READER(),0640)) {
 5924:     my $version=$hash{"version:$symb"};
 5925:     $returnhash{'version'}=$version;
 5926:     my $scope;
 5927:     for ($scope=1;$scope<=$version;$scope++) {
 5928:       my $vkeys=$hash{"$scope:keys:$symb"};
 5929:       my @keys=split(/:/,$vkeys);
 5930:       my $key;
 5931:       $returnhash{"$scope:keys"}=$vkeys;
 5932:       foreach $key (@keys) {
 5933: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 5934: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 5935:       }
 5936:     }
 5937:     if (!(untie(%hash))) {
 5938:       return "error:$!";
 5939:     }
 5940:   } else {
 5941:     return "error:$!";
 5942:   }
 5943:   return %returnhash;
 5944: }
 5945: 
 5946: # ----------------------------------------------------------------------- Store
 5947: 
 5948: sub store {
 5949:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
 5950:     my $home='';
 5951: 
 5952:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 5953: 
 5954:     $symb=&symbclean($symb);
 5955:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 5956: 
 5957:     if (!$domain) { $domain=$env{'user.domain'}; }
 5958:     if (!$stuname) { $stuname=$env{'user.name'}; }
 5959: 
 5960:     &devalidate($symb,$stuname,$domain);
 5961: 
 5962:     $symb=escape($symb);
 5963:     if (!$namespace) { 
 5964:        unless ($namespace=$env{'request.course.id'}) { 
 5965:           return ''; 
 5966:        } 
 5967:     }
 5968:     if (!$home) { $home=$env{'user.home'}; }
 5969: 
 5970:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
 5971:     $$storehash{'host'}=$perlvar{'lonHostID'};
 5972: 
 5973:     my $namevalue='';
 5974:     foreach my $key (keys(%$storehash)) {
 5975:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 5976:     }
 5977:     $namevalue=~s/\&$//;
 5978:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
 5979:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
 5980: }
 5981: 
 5982: # -------------------------------------------------------------- Critical Store
 5983: 
 5984: sub cstore {
 5985:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
 5986:     my $home='';
 5987: 
 5988:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 5989: 
 5990:     $symb=&symbclean($symb);
 5991:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 5992: 
 5993:     if (!$domain) { $domain=$env{'user.domain'}; }
 5994:     if (!$stuname) { $stuname=$env{'user.name'}; }
 5995: 
 5996:     &devalidate($symb,$stuname,$domain);
 5997: 
 5998:     $symb=escape($symb);
 5999:     if (!$namespace) { 
 6000:        unless ($namespace=$env{'request.course.id'}) { 
 6001:           return ''; 
 6002:        } 
 6003:     }
 6004:     if (!$home) { $home=$env{'user.home'}; }
 6005: 
 6006:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
 6007:     $$storehash{'host'}=$perlvar{'lonHostID'};
 6008: 
 6009:     my $namevalue='';
 6010:     foreach my $key (keys(%$storehash)) {
 6011:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 6012:     }
 6013:     $namevalue=~s/\&$//;
 6014:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
 6015:     return critical
 6016:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
 6017: }
 6018: 
 6019: # --------------------------------------------------------------------- Restore
 6020: 
 6021: sub restore {
 6022:     my ($symb,$namespace,$domain,$stuname) = @_;
 6023:     my $home='';
 6024: 
 6025:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 6026: 
 6027:     if (!$symb) {
 6028:         return if ($namespace eq 'courserequests');
 6029:         unless ($symb=escape(&symbread())) { return ''; }
 6030:     } else {
 6031:         unless ($namespace eq 'courserequests') {
 6032:             $symb=&escape(&symbclean($symb));
 6033:         }
 6034:     }
 6035:     if (!$namespace) { 
 6036:        unless ($namespace=$env{'request.course.id'}) { 
 6037:           return ''; 
 6038:        } 
 6039:     }
 6040:     if (!$domain) { $domain=$env{'user.domain'}; }
 6041:     if (!$stuname) { $stuname=$env{'user.name'}; }
 6042:     if (!$home) { $home=$env{'user.home'}; }
 6043:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
 6044: 
 6045:     my %returnhash=();
 6046:     foreach my $line (split(/\&/,$answer)) {
 6047: 	my ($name,$value)=split(/\=/,$line);
 6048:         $returnhash{&unescape($name)}=&thaw_unescape($value);
 6049:     }
 6050:     my $version;
 6051:     for ($version=1;$version<=$returnhash{'version'};$version++) {
 6052:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
 6053:           $returnhash{$item}=$returnhash{$version.':'.$item};
 6054:        }
 6055:     }
 6056:     return %returnhash;
 6057: }
 6058: 
 6059: # ---------------------------------------------------------- Course Description
 6060: #
 6061: #  
 6062: 
 6063: sub coursedescription {
 6064:     my ($courseid,$args)=@_;
 6065:     $courseid=~s/^\///;
 6066:     $courseid=~s/\_/\//g;
 6067:     my ($cdomain,$cnum)=split(/\//,$courseid);
 6068:     my $chome=&homeserver($cnum,$cdomain);
 6069:     my $normalid=$cdomain.'_'.$cnum;
 6070:     # need to always cache even if we get errors otherwise we keep 
 6071:     # trying and trying and trying to get the course description.
 6072:     my %envhash=();
 6073:     my %returnhash=();
 6074:     
 6075:     my $expiretime=600;
 6076:     if ($env{'request.course.id'} eq $normalid) {
 6077: 	$expiretime=120;
 6078:     }
 6079: 
 6080:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
 6081:     if (!$args->{'freshen_cache'}
 6082: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
 6083: 	foreach my $key (keys(%env)) {
 6084: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
 6085: 	    my ($setting) = $1;
 6086: 	    $returnhash{$setting} = $env{$key};
 6087: 	}
 6088: 	return %returnhash;
 6089:     }
 6090: 
 6091:     # get the data again
 6092: 
 6093:     if (!$args->{'one_time'}) {
 6094: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
 6095:     }
 6096: 
 6097:     if ($chome ne 'no_host') {
 6098:        %returnhash=&dump('environment',$cdomain,$cnum);
 6099:        if (!exists($returnhash{'con_lost'})) {
 6100: 	   my $username = $env{'user.name'}; # Defult username
 6101: 	   if(defined $args->{'user'}) {
 6102: 	       $username = $args->{'user'};
 6103: 	   }
 6104:            $returnhash{'home'}= $chome;
 6105: 	   $returnhash{'domain'} = $cdomain;
 6106: 	   $returnhash{'num'} = $cnum;
 6107:            if (!defined($returnhash{'type'})) {
 6108:                $returnhash{'type'} = 'Course';
 6109:            }
 6110:            while (my ($name,$value) = each %returnhash) {
 6111:                $envhash{'course.'.$normalid.'.'.$name}=$value;
 6112:            }
 6113:            $returnhash{'url'}=&clutter($returnhash{'url'});
 6114:            $returnhash{'fn'}=LONCAPA::tempdir() .
 6115: 	       $username.'_'.$cdomain.'_'.$cnum;
 6116:            $envhash{'course.'.$normalid.'.home'}=$chome;
 6117:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
 6118:            $envhash{'course.'.$normalid.'.num'}=$cnum;
 6119:        }
 6120:     }
 6121:     if (!$args->{'one_time'}) {
 6122: 	&appenv(\%envhash);
 6123:     }
 6124:     return %returnhash;
 6125: }
 6126: 
 6127: sub update_released_required {
 6128:     my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
 6129:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
 6130:         $cid = $env{'request.course.id'};
 6131:         $cdom = $env{'course.'.$cid.'.domain'};
 6132:         $cnum = $env{'course.'.$cid.'.num'};
 6133:         $chome = $env{'course.'.$cid.'.home'};
 6134:     }
 6135:     if ($needsrelease) {
 6136:         my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
 6137:         my $needsupdate;
 6138:         if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
 6139:             $needsupdate = 1;
 6140:         } else {
 6141:             my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
 6142:             my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
 6143:             if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
 6144:                 $needsupdate = 1;
 6145:             }
 6146:         }
 6147:         if ($needsupdate) {
 6148:             my %needshash = (
 6149:                              'internal.releaserequired' => $needsrelease,
 6150:                             );
 6151:             my $putresult = &put('environment',\%needshash,$cdom,$cnum);
 6152:             if ($putresult eq 'ok') {
 6153:                 &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
 6154:                 my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
 6155:                 if (ref($crsinfo{$cid}) eq 'HASH') {
 6156:                     $crsinfo{$cid}{'releaserequired'} = $needsrelease;
 6157:                     &courseidput($cdom,\%crsinfo,$chome,'notime');
 6158:                 }
 6159:             }
 6160:         }
 6161:     }
 6162:     return;
 6163: }
 6164: 
 6165: # -------------------------------------------------See if a user is privileged
 6166: 
 6167: sub privileged {
 6168:     my ($username,$domain,$possdomains,$possroles)=@_;
 6169:     my $now = time;
 6170:     my $roles;
 6171:     if (ref($possroles) eq 'ARRAY') {
 6172:         $roles = $possroles; 
 6173:     } else {
 6174:         $roles = ['dc','su'];
 6175:     }
 6176:     if (ref($possdomains) eq 'ARRAY') {
 6177:         my %privileged = &privileged_by_domain($possdomains,$roles);
 6178:         foreach my $dom (@{$possdomains}) {
 6179:             if (($username =~ /^$match_username$/) && ($domain =~ /^$match_domain$/) &&
 6180:                 (ref($privileged{$dom}) eq 'HASH')) {
 6181:                 foreach my $role (@{$roles}) {
 6182:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
 6183:                         if (exists($privileged{$dom}{$role}{$username.':'.$domain})) {
 6184:                             my ($end,$start) = split(/:/,$privileged{$dom}{$role}{$username.':'.$domain});
 6185:                             return 1 unless (($end && $end < $now) ||
 6186:                                              ($start && $start > $now));
 6187:                         }
 6188:                     }
 6189:                 }
 6190:             }
 6191:         }
 6192:     } else {
 6193:         my %rolesdump = &dump("roles", $domain, $username) or return 0;
 6194:         my $now = time;
 6195: 
 6196:         for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys(%rolesdump)}) {
 6197:             my ($trole, $tend, $tstart) = split(/_/, $role);
 6198:             if (grep(/^\Q$trole\E$/,@{$roles})) {
 6199:                 return 1 unless ($tend && $tend < $now) 
 6200:                         or ($tstart && $tstart > $now);
 6201:             }
 6202:         }
 6203:     }
 6204:     return 0;
 6205: }
 6206: 
 6207: sub privileged_by_domain {
 6208:     my ($domains,$roles) = @_;
 6209:     my %privileged = ();
 6210:     my $cachetime = 60*60*24;
 6211:     my $now = time;
 6212:     unless ((ref($domains) eq 'ARRAY') && (ref($roles) eq 'ARRAY')) {
 6213:         return %privileged;
 6214:     }
 6215:     foreach my $dom (@{$domains}) {
 6216:         next if (ref($privileged{$dom}) eq 'HASH');
 6217:         my $needroles;
 6218:         foreach my $role (@{$roles}) {
 6219:             my ($result,$cached)=&is_cached_new('priv_'.$role,$dom);
 6220:             if (defined($cached)) {
 6221:                 if (ref($result) eq 'HASH') {
 6222:                     $privileged{$dom}{$role} = $result;
 6223:                 }
 6224:             } else {
 6225:                 $needroles = 1;
 6226:             }
 6227:         }
 6228:         if ($needroles) {
 6229:             my %dompersonnel = &get_domain_roles($dom,$roles);
 6230:             $privileged{$dom} = {};
 6231:             foreach my $server (keys(%dompersonnel)) {
 6232:                 if (ref($dompersonnel{$server}) eq 'HASH') {
 6233:                     foreach my $item (keys(%{$dompersonnel{$server}})) {
 6234:                         my ($trole,$uname,$udom,$rest) = split(/:/,$item,4);
 6235:                         my ($end,$start) = split(/:/,$dompersonnel{$server}{$item});
 6236:                         next if ($end && $end < $now);
 6237:                         $privileged{$dom}{$trole}{$uname.':'.$udom} = 
 6238:                             $dompersonnel{$server}{$item};
 6239:                     }
 6240:                 }
 6241:             }
 6242:             if (ref($privileged{$dom}) eq 'HASH') {
 6243:                 foreach my $role (@{$roles}) {
 6244:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
 6245:                         &do_cache_new('priv_'.$role,$dom,$privileged{$dom}{$role},$cachetime);
 6246:                     } else {
 6247:                         my %hash = ();
 6248:                         &do_cache_new('priv_'.$role,$dom,\%hash,$cachetime);
 6249:                     }
 6250:                 }
 6251:             }
 6252:         }
 6253:     }
 6254:     return %privileged;
 6255: }
 6256: 
 6257: # -------------------------------------------------------- Get user privileges
 6258: 
 6259: sub rolesinit {
 6260:     my ($domain, $username) = @_;
 6261:     my %userroles = ('user.login.time' => time);
 6262:     my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
 6263: 
 6264:     # firstaccess and timerinterval are related to timed maps/resources. 
 6265:     # also, blocking can be triggered by an activating timer
 6266:     # it's saved in the user's %env.
 6267:     my %firstaccess = &dump('firstaccesstimes', $domain, $username);
 6268:     my %timerinterval = &dump('timerinterval', $domain, $username);
 6269:     my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
 6270:         %timerintchk, %timerintenv);
 6271: 
 6272:     foreach my $key (keys(%firstaccess)) {
 6273:         my ($cid, $rest) = split(/\0/, $key);
 6274:         $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
 6275:     }
 6276: 
 6277:     foreach my $key (keys(%timerinterval)) {
 6278:         my ($cid,$rest) = split(/\0/,$key);
 6279:         $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
 6280:     }
 6281: 
 6282:     my %allroles=();
 6283:     my %allgroups=();
 6284: 
 6285:     for my $area (grep { ! /^rolesdef_/ } keys(%rolesdump)) {
 6286:         my $role = $rolesdump{$area};
 6287:         $area =~ s/\_\w\w$//;
 6288: 
 6289:         my ($trole, $tend, $tstart, $group_privs);
 6290: 
 6291:         if ($role =~ /^cr/) {
 6292:         # Custom role, defined by a user 
 6293:         # e.g., user.role.cr/msu/smith/mynewrole
 6294:             if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
 6295:                 $trole = $1;
 6296:                 ($tend, $tstart) = split('_', $2);
 6297:             } else {
 6298:                 $trole = $role;
 6299:             }
 6300:         } elsif ($role =~ m|^gr/|) {
 6301:         # Role of member in a group, defined within a course/community
 6302:         # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
 6303:             ($trole, $tend, $tstart) = split(/_/, $role);
 6304:             next if $tstart eq '-1';
 6305:             ($trole, $group_privs) = split(/\//, $trole);
 6306:             $group_privs = &unescape($group_privs);
 6307:         } else {
 6308:         # Just a normal role, defined in roles.tab
 6309:             ($trole, $tend, $tstart) = split(/_/,$role);
 6310:         }
 6311: 
 6312:         my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
 6313:                  $username);
 6314:         @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
 6315: 
 6316:         # role expired or not available yet?
 6317:         $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or 
 6318:             ($tstart != 0 && $tstart > $userroles{'user.login.time'});
 6319: 
 6320:         next if $area eq '' or $trole eq '';
 6321: 
 6322:         my $spec = "$trole.$area";
 6323:         my ($tdummy, $tdomain, $trest) = split(/\//, $area);
 6324: 
 6325:         if ($trole =~ /^cr\//) {
 6326:         # Custom role, defined by a user
 6327:             &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
 6328:         } elsif ($trole eq 'gr') {
 6329:         # Role of a member in a group, defined within a course/community
 6330:             &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
 6331:             next;
 6332:         } else {
 6333:         # Normal role, defined in roles.tab
 6334:             &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
 6335:         }
 6336: 
 6337:         my $cid = $tdomain.'_'.$trest;
 6338:         unless ($firstaccchk{$cid}) {
 6339:             if (ref($coursetimerstarts{$cid}) eq 'HASH') {
 6340:                 foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
 6341:                     $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} = 
 6342:                         $coursetimerstarts{$cid}{$item}; 
 6343:                 }
 6344:             }
 6345:             $firstaccchk{$cid} = 1;
 6346:         }
 6347:         unless ($timerintchk{$cid}) {
 6348:             if (ref($coursetimerintervals{$cid}) eq 'HASH') {
 6349:                 foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
 6350:                     $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
 6351:                        $coursetimerintervals{$cid}{$item};
 6352:                 }
 6353:             }
 6354:             $timerintchk{$cid} = 1;
 6355:         }
 6356:     }
 6357: 
 6358:     @userroles{'user.author','user.adv','user.rar'} = &set_userprivs(\%userroles,
 6359:                                                           \%allroles, \%allgroups);
 6360:     $env{'user.adv'} = $userroles{'user.adv'};
 6361:     $env{'user.rar'} = $userroles{'user.rar'};
 6362: 
 6363:     return (\%userroles,\%firstaccenv,\%timerintenv);
 6364: }
 6365: 
 6366: sub set_arearole {
 6367:     my ($trole,$area,$tstart,$tend,$domain,$username,$nolog) = @_;
 6368:     unless ($nolog) {
 6369: # log the associated role with the area
 6370:         &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
 6371:     }
 6372:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
 6373: }
 6374: 
 6375: sub custom_roleprivs {
 6376:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
 6377:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
 6378:     my $homsvr = &homeserver($rauthor,$rdomain);
 6379:     if (&hostname($homsvr) ne '') {
 6380:         my ($rdummy,$roledef)=
 6381:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
 6382:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
 6383:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
 6384:             if (defined($syspriv)) {
 6385:                 if ($trest =~ /^$match_community$/) {
 6386:                     $syspriv =~ s/bre\&S//; 
 6387:                 }
 6388:                 $$allroles{'cm./'}.=':'.$syspriv;
 6389:                 $$allroles{$spec.'./'}.=':'.$syspriv;
 6390:             }
 6391:             if ($tdomain ne '') {
 6392:                 if (defined($dompriv)) {
 6393:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
 6394:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
 6395:                 }
 6396:                 if (($trest ne '') && (defined($coursepriv))) {
 6397:                     if ($trole =~ m{^cr/$tdomain/$tdomain\Q-domainconfig\E/([^/]+)$}) {
 6398:                         my $rolename = $1;
 6399:                         $coursepriv = &course_adhocrole_privs($rolename,$tdomain,$trest,$coursepriv);
 6400:                     }
 6401:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
 6402:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
 6403:                 }
 6404:             }
 6405:         }
 6406:     }
 6407: }
 6408: 
 6409: sub course_adhocrole_privs {
 6410:     my ($rolename,$cdom,$cnum,$coursepriv) = @_;
 6411:     my %overrides = &get('environment',["internal.adhocpriv.$rolename"],$cdom,$cnum);
 6412:     if ($overrides{"internal.adhocpriv.$rolename"}) {
 6413:         my (%currprivs,%storeprivs);
 6414:         foreach my $item (split(/:/,$coursepriv)) {
 6415:             my ($priv,$restrict) = split(/\&/,$item);
 6416:             $currprivs{$priv} = $restrict;
 6417:         }
 6418:         my (%possadd,%possremove,%full);
 6419:         foreach my $item (split(/\:/,$Apache::lonnet::pr{'cr:c'})) {
 6420:             my ($priv,$restrict)=split(/\&/,$item);
 6421:             $full{$priv} = $restrict;
 6422:         }
 6423:         foreach my $item (split(/,/,$overrides{"internal.adhocpriv.$rolename"})) {
 6424:              next if ($item eq '');
 6425:              my ($rule,$rest) = split(/=/,$item);
 6426:              next unless (($rule eq 'off') || ($rule eq 'on'));
 6427:              foreach my $priv (split(/:/,$rest)) {
 6428:                  if ($priv ne '') {
 6429:                      if ($rule eq 'off') {
 6430:                          $possremove{$priv} = 1;
 6431:                      } else {
 6432:                          $possadd{$priv} = 1;
 6433:                      }
 6434:                  }
 6435:              }
 6436:          }
 6437:          foreach my $priv (sort(keys(%full))) {
 6438:              if (exists($currprivs{$priv})) {
 6439:                  unless (exists($possremove{$priv})) {
 6440:                      $storeprivs{$priv} = $currprivs{$priv};
 6441:                  }
 6442:              } elsif (exists($possadd{$priv})) {
 6443:                  $storeprivs{$priv} = $full{$priv};
 6444:              }
 6445:          }
 6446:          $coursepriv = ':'.join(':',map { $_.'&'.$storeprivs{$_}; } sort(keys(%storeprivs)));
 6447:      }
 6448:      return $coursepriv;
 6449: }
 6450: 
 6451: sub group_roleprivs {
 6452:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
 6453:     my $access = 1;
 6454:     my $now = time;
 6455:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
 6456:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
 6457:     if ($access) {
 6458:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
 6459:         $$allgroups{$course}{$group} .=':'.$group_privs;
 6460:     }
 6461: }
 6462: 
 6463: sub standard_roleprivs {
 6464:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
 6465:     if (defined($pr{$trole.':s'})) {
 6466:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
 6467:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
 6468:     }
 6469:     if ($tdomain ne '') {
 6470:         if (defined($pr{$trole.':d'})) {
 6471:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 6472:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 6473:         }
 6474:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
 6475:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
 6476:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
 6477:         }
 6478:     }
 6479: }
 6480: 
 6481: sub set_userprivs {
 6482:     my ($userroles,$allroles,$allgroups,$groups_roles) = @_; 
 6483:     my $author=0;
 6484:     my $adv=0;
 6485:     my $rar=0;
 6486:     my %grouproles = ();
 6487:     if (keys(%{$allgroups}) > 0) {
 6488:         my @groupkeys; 
 6489:         foreach my $role (keys(%{$allroles})) {
 6490:             push(@groupkeys,$role);
 6491:         }
 6492:         if (ref($groups_roles) eq 'HASH') {
 6493:             foreach my $key (keys(%{$groups_roles})) {
 6494:                 unless (grep(/^\Q$key\E$/,@groupkeys)) {
 6495:                     push(@groupkeys,$key);
 6496:                 }
 6497:             }
 6498:         }
 6499:         if (@groupkeys > 0) {
 6500:             foreach my $role (@groupkeys) {
 6501:                 my ($trole,$area,$sec,$extendedarea);
 6502:                 if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
 6503:                     $trole = $1;
 6504:                     $area = $2;
 6505:                     $sec = $3;
 6506:                     $extendedarea = $area.$sec;
 6507:                     if (exists($$allgroups{$area})) {
 6508:                         foreach my $group (keys(%{$$allgroups{$area}})) {
 6509:                             my $spec = $trole.'.'.$extendedarea;
 6510:                             $grouproles{$spec.'.'.$area.'/'.$group} = 
 6511:                                                 $$allgroups{$area}{$group};
 6512:                         }
 6513:                     }
 6514:                 }
 6515:             }
 6516:         }
 6517:     }
 6518:     foreach my $group (keys(%grouproles)) {
 6519:         $$allroles{$group} = $grouproles{$group};
 6520:     }
 6521:     foreach my $role (keys(%{$allroles})) {
 6522:         my %thesepriv;
 6523:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
 6524:         foreach my $item (split(/:/,$$allroles{$role})) {
 6525:             if ($item ne '') {
 6526:                 my ($privilege,$restrictions)=split(/&/,$item);
 6527:                 if ($restrictions eq '') {
 6528:                     $thesepriv{$privilege}='F';
 6529:                 } elsif ($thesepriv{$privilege} ne 'F') {
 6530:                     $thesepriv{$privilege}.=$restrictions;
 6531:                 }
 6532:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
 6533:                 if ($thesepriv{'rar'} eq 'F') { $rar=1; }
 6534:             }
 6535:         }
 6536:         my $thesestr='';
 6537:         foreach my $priv (sort(keys(%thesepriv))) {
 6538: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
 6539: 	}
 6540:         $userroles->{'user.priv.'.$role} = $thesestr;
 6541:     }
 6542:     return ($author,$adv,$rar);
 6543: }
 6544: 
 6545: sub role_status {
 6546:     my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
 6547:     if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
 6548:         my ($one,$two) = split(m{\./},$rolekey,2);
 6549:         (undef,undef,$$role) = split(/\./,$one,3);
 6550:         unless (!defined($$role) || $$role eq '') {
 6551:             $$where = '/'.$two;
 6552:             $$trolecode=$$role.'.'.$$where;
 6553:             ($$tstart,$$tend)=split(/\./,$env{$rolekey});
 6554:             $$tstatus='is';
 6555:             if ($$tstart && $$tstart>$update) {
 6556:                 $$tstatus='future';
 6557:                 if ($$tstart<$now) {
 6558:                     if ($$tstart && $$tstart>$refresh) {
 6559:                         if (($$where ne '') && ($$role ne '')) {
 6560:                             my (%allroles,%allgroups,$group_privs,
 6561:                                 %groups_roles,@rolecodes);
 6562:                             my %userroles = (
 6563:                                 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
 6564:                             );
 6565:                             @rolecodes = ('cm'); 
 6566:                             my $spec=$$role.'.'.$$where;
 6567:                             my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
 6568:                             if ($$role =~ /^cr\//) {
 6569:                                 &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
 6570:                                 push(@rolecodes,'cr');
 6571:                             } elsif ($$role eq 'gr') {
 6572:                                 push(@rolecodes,$$role);
 6573:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
 6574:                                                     $env{'user.name'});
 6575:                                 my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
 6576:                                 (undef,my $group_privs) = split(/\//,$trole);
 6577:                                 $group_privs = &unescape($group_privs);
 6578:                                 &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
 6579:                                 my %course_roles = &get_my_roles($env{'user.name'},$env{'user.domain'},'userroles',['active'],['cc','co','in','ta','ep','ad','st','cr'],[$tdomain],1);
 6580:                                 &get_groups_roles($tdomain,$trest,
 6581:                                                   \%course_roles,\@rolecodes,
 6582:                                                   \%groups_roles);
 6583:                             } else {
 6584:                                 push(@rolecodes,$$role);
 6585:                                 &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
 6586:                             }
 6587:                             my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%allroles,\%allgroups,
 6588:                                                                    \%groups_roles);
 6589:                             &appenv(\%userroles,\@rolecodes);
 6590:                             &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
 6591:                         }
 6592:                     }
 6593:                     $$tstatus = 'is';
 6594:                 }
 6595:             }
 6596:             if ($$tend) {
 6597:                 if ($$tend<$update) {
 6598:                     $$tstatus='expired';
 6599:                 } elsif ($$tend<$now) {
 6600:                     $$tstatus='will_not';
 6601:                 }
 6602:             }
 6603:         }
 6604:     }
 6605: }
 6606: 
 6607: sub get_groups_roles {
 6608:     my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
 6609:     return unless((ref($cdom_courseroles) eq 'HASH') && 
 6610:                   (ref($rolecodes) eq 'ARRAY') && 
 6611:                   (ref($groups_roles) eq 'HASH')); 
 6612:     if (keys(%{$cdom_courseroles}) > 0) {
 6613:         my ($cnum) = ($rest =~ /^($match_courseid)/);
 6614:         if ($cdom ne '' && $cnum ne '') {
 6615:             foreach my $key (keys(%{$cdom_courseroles})) {
 6616:                 if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
 6617:                     my $crsrole = $1;
 6618:                     my $crssec = $2;
 6619:                     if ($crsrole =~ /^cr/) {
 6620:                         unless (grep(/^cr$/,@{$rolecodes})) {
 6621:                             push(@{$rolecodes},'cr');
 6622:                         }
 6623:                     } else {
 6624:                         unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
 6625:                             push(@{$rolecodes},$crsrole);
 6626:                         }
 6627:                     }
 6628:                     my $rolekey = "$crsrole./$cdom/$cnum";
 6629:                     if ($crssec ne '') {
 6630:                         $rolekey .= "/$crssec";
 6631:                     }
 6632:                     $rolekey .= './';
 6633:                     $groups_roles->{$rolekey} = $rolecodes;
 6634:                 }
 6635:             }
 6636:         }
 6637:     }
 6638:     return;
 6639: }
 6640: 
 6641: sub delete_env_groupprivs {
 6642:     my ($where,$courseroles,$possroles) = @_;
 6643:     return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
 6644:     my ($dummy,$udom,$uname,$group) = split(/\//,$where);
 6645:     unless (ref($courseroles->{$udom}) eq 'HASH') {
 6646:         %{$courseroles->{$udom}} =
 6647:             &get_my_roles('','','userroles',['active'],
 6648:                           $possroles,[$udom],1);
 6649:     }
 6650:     if (ref($courseroles->{$udom}) eq 'HASH') {
 6651:         foreach my $item (keys(%{$courseroles->{$udom}})) {
 6652:             my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
 6653:             my $area = '/'.$cdom.'/'.$cnum;
 6654:             my $privkey = "user.priv.$crsrole.$area";
 6655:             if ($crssec ne '') {
 6656:                 $privkey .= '/'.$crssec;
 6657:             }
 6658:             $privkey .= ".$area/$group";
 6659:             &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
 6660:         }
 6661:     }
 6662:     return;
 6663: }
 6664: 
 6665: sub check_adhoc_privs {
 6666:     my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller,$sec) = @_;
 6667:     my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
 6668:     if ($sec) {
 6669:         $cckey .= '/'.$sec;
 6670:     } 
 6671:     my $setprivs;
 6672:     if ($env{$cckey}) {
 6673:         my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
 6674:         &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
 6675:         unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
 6676:             &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
 6677:             $setprivs = 1;
 6678:         }
 6679:     } else {
 6680:         &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
 6681:         $setprivs = 1;
 6682:     }
 6683:     return $setprivs;
 6684: }
 6685: 
 6686: sub set_adhoc_privileges {
 6687: # role can be cc, ca, or cr/<dom>/<dom>-domainconfig/role
 6688:     my ($dcdom,$pickedcourse,$role,$caller,$sec) = @_;
 6689:     my $area = '/'.$dcdom.'/'.$pickedcourse;
 6690:     if ($sec ne '') {
 6691:         $area .= '/'.$sec;
 6692:     }
 6693:     my $spec = $role.'.'.$area;
 6694:     my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
 6695:                                   $env{'user.name'},1);
 6696:     my %rolehash = ();
 6697:     if ($role =~ m{^\Qcr/$dcdom/$dcdom\E\-domainconfig/(\w+)$}) {
 6698:         my $rolename = $1;
 6699:         &custom_roleprivs(\%rolehash,$role,$dcdom,$pickedcourse,$spec,$area);
 6700:         my %domdef = &get_domain_defaults($dcdom);
 6701:         if (ref($domdef{'adhocroles'}) eq 'HASH') {
 6702:             if (ref($domdef{'adhocroles'}{$rolename}) eq 'HASH') {
 6703:                 &appenv({'request.role.desc' => $domdef{'adhocroles'}{$rolename}{'desc'},});
 6704:             }
 6705:         }
 6706:     } else {
 6707:         &standard_roleprivs(\%rolehash,$role,$dcdom,$spec,$pickedcourse,$area);
 6708:     }
 6709:     my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%rolehash);
 6710:     &appenv(\%userroles,[$role,'cm']);
 6711:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
 6712:     unless (($caller eq 'constructaccess' && $env{'request.course.id'}) ||
 6713:             ($caller eq 'tiny')) {
 6714:         &appenv( {'request.role'        => $spec,
 6715:                   'request.role.domain' => $dcdom,
 6716:                   'request.course.sec'  => $sec,
 6717:                  }
 6718:                );
 6719:         my $tadv=0;
 6720:         if (&allowed('adv') eq 'F') { $tadv=1; }
 6721:         &appenv({'request.role.adv'    => $tadv});
 6722:     }
 6723: }
 6724: 
 6725: # --------------------------------------------------------------- get interface
 6726: 
 6727: sub get {
 6728:    my ($namespace,$storearr,$udomain,$uname)=@_;
 6729:    my $items='';
 6730:    foreach my $item (@$storearr) {
 6731:        $items.=&escape($item).'&';
 6732:    }
 6733:    $items=~s/\&$//;
 6734:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 6735:    if (!$uname) { $uname=$env{'user.name'}; }
 6736:    my $uhome=&homeserver($uname,$udomain);
 6737: 
 6738:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
 6739:    my @pairs=split(/\&/,$rep);
 6740:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
 6741:      return @pairs;
 6742:    }
 6743:    my %returnhash=();
 6744:    my $i=0;
 6745:    foreach my $item (@$storearr) {
 6746:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 6747:       $i++;
 6748:    }
 6749:    return %returnhash;
 6750: }
 6751: 
 6752: # --------------------------------------------------------------- del interface
 6753: 
 6754: sub del {
 6755:    my ($namespace,$storearr,$udomain,$uname)=@_;
 6756:    my $items='';
 6757:    foreach my $item (@$storearr) {
 6758:        $items.=&escape($item).'&';
 6759:    }
 6760: 
 6761:    $items=~s/\&$//;
 6762:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 6763:    if (!$uname) { $uname=$env{'user.name'}; }
 6764:    my $uhome=&homeserver($uname,$udomain);
 6765:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
 6766: }
 6767: 
 6768: # -------------------------------------------------------------- dump interface
 6769: 
 6770: sub unserialize {
 6771:     my ($rep, $escapedkeys) = @_;
 6772: 
 6773:     return {} if $rep =~ /^error/;
 6774: 
 6775:     my %returnhash=();
 6776: 	foreach my $item (split(/\&/,$rep)) {
 6777: 	    my ($key, $value) = split(/=/, $item, 2);
 6778: 	    $key = unescape($key) unless $escapedkeys;
 6779: 	    next if $key =~ /^error: 2 /;
 6780: 	    $returnhash{$key} = &thaw_unescape($value);
 6781: 	}
 6782:     #return %returnhash;
 6783:     return \%returnhash;
 6784: }        
 6785: 
 6786: # see Lond::dump_with_regexp
 6787: # if $escapedkeys hash keys won't get unescaped.
 6788: sub dump {
 6789:     my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys)=@_;
 6790:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 6791:     if (!$uname) { $uname=$env{'user.name'}; }
 6792:     my $uhome=&homeserver($uname,$udomain);
 6793: 
 6794:     if ($regexp) {
 6795:         $regexp=&escape($regexp);
 6796:     } else {
 6797:         $regexp='.';
 6798:     }
 6799:     if (grep { $_ eq $uhome } current_machine_ids()) {
 6800:         # user is hosted on this machine
 6801:         my $reply = LONCAPA::Lond::dump_with_regexp(join(":", ($udomain,
 6802:                     $uname, $namespace, $regexp, $range)), $perlvar{'lonVersion'});
 6803:         return %{unserialize($reply, $escapedkeys)};
 6804:     }
 6805:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
 6806:     my @pairs=split(/\&/,$rep);
 6807:     my %returnhash=();
 6808:     if (!($rep =~ /^error/ )) {
 6809: 	foreach my $item (@pairs) {
 6810: 	    my ($key,$value)=split(/=/,$item,2);
 6811:         $key = unescape($key) unless $escapedkeys;
 6812:         #$key = &unescape($key);
 6813: 	    next if ($key =~ /^error: 2 /);
 6814: 	    $returnhash{$key}=&thaw_unescape($value);
 6815: 	}
 6816:     }
 6817:     return %returnhash;
 6818: }
 6819: 
 6820: 
 6821: # --------------------------------------------------------- dumpstore interface
 6822: 
 6823: sub dumpstore {
 6824:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
 6825:    # same as dump but keys must be escaped. They may contain colon separated
 6826:    # lists of values that may themself contain colons (e.g. symbs).
 6827:    return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
 6828: }
 6829: 
 6830: # -------------------------------------------------------------- keys interface
 6831: 
 6832: sub getkeys {
 6833:    my ($namespace,$udomain,$uname)=@_;
 6834:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 6835:    if (!$uname) { $uname=$env{'user.name'}; }
 6836:    my $uhome=&homeserver($uname,$udomain);
 6837:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
 6838:    my @keyarray=();
 6839:    foreach my $key (split(/\&/,$rep)) {
 6840:       next if ($key =~ /^error: 2 /);
 6841:       push(@keyarray,&unescape($key));
 6842:    }
 6843:    return @keyarray;
 6844: }
 6845: 
 6846: # --------------------------------------------------------------- currentdump
 6847: sub currentdump {
 6848:    my ($courseid,$sdom,$sname)=@_;
 6849:    $courseid = $env{'request.course.id'} if (! defined($courseid));
 6850:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
 6851:    $sname    = $env{'user.name'}         if (! defined($sname));
 6852:    my $uhome = &homeserver($sname,$sdom);
 6853:    my $rep;
 6854: 
 6855:    if (grep { $_ eq $uhome } current_machine_ids()) {
 6856:        $rep = LONCAPA::Lond::dump_profile_database(join(":", ($sdom, $sname, 
 6857:                    $courseid)));
 6858:    } else {
 6859:        $rep = reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
 6860:    }
 6861: 
 6862:    return if ($rep =~ /^(error:|no_such_host)/);
 6863:    #
 6864:    my %returnhash=();
 6865:    #
 6866:    if ($rep eq 'unknown_cmd') {
 6867:        # an old lond will not know currentdump
 6868:        # Do a dump and make it look like a currentdump
 6869:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
 6870:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
 6871:        my %hash = @tmp;
 6872:        @tmp=();
 6873:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
 6874:    } else {
 6875:        my @pairs=split(/\&/,$rep);
 6876:        foreach my $pair (@pairs) {
 6877:            my ($key,$value)=split(/=/,$pair,2);
 6878:            my ($symb,$param) = split(/:/,$key);
 6879:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
 6880:                                                         &thaw_unescape($value);
 6881:        }
 6882:    }
 6883:    return %returnhash;
 6884: }
 6885: 
 6886: sub convert_dump_to_currentdump{
 6887:     my %hash = %{shift()};
 6888:     my %returnhash;
 6889:     # Code ripped from lond, essentially.  The only difference
 6890:     # here is the unescaping done by lonnet::dump().  Conceivably
 6891:     # we might run in to problems with parameter names =~ /^v\./
 6892:     while (my ($key,$value) = each(%hash)) {
 6893:         my ($v,$symb,$param) = split(/:/,$key);
 6894: 	$symb  = &unescape($symb);
 6895: 	$param = &unescape($param);
 6896:         next if ($v eq 'version' || $symb eq 'keys');
 6897:         next if (exists($returnhash{$symb}) &&
 6898:                  exists($returnhash{$symb}->{$param}) &&
 6899:                  $returnhash{$symb}->{'v.'.$param} > $v);
 6900:         $returnhash{$symb}->{$param}=$value;
 6901:         $returnhash{$symb}->{'v.'.$param}=$v;
 6902:     }
 6903:     #
 6904:     # Remove all of the keys in the hashes which keep track of
 6905:     # the version of the parameter.
 6906:     while (my ($symb,$param_hash) = each(%returnhash)) {
 6907:         # use a foreach because we are going to delete from the hash.
 6908:         foreach my $key (keys(%$param_hash)) {
 6909:             delete($param_hash->{$key}) if ($key =~ /^v\./);
 6910:         }
 6911:     }
 6912:     return \%returnhash;
 6913: }
 6914: 
 6915: # ------------------------------------------------------ critical inc interface
 6916: 
 6917: sub cinc {
 6918:     return &inc(@_,'critical');
 6919: }
 6920: 
 6921: # --------------------------------------------------------------- inc interface
 6922: 
 6923: sub inc {
 6924:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
 6925:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 6926:     if (!$uname) { $uname=$env{'user.name'}; }
 6927:     my $uhome=&homeserver($uname,$udomain);
 6928:     my $items='';
 6929:     if (! ref($store)) {
 6930:         # got a single value, so use that instead
 6931:         $items = &escape($store).'=&';
 6932:     } elsif (ref($store) eq 'SCALAR') {
 6933:         $items = &escape($$store).'=&';        
 6934:     } elsif (ref($store) eq 'ARRAY') {
 6935:         $items = join('=&',map {&escape($_);} @{$store});
 6936:     } elsif (ref($store) eq 'HASH') {
 6937:         while (my($key,$value) = each(%{$store})) {
 6938:             $items.= &escape($key).'='.&escape($value).'&';
 6939:         }
 6940:     }
 6941:     $items=~s/\&$//;
 6942:     if ($critical) {
 6943: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
 6944:     } else {
 6945: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
 6946:     }
 6947: }
 6948: 
 6949: # --------------------------------------------------------------- put interface
 6950: 
 6951: sub put {
 6952:    my ($namespace,$storehash,$udomain,$uname)=@_;
 6953:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 6954:    if (!$uname) { $uname=$env{'user.name'}; }
 6955:    my $uhome=&homeserver($uname,$udomain);
 6956:    my $items='';
 6957:    foreach my $item (keys(%$storehash)) {
 6958:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 6959:    }
 6960:    $items=~s/\&$//;
 6961:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 6962: }
 6963: 
 6964: # ------------------------------------------------------------ newput interface
 6965: 
 6966: sub newput {
 6967:    my ($namespace,$storehash,$udomain,$uname)=@_;
 6968:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 6969:    if (!$uname) { $uname=$env{'user.name'}; }
 6970:    my $uhome=&homeserver($uname,$udomain);
 6971:    my $items='';
 6972:    foreach my $key (keys(%$storehash)) {
 6973:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 6974:    }
 6975:    $items=~s/\&$//;
 6976:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
 6977: }
 6978: 
 6979: # ---------------------------------------------------------  putstore interface
 6980: 
 6981: sub putstore {
 6982:    my ($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog)=@_;
 6983:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 6984:    if (!$uname) { $uname=$env{'user.name'}; }
 6985:    my $uhome=&homeserver($uname,$udomain);
 6986:    my $items='';
 6987:    foreach my $key (keys(%$storehash)) {
 6988:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
 6989:    }
 6990:    $items=~s/\&$//;
 6991:    my $esc_symb=&escape($symb);
 6992:    my $esc_v=&escape($version);
 6993:    my $reply =
 6994:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
 6995: 	      $uhome);
 6996:    if (($tolog) && ($reply eq 'ok')) {
 6997:        my $namevalue='';
 6998:        foreach my $key (keys(%{$storehash})) {
 6999:            $namevalue.=&escape($key).'='.&freeze_escape($storehash->{$key}).'&';
 7000:        }
 7001:        $namevalue .= 'ip='.&escape($ENV{'REMOTE_ADDR'}).
 7002:                      '&host='.&escape($perlvar{'lonHostID'}).
 7003:                      '&version='.$esc_v.
 7004:                      '&by='.&escape($env{'user.name'}.':'.$env{'user.domain'});
 7005:        &Apache::lonnet::courselog($symb.':'.$uname.':'.$udomain.':PUTSTORE:'.$namevalue);
 7006:    }
 7007:    if ($reply eq 'unknown_cmd') {
 7008:        # gfall back to way things use to be done
 7009:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
 7010: 			    $uname);
 7011:    }
 7012:    return $reply;
 7013: }
 7014: 
 7015: sub old_putstore {
 7016:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
 7017:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 7018:     if (!$uname) { $uname=$env{'user.name'}; }
 7019:     my $uhome=&homeserver($uname,$udomain);
 7020:     my %newstorehash;
 7021:     foreach my $item (keys(%$storehash)) {
 7022: 	my $key = $version.':'.&escape($symb).':'.$item;
 7023: 	$newstorehash{$key} = $storehash->{$item};
 7024:     }
 7025:     my $items='';
 7026:     my %allitems = ();
 7027:     foreach my $item (keys(%newstorehash)) {
 7028: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
 7029: 	    my $key = $1.':keys:'.$2;
 7030: 	    $allitems{$key} .= $3.':';
 7031: 	}
 7032: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
 7033:     }
 7034:     foreach my $item (keys(%allitems)) {
 7035: 	$allitems{$item} =~ s/\:$//;
 7036: 	$items.= $item.'='.$allitems{$item}.'&';
 7037:     }
 7038:     $items=~s/\&$//;
 7039:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 7040: }
 7041: 
 7042: # ------------------------------------------------------ critical put interface
 7043: 
 7044: sub cput {
 7045:    my ($namespace,$storehash,$udomain,$uname)=@_;
 7046:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 7047:    if (!$uname) { $uname=$env{'user.name'}; }
 7048:    my $uhome=&homeserver($uname,$udomain);
 7049:    my $items='';
 7050:    foreach my $item (keys(%$storehash)) {
 7051:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 7052:    }
 7053:    $items=~s/\&$//;
 7054:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
 7055: }
 7056: 
 7057: # -------------------------------------------------------------- eget interface
 7058: 
 7059: sub eget {
 7060:    my ($namespace,$storearr,$udomain,$uname)=@_;
 7061:    my $items='';
 7062:    foreach my $item (@$storearr) {
 7063:        $items.=&escape($item).'&';
 7064:    }
 7065:    $items=~s/\&$//;
 7066:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 7067:    if (!$uname) { $uname=$env{'user.name'}; }
 7068:    my $uhome=&homeserver($uname,$udomain);
 7069:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
 7070:    my @pairs=split(/\&/,$rep);
 7071:    my %returnhash=();
 7072:    my $i=0;
 7073:    foreach my $item (@$storearr) {
 7074:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 7075:       $i++;
 7076:    }
 7077:    return %returnhash;
 7078: }
 7079: 
 7080: # ------------------------------------------------------------ tmpput interface
 7081: sub tmpput {
 7082:     my ($storehash,$server,$context)=@_;
 7083:     my $items='';
 7084:     foreach my $item (keys(%$storehash)) {
 7085: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 7086:     }
 7087:     $items=~s/\&$//;
 7088:     if (defined($context)) {
 7089:         $items .= ':'.&escape($context);
 7090:     }
 7091:     return &reply("tmpput:$items",$server);
 7092: }
 7093: 
 7094: # ------------------------------------------------------------ tmpget interface
 7095: sub tmpget {
 7096:     my ($token,$server)=@_;
 7097:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 7098:     my $rep=&reply("tmpget:$token",$server);
 7099:     my %returnhash;
 7100:     if ($rep =~ /^(con_lost|error|no_such_host)/i) {
 7101:         return %returnhash;
 7102:     }
 7103:     foreach my $item (split(/\&/,$rep)) {
 7104: 	my ($key,$value)=split(/=/,$item);
 7105: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
 7106:     }
 7107:     return %returnhash;
 7108: }
 7109: 
 7110: # ------------------------------------------------------------ tmpdel interface
 7111: sub tmpdel {
 7112:     my ($token,$server)=@_;
 7113:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 7114:     return &reply("tmpdel:$token",$server);
 7115: }
 7116: 
 7117: # ------------------------------------------------------------ get_timebased_id 
 7118: 
 7119: sub get_timebased_id {
 7120:     my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
 7121:         $maxtries) = @_;
 7122:     my ($newid,$error,$dellock);
 7123:     unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {  
 7124:         return ('','ok','invalid call to get suffix');
 7125:     }
 7126: 
 7127: # set defaults for any optional args for which values were not supplied
 7128:     if ($who eq '') {
 7129:         $who = $env{'user.name'}.':'.$env{'user.domain'};
 7130:     }
 7131:     if (!$locktries) {
 7132:         $locktries = 3;
 7133:     }
 7134:     if (!$maxtries) {
 7135:         $maxtries = 10;
 7136:     }
 7137:     
 7138:     if (($cdom eq '') || ($cnum eq '')) {
 7139:         if ($env{'request.course.id'}) {
 7140:             $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 7141:             $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 7142:         }
 7143:         if (($cdom eq '') || ($cnum eq '')) {
 7144:             return ('','ok','call to get suffix not in course context');
 7145:         }
 7146:     }
 7147: 
 7148: # construct locking item
 7149:     my $lockhash = {
 7150:                       $prefix."\0".'locked_'.$keyid => $who,
 7151:                    };
 7152:     my $tries = 0;
 7153: 
 7154: # attempt to get lock on nohist_$namespace file
 7155:     my $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
 7156:     while (($gotlock ne 'ok') && $tries <$locktries) {
 7157:         $tries ++;
 7158:         sleep 1;
 7159:         $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
 7160:     }
 7161: 
 7162: # attempt to get unique identifier, based on current timestamp
 7163:     if ($gotlock eq 'ok') {
 7164:         my %inuse = &Apache::lonnet::dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
 7165:         my $id = time;
 7166:         $newid = $id;
 7167:         if ($idtype eq 'addcode') {
 7168:             $newid .= &sixnum_code();
 7169:         }
 7170:         my $idtries = 0;
 7171:         while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
 7172:             if ($idtype eq 'concat') {
 7173:                 $newid = $id.$idtries;
 7174:             } elsif ($idtype eq 'addcode') {
 7175:                 $newid = $newid.&sixnum_code();
 7176:             } else {
 7177:                 $newid ++;
 7178:             }
 7179:             $idtries ++;
 7180:         }
 7181:         if (!exists($inuse{$prefix."\0".$newid})) {
 7182:             my %new_item =  (
 7183:                               $prefix."\0".$newid => $who,
 7184:                             );
 7185:             my $putresult = &Apache::lonnet::put('nohist_'.$namespace,\%new_item,
 7186:                                                  $cdom,$cnum);
 7187:             if ($putresult ne 'ok') {
 7188:                 undef($newid);
 7189:                 $error = 'error saving new item: '.$putresult;
 7190:             }
 7191:         } else {
 7192:              undef($newid);
 7193:              $error = ('error: no unique suffix available for the new item ');
 7194:         }
 7195: #  remove lock
 7196:         my @del_lock = ($prefix."\0".'locked_'.$keyid);
 7197:         $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
 7198:     } else {
 7199:         $error = "error: could not obtain lockfile\n";
 7200:         $dellock = 'ok';
 7201:         if (($prefix eq 'paste') && ($namespace eq 'courseeditor') && ($keyid eq 'num')) {
 7202:             $dellock = 'nolock';
 7203:         }
 7204:     }
 7205:     return ($newid,$dellock,$error);
 7206: }
 7207: 
 7208: sub sixnum_code {
 7209:     my $code;
 7210:     for (0..6) {
 7211:         $code .= int( rand(9) );
 7212:     }
 7213:     return $code;
 7214: }
 7215: 
 7216: # -------------------------------------------------- portfolio access checking
 7217: 
 7218: sub portfolio_access {
 7219:     my ($requrl,$clientip) = @_;
 7220:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
 7221:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group,$clientip);
 7222:     if ($result) {
 7223:         my %setters;
 7224:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 7225:             my ($startblock,$endblock) =
 7226:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
 7227:             if ($startblock && $endblock) {
 7228:                 return 'B';
 7229:             }
 7230:         } else {
 7231:             my ($startblock,$endblock) =
 7232:                 &Apache::loncommon::blockcheck(\%setters,'port');
 7233:             if ($startblock && $endblock) {
 7234:                 return 'B';
 7235:             }
 7236:         }
 7237:     }
 7238:     if ($result eq 'ok') {
 7239:        return 'F';
 7240:     } elsif ($result =~ /^[^:]+:guest_/) {
 7241:        return 'A';
 7242:     }
 7243:     return '';
 7244: }
 7245: 
 7246: sub get_portfolio_access {
 7247:     my ($udom,$unum,$file_name,$group,$clientip,$access_hash) = @_;
 7248: 
 7249:     if (!ref($access_hash)) {
 7250: 	my $current_perms = &get_portfile_permissions($udom,$unum);
 7251: 	my %access_controls = &get_access_controls($current_perms,$group,
 7252: 						   $file_name);
 7253: 	$access_hash = $access_controls{$file_name};
 7254:     }
 7255: 
 7256:     my ($public,$guest,@domains,@users,@courses,@groups,@ips);
 7257:     my $now = time;
 7258:     if (ref($access_hash) eq 'HASH') {
 7259:         foreach my $key (keys(%{$access_hash})) {
 7260:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
 7261:             if ($start > $now) {
 7262:                 next;
 7263:             }
 7264:             if ($end && $end<$now) {
 7265:                 next;
 7266:             }
 7267:             if ($scope eq 'public') {
 7268:                 $public = $key;
 7269:                 last;
 7270:             } elsif ($scope eq 'guest') {
 7271:                 $guest = $key;
 7272:             } elsif ($scope eq 'domains') {
 7273:                 push(@domains,$key);
 7274:             } elsif ($scope eq 'users') {
 7275:                 push(@users,$key);
 7276:             } elsif ($scope eq 'course') {
 7277:                 push(@courses,$key);
 7278:             } elsif ($scope eq 'group') {
 7279:                 push(@groups,$key);
 7280:             } elsif ($scope eq 'ip') {
 7281:                 push(@ips,$key);
 7282:             }
 7283:         }
 7284:         if ($public) {
 7285:             return 'ok';
 7286:         } elsif (@ips > 0) {
 7287:             my $allowed;
 7288:             foreach my $ipkey (@ips) {
 7289:                 if (ref($access_hash->{$ipkey}{'ip'}) eq 'ARRAY') {
 7290:                     if (&Apache::loncommon::check_ip_acc(join(',',@{$access_hash->{$ipkey}{'ip'}}),$clientip)) {
 7291:                         $allowed = 1;
 7292:                         last; 
 7293:                     }
 7294:                 }
 7295:             }
 7296:             if ($allowed) {
 7297:                 return 'ok';
 7298:             }
 7299:         }
 7300:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 7301:             if ($guest) {
 7302:                 return $guest;
 7303:             }
 7304:         } else {
 7305:             if (@domains > 0) {
 7306:                 foreach my $domkey (@domains) {
 7307:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
 7308:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
 7309:                             return 'ok';
 7310:                         }
 7311:                     }
 7312:                 }
 7313:             }
 7314:             if (@users > 0) {
 7315:                 foreach my $userkey (@users) {
 7316:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
 7317:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
 7318:                             if (ref($item) eq 'HASH') {
 7319:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
 7320:                                     ($item->{'udom'} eq $env{'user.domain'})) {
 7321:                                     return 'ok';
 7322:                                 }
 7323:                             }
 7324:                         }
 7325:                     } 
 7326:                 }
 7327:             }
 7328:             my %roleshash;
 7329:             my @courses_and_groups = @courses;
 7330:             push(@courses_and_groups,@groups); 
 7331:             if (@courses_and_groups > 0) {
 7332:                 my (%allgroups,%allroles); 
 7333:                 my ($start,$end,$role,$sec,$group);
 7334:                 foreach my $envkey (%env) {
 7335:                     if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
 7336:                         my $cid = $2.'_'.$3; 
 7337:                         if ($1 eq 'gr') {
 7338:                             $group = $4;
 7339:                             $allgroups{$cid}{$group} = $env{$envkey};
 7340:                         } else {
 7341:                             if ($4 eq '') {
 7342:                                 $sec = 'none';
 7343:                             } else {
 7344:                                 $sec = $4;
 7345:                             }
 7346:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
 7347:                         }
 7348:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
 7349:                         my $cid = $2.'_'.$3;
 7350:                         if ($4 eq '') {
 7351:                             $sec = 'none';
 7352:                         } else {
 7353:                             $sec = $4;
 7354:                         }
 7355:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
 7356:                     }
 7357:                 }
 7358:                 if (keys(%allroles) == 0) {
 7359:                     return;
 7360:                 }
 7361:                 foreach my $key (@courses_and_groups) {
 7362:                     my %content = %{$$access_hash{$key}};
 7363:                     my $cnum = $content{'number'};
 7364:                     my $cdom = $content{'domain'};
 7365:                     my $cid = $cdom.'_'.$cnum;
 7366:                     if (!exists($allroles{$cid})) {
 7367:                         next;
 7368:                     }    
 7369:                     foreach my $role_id (keys(%{$content{'roles'}})) {
 7370:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
 7371:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
 7372:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
 7373:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
 7374:                         foreach my $role (keys(%{$allroles{$cid}})) {
 7375:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
 7376:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
 7377:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
 7378:                                         if (grep/^all$/,@sections) {
 7379:                                             return 'ok';
 7380:                                         } else {
 7381:                                             if (grep/^$sec$/,@sections) {
 7382:                                                 return 'ok';
 7383:                                             }
 7384:                                         }
 7385:                                     }
 7386:                                 }
 7387:                                 if (keys(%{$allgroups{$cid}}) == 0) {
 7388:                                     if (grep/^none$/,@groups) {
 7389:                                         return 'ok';
 7390:                                     }
 7391:                                 } else {
 7392:                                     if (grep/^all$/,@groups) {
 7393:                                         return 'ok';
 7394:                                     } 
 7395:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
 7396:                                         if (grep/^$group$/,@groups) {
 7397:                                             return 'ok';
 7398:                                         }
 7399:                                     }
 7400:                                 } 
 7401:                             }
 7402:                         }
 7403:                     }
 7404:                 }
 7405:             }
 7406:             if ($guest) {
 7407:                 return $guest;
 7408:             }
 7409:         }
 7410:     }
 7411:     return;
 7412: }
 7413: 
 7414: sub course_group_datechecker {
 7415:     my ($dates,$now,$status) = @_;
 7416:     my ($start,$end) = split(/\./,$dates);
 7417:     if (!$start && !$end) {
 7418:         return 'ok';
 7419:     }
 7420:     if (grep/^active$/,@{$status}) {
 7421:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
 7422:             return 'ok';
 7423:         }
 7424:     }
 7425:     if (grep/^previous$/,@{$status}) {
 7426:         if ($end > $now ) {
 7427:             return 'ok';
 7428:         }
 7429:     }
 7430:     if (grep/^future$/,@{$status}) {
 7431:         if ($start > $now) {
 7432:             return 'ok';
 7433:         }
 7434:     }
 7435:     return; 
 7436: }
 7437: 
 7438: sub parse_portfolio_url {
 7439:     my ($url) = @_;
 7440: 
 7441:     my ($type,$udom,$unum,$group,$file_name);
 7442:     
 7443:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
 7444: 	$type = 1;
 7445:         $udom = $1;
 7446:         $unum = $2;
 7447:         $file_name = $3;
 7448:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
 7449: 	$type = 2;
 7450:         $udom = $1;
 7451:         $unum = $2;
 7452:         $group = $3;
 7453:         $file_name = $3.'/'.$4;
 7454:     }
 7455:     if (wantarray) {
 7456: 	return ($type,$udom,$unum,$file_name,$group);
 7457:     }
 7458:     return $type;
 7459: }
 7460: 
 7461: sub is_portfolio_url {
 7462:     my ($url) = @_;
 7463:     return scalar(&parse_portfolio_url($url));
 7464: }
 7465: 
 7466: sub is_portfolio_file {
 7467:     my ($file) = @_;
 7468:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
 7469:         return 1;
 7470:     }
 7471:     return;
 7472: }
 7473: 
 7474: sub usertools_access {
 7475:     my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
 7476:     my ($access,%tools);
 7477:     if ($context eq '') {
 7478:         $context = 'tools';
 7479:     }
 7480:     if ($context eq 'requestcourses') {
 7481:         %tools = (
 7482:                       official   => 1,
 7483:                       unofficial => 1,
 7484:                       community  => 1,
 7485:                       textbook   => 1,
 7486:                       placement  => 1,
 7487:                       lti        => 1,
 7488:                  );
 7489:     } elsif ($context eq 'requestauthor') {
 7490:         %tools = (
 7491:                       requestauthor => 1,
 7492:                  );
 7493:     } else {
 7494:         %tools = (
 7495:                       aboutme   => 1,
 7496:                       blog      => 1,
 7497:                       webdav    => 1,
 7498:                       portfolio => 1,
 7499:                  );
 7500:     }
 7501:     return if (!defined($tools{$tool}));
 7502: 
 7503:     if (($udom eq '') || ($uname eq '')) {
 7504:         $udom = $env{'user.domain'};
 7505:         $uname = $env{'user.name'};
 7506:     }
 7507: 
 7508:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 7509:         if ($action ne 'reload') {
 7510:             if ($context eq 'requestcourses') {
 7511:                 return $env{'environment.canrequest.'.$tool};
 7512:             } elsif ($context eq 'requestauthor') {
 7513:                 return $env{'environment.canrequest.author'};
 7514:             } else {
 7515:                 return $env{'environment.availabletools.'.$tool};
 7516:             }
 7517:         }
 7518:     }
 7519: 
 7520:     my ($toolstatus,$inststatus,$envkey);
 7521:     if ($context eq 'requestauthor') {
 7522:         $envkey = $context; 
 7523:     } else {
 7524:         $envkey = $context.'.'.$tool;
 7525:     }
 7526: 
 7527:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
 7528:          ($action ne 'reload')) {
 7529:         $toolstatus = $env{'environment.'.$envkey};
 7530:         $inststatus = $env{'environment.inststatus'};
 7531:     } else {
 7532:         if (ref($userenvref) eq 'HASH') {
 7533:             $toolstatus = $userenvref->{$envkey};
 7534:             $inststatus = $userenvref->{'inststatus'};
 7535:         } else {
 7536:             my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
 7537:             $toolstatus = $userenv{$envkey};
 7538:             $inststatus = $userenv{'inststatus'};
 7539:         }
 7540:     }
 7541: 
 7542:     if ($toolstatus ne '') {
 7543:         if ($toolstatus) {
 7544:             $access = 1;
 7545:         } else {
 7546:             $access = 0;
 7547:         }
 7548:         return $access;
 7549:     }
 7550: 
 7551:     my ($is_adv,%domdef);
 7552:     if (ref($is_advref) eq 'HASH') {
 7553:         $is_adv = $is_advref->{'is_adv'};
 7554:     } else {
 7555:         $is_adv = &is_advanced_user($udom,$uname);
 7556:     }
 7557:     if (ref($domdefref) eq 'HASH') {
 7558:         %domdef = %{$domdefref};
 7559:     } else {
 7560:         %domdef = &get_domain_defaults($udom);
 7561:     }
 7562:     if (ref($domdef{$tool}) eq 'HASH') {
 7563:         if ($is_adv) {
 7564:             if ($domdef{$tool}{'_LC_adv'} ne '') {
 7565:                 if ($domdef{$tool}{'_LC_adv'}) { 
 7566:                     $access = 1;
 7567:                 } else {
 7568:                     $access = 0;
 7569:                 }
 7570:                 return $access;
 7571:             }
 7572:         }
 7573:         if ($inststatus ne '') {
 7574:             my ($hasaccess,$hasnoaccess);
 7575:             foreach my $affiliation (split(/:/,$inststatus)) {
 7576:                 if ($domdef{$tool}{$affiliation} ne '') { 
 7577:                     if ($domdef{$tool}{$affiliation}) {
 7578:                         $hasaccess = 1;
 7579:                     } else {
 7580:                         $hasnoaccess = 1;
 7581:                     }
 7582:                 }
 7583:             }
 7584:             if ($hasaccess || $hasnoaccess) {
 7585:                 if ($hasaccess) {
 7586:                     $access = 1;
 7587:                 } elsif ($hasnoaccess) {
 7588:                     $access = 0; 
 7589:                 }
 7590:                 return $access;
 7591:             }
 7592:         } else {
 7593:             if ($domdef{$tool}{'default'} ne '') {
 7594:                 if ($domdef{$tool}{'default'}) {
 7595:                     $access = 1;
 7596:                 } elsif ($domdef{$tool}{'default'} == 0) {
 7597:                     $access = 0;
 7598:                 }
 7599:                 return $access;
 7600:             }
 7601:         }
 7602:     } else {
 7603:         if (($context eq 'tools') && ($tool ne 'webdav')) {
 7604:             $access = 1;
 7605:         } else {
 7606:             $access = 0;
 7607:         }
 7608:         return $access;
 7609:     }
 7610: }
 7611: 
 7612: sub is_course_owner {
 7613:     my ($cdom,$cnum,$udom,$uname) = @_;
 7614:     if (($udom eq '') || ($uname eq '')) {
 7615:         $udom = $env{'user.domain'};
 7616:         $uname = $env{'user.name'};
 7617:     }
 7618:     unless (($udom eq '') || ($uname eq '')) {
 7619:         if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
 7620:             if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
 7621:                 return 1;
 7622:             } else {
 7623:                 my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
 7624:                 if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
 7625:                     return 1;
 7626:                 }
 7627:             }
 7628:         }
 7629:     }
 7630:     return;
 7631: }
 7632: 
 7633: sub is_advanced_user {
 7634:     my ($udom,$uname) = @_;
 7635:     if ($udom ne '' && $uname ne '') {
 7636:         if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 7637:             if (wantarray) {
 7638:                 return ($env{'user.adv'},$env{'user.author'});
 7639:             } else {
 7640:                 return $env{'user.adv'};
 7641:             }
 7642:         }
 7643:     }
 7644:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
 7645:     my %allroles;
 7646:     my ($is_adv,$is_author);
 7647:     foreach my $role (keys(%roleshash)) {
 7648:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
 7649:         my $area = '/'.$tdomain.'/'.$trest;
 7650:         if ($sec ne '') {
 7651:             $area .= '/'.$sec;
 7652:         }
 7653:         if (($area ne '') && ($trole ne '')) {
 7654:             my $spec=$trole.'.'.$area;
 7655:             if ($trole =~ /^cr\//) {
 7656:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
 7657:             } elsif ($trole ne 'gr') {
 7658:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
 7659:             }
 7660:             if ($trole eq 'au') {
 7661:                 $is_author = 1;
 7662:             }
 7663:         }
 7664:     }
 7665:     foreach my $role (keys(%allroles)) {
 7666:         last if ($is_adv);
 7667:         foreach my $item (split(/:/,$allroles{$role})) {
 7668:             if ($item ne '') {
 7669:                 my ($privilege,$restrictions)=split(/&/,$item);
 7670:                 if ($privilege eq 'adv') {
 7671:                     $is_adv = 1;
 7672:                     last;
 7673:                 }
 7674:             }
 7675:         }
 7676:     }
 7677:     if (wantarray) {
 7678:         return ($is_adv,$is_author);
 7679:     }
 7680:     return $is_adv;
 7681: }
 7682: 
 7683: sub check_can_request {
 7684:     my ($dom,$can_request,$request_domains,$uname,$udom) = @_;
 7685:     my $canreq = 0;
 7686:     if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
 7687:         $uname = $env{'user.name'};
 7688:         $udom = $env{'user.domain'};
 7689:     }
 7690:     my ($types,$typename) = &Apache::loncommon::course_types();
 7691:     my @options = ('approval','validate','autolimit');
 7692:     my $optregex = join('|',@options);
 7693:     if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
 7694:         foreach my $type (@{$types}) {
 7695:             if (&usertools_access($uname,$udom,$type,undef,
 7696:                                   'requestcourses')) {
 7697:                 $canreq ++;
 7698:                 if (ref($request_domains) eq 'HASH') {
 7699:                     push(@{$request_domains->{$type}},$udom);
 7700:                 }
 7701:                 if ($dom eq $udom) {
 7702:                     $can_request->{$type} = 1;
 7703:                 }
 7704:             }
 7705:             if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '') &&
 7706:                 ($env{'environment.reqcrsotherdom.'.$type} ne '')) {
 7707:                 my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
 7708:                 if (@curr > 0) {
 7709:                     foreach my $item (@curr) {
 7710:                         if (ref($request_domains) eq 'HASH') {
 7711:                             my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
 7712:                             if ($otherdom ne '') {
 7713:                                 if (ref($request_domains->{$type}) eq 'ARRAY') {
 7714:                                     unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
 7715:                                         push(@{$request_domains->{$type}},$otherdom);
 7716:                                     }
 7717:                                 } else {
 7718:                                     push(@{$request_domains->{$type}},$otherdom);
 7719:                                 }
 7720:                             }
 7721:                         }
 7722:                     }
 7723:                     unless ($dom eq $env{'user.domain'}) {
 7724:                         $canreq ++;
 7725:                         if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
 7726:                             $can_request->{$type} = 1;
 7727:                         }
 7728:                     }
 7729:                 }
 7730:             }
 7731:         }
 7732:     }
 7733:     return $canreq;
 7734: }
 7735: 
 7736: # ---------------------------------------------- Custom access rule evaluation
 7737: 
 7738: sub customaccess {
 7739:     my ($priv,$uri)=@_;
 7740:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
 7741:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
 7742:     $udom = &LONCAPA::clean_domain($udom);
 7743:     $ucrs = &LONCAPA::clean_username($ucrs);
 7744:     my $access=0;
 7745:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
 7746: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
 7747: 	if ($type eq 'user') {
 7748: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
 7749: 		my ($tdom,$tuname)=split(m{/},$scope);
 7750: 		if ($tdom) {
 7751: 		    if ($tdom ne $env{'user.domain'}) { next; }
 7752: 		}
 7753: 		if ($tuname) {
 7754: 		    if ($tuname ne $env{'user.name'}) { next; }
 7755: 		}
 7756: 		$access=($effect eq 'allow');
 7757: 		last;
 7758: 	    }
 7759: 	} else {
 7760: 	    if ($role) {
 7761: 		if ($role ne $urole) { next; }
 7762: 	    }
 7763: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
 7764: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
 7765: 		if ($tdom) {
 7766: 		    if ($tdom ne $udom) { next; }
 7767: 		}
 7768: 		if ($tcrs) {
 7769: 		    if ($tcrs ne $ucrs) { next; }
 7770: 		}
 7771: 		if ($tsec) {
 7772: 		    if ($tsec ne $usec) { next; }
 7773: 		}
 7774: 		$access=($effect eq 'allow');
 7775: 		last;
 7776: 	    }
 7777: 	    if ($realm eq '' && $role eq '') {
 7778: 		$access=($effect eq 'allow');
 7779: 	    }
 7780: 	}
 7781:     }
 7782:     return $access;
 7783: }
 7784: 
 7785: # ------------------------------------------------- Check for a user privilege
 7786: 
 7787: sub allowed {
 7788:     my ($priv,$uri,$symb,$role,$clientip,$noblockcheck)=@_;
 7789:     my $ver_orguri=$uri;
 7790:     $uri=&deversion($uri);
 7791:     my $orguri=$uri;
 7792:     $uri=&declutter($uri);
 7793: 
 7794:     if ($priv eq 'evb') {
 7795: # Evade communication block restrictions for specified role in a course
 7796:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
 7797:             return $1;
 7798:         } else {
 7799:             return;
 7800:         }
 7801:     }
 7802: 
 7803:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
 7804: # Free bre access to adm and meta resources
 7805:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard|ext\.tool)$})) 
 7806: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
 7807: 	&& ($priv eq 'bre')) {
 7808: 	return 'F';
 7809:     }
 7810: 
 7811: # Free bre access to user's own portfolio contents
 7812:     my ($space,$domain,$name,@dir)=split('/',$uri);
 7813:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
 7814: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
 7815:         my %setters;
 7816:         my ($startblock,$endblock) = 
 7817:             &Apache::loncommon::blockcheck(\%setters,'port');
 7818:         if ($startblock && $endblock) {
 7819:             return 'B';
 7820:         } else {
 7821:             return 'F';
 7822:         }
 7823:     }
 7824: 
 7825: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
 7826:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
 7827:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
 7828:         if (exists($env{'request.course.id'})) {
 7829:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 7830:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 7831:             if (($domain eq $cdom) && ($name eq $cnum)) {
 7832:                 my $courseprivid=$env{'request.course.id'};
 7833:                 $courseprivid=~s/\_/\//;
 7834:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
 7835:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
 7836:                     return $1; 
 7837:                 } else {
 7838:                     if ($env{'request.course.sec'}) {
 7839:                         $courseprivid.='/'.$env{'request.course.sec'};
 7840:                     }
 7841:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
 7842:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
 7843:                         return $2;
 7844:                     }
 7845:                 }
 7846:             }
 7847:         }
 7848:     }
 7849: 
 7850: # Free bre to public access
 7851: 
 7852:     if ($priv eq 'bre') {
 7853:         my $copyright;
 7854:         unless ($uri =~ /ext\.tool/) {
 7855:             $copyright=&metadata($uri,'copyright');
 7856:         }
 7857: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
 7858:            return 'F'; 
 7859:         }
 7860:         if ($copyright eq 'priv') {
 7861:             $uri=~/([^\/]+)\/([^\/]+)\//;
 7862: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
 7863: 		return '';
 7864:             }
 7865:         }
 7866:         if ($copyright eq 'domain') {
 7867:             $uri=~/([^\/]+)\/([^\/]+)\//;
 7868: 	    unless (($env{'user.domain'} eq $1) ||
 7869:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
 7870: 		return '';
 7871:             }
 7872:         }
 7873:         if ($env{'request.role'}=~ /li\.\//) {
 7874:             # Library role, so allow browsing of resources in this domain.
 7875:             return 'F';
 7876:         }
 7877:         if ($copyright eq 'custom') {
 7878: 	    unless (&customaccess($priv,$uri)) { return ''; }
 7879:         }
 7880:     }
 7881:     # Domain coordinator is trying to create a course
 7882:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
 7883:         # uri is the requested domain in this case.
 7884:         # comparison to 'request.role.domain' shows if the user has selected
 7885:         # a role of dc for the domain in question.
 7886:         return 'F' if ($uri eq $env{'request.role.domain'});
 7887:     }
 7888: 
 7889:     my $thisallowed='';
 7890:     my $statecond=0;
 7891:     my $courseprivid='';
 7892: 
 7893:     my $ownaccess;
 7894:     # Community Coordinator or Assistant Co-author browsing resource space.
 7895:     if (($priv eq 'bro') && ($env{'user.author'})) {
 7896:         if ($uri eq '') {
 7897:             $ownaccess = 1;
 7898:         } else {
 7899:             if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
 7900:                 my $udom = $env{'user.domain'};
 7901:                 my $uname = $env{'user.name'};
 7902:                 if ($uri =~ m{^\Q$udom\E/?$}) {
 7903:                     $ownaccess = 1;
 7904:                 } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
 7905:                     unless ($uri =~ m{\.\./}) {
 7906:                         $ownaccess = 1;
 7907:                     }
 7908:                 } elsif (($udom ne 'public') && ($uname ne 'public')) {
 7909:                     my $now = time;
 7910:                     if ($uri =~ m{^([^/]+)/?$}) {
 7911:                         my $adom = $1;
 7912:                         foreach my $key (keys(%env)) {
 7913:                             if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
 7914:                                 my ($start,$end) = split('.',$env{$key});
 7915:                                 if (($now >= $start) && (!$end || $end < $now)) {
 7916:                                     $ownaccess = 1;
 7917:                                     last;
 7918:                                 }
 7919:                             }
 7920:                         }
 7921:                     } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
 7922:                         my $adom = $1;
 7923:                         my $aname = $2;
 7924:                         foreach my $role ('ca','aa') { 
 7925:                             if ($env{"user.role.$role./$adom/$aname"}) {
 7926:                                 my ($start,$end) =
 7927:                                     split('.',$env{"user.role.$role./$adom/$aname"});
 7928:                                 if (($now >= $start) && (!$end || $end < $now)) {
 7929:                                     $ownaccess = 1;
 7930:                                     last;
 7931:                                 }
 7932:                             }
 7933:                         }
 7934:                     }
 7935:                 }
 7936:             }
 7937:         }
 7938:     }
 7939: 
 7940: # Course
 7941: 
 7942:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
 7943:         unless (($priv eq 'bro') && (!$ownaccess)) {
 7944:             $thisallowed.=$1;
 7945:         }
 7946:     }
 7947: 
 7948: # Domain
 7949: 
 7950:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
 7951:        =~/\Q$priv\E\&([^\:]*)/) {
 7952:         unless (($priv eq 'bro') && (!$ownaccess)) {
 7953:             $thisallowed.=$1;
 7954:         }
 7955:     }
 7956: 
 7957: # User who is not author or co-author might still be able to edit
 7958: # resource of an author in the domain (e.g., if Domain Coordinator).
 7959:     if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
 7960:         (&allowed('mdc',$env{'request.course.id'}))) {
 7961:         if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
 7962:             $thisallowed.=$1;
 7963:         }
 7964:     }
 7965: 
 7966: # Course: uri itself is a course
 7967:     my $courseuri=$uri;
 7968:     $courseuri=~s/\_(\d)/\/$1/;
 7969:     $courseuri=~s/^([^\/])/\/$1/;
 7970: 
 7971:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
 7972:        =~/\Q$priv\E\&([^\:]*)/) {
 7973:         unless (($priv eq 'bro') && (!$ownaccess)) {
 7974:             $thisallowed.=$1;
 7975:         }
 7976:     }
 7977: 
 7978: # URI is an uploaded document for this course, default permissions don't matter
 7979: # not allowing 'edit' access (editupload) to uploaded course docs
 7980:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
 7981: 	$thisallowed='';
 7982:         my ($match)=&is_on_map($uri);
 7983:         if ($match) {
 7984:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
 7985:                   =~/\Q$priv\E\&([^\:]*)/) {
 7986:                 my $value = $1;
 7987:                 my $deeplinkblock = &deeplink_check($priv,$symb,$uri);
 7988:                 if ($deeplinkblock) {
 7989:                     $thisallowed='D';
 7990:                 } elsif ($noblockcheck) {
 7991:                     $thisallowed.=$value;
 7992:                 } else {
 7993:                     my @blockers = &has_comm_blocking($priv,$symb,$uri);
 7994:                     if (@blockers > 0) {
 7995:                         $thisallowed = 'B';
 7996:                     } else {
 7997:                         $thisallowed.=$value;
 7998:                     }
 7999:                 }
 8000:             }
 8001:         } else {
 8002:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
 8003:             if ($refuri) {
 8004:                 if ($refuri =~ m|^/adm/|) {
 8005:                     $thisallowed='F';
 8006:                 } else {
 8007:                     $refuri=&declutter($refuri);
 8008:                     my ($match) = &is_on_map($refuri);
 8009:                     if ($match) {
 8010:                         my $deeplinkblock = &deeplink_check($priv,$symb,$refuri);
 8011:                         if ($deeplinkblock) {
 8012:                             $thisallowed='D';
 8013:                         } elsif ($noblockcheck) {
 8014:                             $thisallowed='F';
 8015:                         } else {
 8016:                             my @blockers = &has_comm_blocking($priv,$symb,$refuri);
 8017:                             if (@blockers > 0) {
 8018:                                 $thisallowed = 'B';
 8019:                             } else {
 8020:                                 $thisallowed='F';
 8021:                             }
 8022:                         }
 8023:                     }
 8024:                 }
 8025:             }
 8026:         }
 8027:     }
 8028: 
 8029:     if ($priv eq 'bre'
 8030: 	&& $thisallowed ne 'F' 
 8031: 	&& $thisallowed ne '2'
 8032: 	&& &is_portfolio_url($uri)) {
 8033: 	$thisallowed = &portfolio_access($uri,$clientip);
 8034:     }
 8035: 
 8036: # Full access at system, domain or course-wide level? Exit.
 8037:     if ($thisallowed=~/F/) {
 8038: 	return 'F';
 8039:     }
 8040: 
 8041: # If this is generating or modifying users, exit with special codes
 8042: 
 8043:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
 8044: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
 8045: 	    my ($audom,$auname)=split('/',$uri);
 8046: # no author name given, so this just checks on the general right to make a co-author in this domain
 8047: 	    unless ($auname) { return $thisallowed; }
 8048: # an author name is given, so we are about to actually make a co-author for a certain account
 8049: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
 8050: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
 8051: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
 8052: 	}
 8053: 	return $thisallowed;
 8054:     }
 8055: #
 8056: # Gathered so far: system, domain and course wide privileges
 8057: #
 8058: # Course: See if uri or referer is an individual resource that is part of 
 8059: # the course
 8060: 
 8061:     if ($env{'request.course.id'}) {
 8062: 
 8063:        $courseprivid=$env{'request.course.id'};
 8064:        if ($env{'request.course.sec'}) {
 8065:           $courseprivid.='/'.$env{'request.course.sec'};
 8066:        }
 8067:        $courseprivid=~s/\_/\//;
 8068:        my $checkreferer=1;
 8069:        my ($match,$cond)=&is_on_map($uri);
 8070:        if ($match) {
 8071:            $statecond=$cond;
 8072:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 8073:                =~/\Q$priv\E\&([^\:]*)/) {
 8074:                my $value = $1;
 8075:                if ($priv eq 'bre') {
 8076:                    if ($noblockcheck) {
 8077:                        $thisallowed.=$value;
 8078:                    } else {
 8079:                        my @blockers = &has_comm_blocking($priv,$symb,$uri);
 8080:                        if (@blockers > 0) {
 8081:                            $thisallowed = 'B';
 8082:                        } else {
 8083:                            $thisallowed.=$value;
 8084:                        }
 8085:                    }
 8086:                } else {
 8087:                    $thisallowed.=$value;
 8088:                }
 8089:                $checkreferer=0;
 8090:            }
 8091:        }
 8092:        
 8093:        if ($checkreferer) {
 8094: 	  my $refuri=$env{'httpref.'.$orguri};
 8095:             unless ($refuri) {
 8096:                 foreach my $key (keys(%env)) {
 8097: 		    if ($key=~/^httpref\..*\*/) {
 8098: 			my $pattern=$key;
 8099:                         $pattern=~s/^httpref\.\/res\///;
 8100:                         $pattern=~s/\*/\[\^\/\]\+/g;
 8101:                         $pattern=~s/\//\\\//g;
 8102:                         if ($orguri=~/$pattern/) {
 8103: 			    $refuri=$env{$key};
 8104:                         }
 8105:                     }
 8106:                 }
 8107:             }
 8108: 
 8109:          if ($refuri) { 
 8110: 	  $refuri=&declutter($refuri);
 8111:           my ($match,$cond)=&is_on_map($refuri);
 8112:             if ($match) {
 8113:               my $refstatecond=$cond;
 8114:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 8115:                   =~/\Q$priv\E\&([^\:]*)/) {
 8116:                   my $value = $1;
 8117:                   if ($priv eq 'bre') {
 8118:                       my $deeplinkblock = &deeplink_check($priv,$symb,$refuri);
 8119:                       if ($deeplinkblock) {
 8120:                           $thisallowed = 'D';
 8121:                       } elsif ($noblockcheck) {
 8122:                           $thisallowed.=$value;
 8123:                       } else {
 8124:                           my @blockers = &has_comm_blocking($priv,$symb,$refuri);
 8125:                           if (@blockers > 0) {
 8126:                               $thisallowed = 'B';
 8127:                           } else {
 8128:                               $thisallowed.=$value;
 8129:                           }
 8130:                       }
 8131:                   } else {
 8132:                       $thisallowed.=$value;
 8133:                   }
 8134:                   $uri=$refuri;
 8135:                   $statecond=$refstatecond;
 8136:               }
 8137:           }
 8138:         }
 8139:        }
 8140:    }
 8141: 
 8142: #
 8143: # Gathered now: all privileges that could apply, and condition number
 8144: # 
 8145: #
 8146: # Full or no access?
 8147: #
 8148: 
 8149:     if ($thisallowed=~/F/) {
 8150: 	return 'F';
 8151:     }
 8152: 
 8153:     unless ($thisallowed) {
 8154:         return '';
 8155:     }
 8156: 
 8157: # Restrictions exist, deal with them
 8158: #
 8159: #   C:according to course preferences
 8160: #   R:according to resource settings
 8161: #   L:unless locked
 8162: #   X:according to user session state
 8163: #
 8164: 
 8165: # Possibly locked functionality, check all courses
 8166: # Locks might take effect only after 10 minutes cache expiration for other
 8167: # courses, and 2 minutes for current course
 8168: 
 8169:     my $envkey;
 8170:     if ($thisallowed=~/L/) {
 8171:         foreach $envkey (keys(%env)) {
 8172:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
 8173:                my $courseid=$2;
 8174:                my $roleid=$1.'.'.$2;
 8175:                $courseid=~s/^\///;
 8176:                my $expiretime=600;
 8177:                if ($env{'request.role'} eq $roleid) {
 8178: 		  $expiretime=120;
 8179:                }
 8180: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
 8181:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
 8182:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
 8183: 		   &coursedescription($courseid,{'freshen_cache' => 1});
 8184:                }
 8185:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
 8186:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
 8187: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
 8188:                        &log($env{'user.domain'},$env{'user.name'},
 8189:                             $env{'user.home'},
 8190:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
 8191:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 8192:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 8193: 		       return '';
 8194:                    }
 8195:                }
 8196:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
 8197:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
 8198: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
 8199:                        &log($env{'user.domain'},$env{'user.name'},
 8200:                             $env{'user.home'},
 8201:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
 8202:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 8203:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 8204: 		       return '';
 8205:                    }
 8206:                }
 8207: 	   }
 8208:        }
 8209:     }
 8210:    
 8211: #
 8212: # Rest of the restrictions depend on selected course
 8213: #
 8214: 
 8215:     unless ($env{'request.course.id'}) {
 8216: 	if ($thisallowed eq 'A') {
 8217: 	    return 'A';
 8218:         } elsif ($thisallowed eq 'B') {
 8219:             return 'B';
 8220: 	} else {
 8221: 	    return '1';
 8222: 	}
 8223:     }
 8224: 
 8225: #
 8226: # Now user is definitely in a course
 8227: #
 8228: 
 8229: 
 8230: # Course preferences
 8231: 
 8232:    if ($thisallowed=~/C/) {
 8233:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 8234:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
 8235:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
 8236: 	   =~/\Q$rolecode\E/) {
 8237: 	   if (($priv ne 'pch') && ($priv ne 'plc') && ($priv ne 'pac')) {
 8238: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 8239: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
 8240: 			$env{'request.course.id'});
 8241: 	   }
 8242:            return '';
 8243:        }
 8244: 
 8245:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
 8246: 	   =~/\Q$unamedom\E/) {
 8247: 	   if (($priv ne 'pch') && ($priv ne 'plc') && ($priv ne 'pac')) {
 8248: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
 8249: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
 8250: 			$env{'request.course.id'});
 8251: 	   }
 8252:            return '';
 8253:        }
 8254:    }
 8255: 
 8256: # Resource preferences
 8257: 
 8258:    if ($thisallowed=~/R/) {
 8259:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 8260:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
 8261: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
 8262: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 8263: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
 8264: 	   }
 8265: 	   return '';
 8266:        }
 8267:    }
 8268: 
 8269: # Restricted by state or randomout?
 8270: 
 8271:    if ($thisallowed=~/X/) {
 8272:       if ($env{'acc.randomout'}) {
 8273: 	 if (!$symb) { $symb=&symbread($uri,1); }
 8274:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
 8275:             return ''; 
 8276:          }
 8277:       }
 8278:       if (&condval($statecond)) {
 8279: 	 return '2';
 8280:       } else {
 8281:          return '';
 8282:       }
 8283:    }
 8284: 
 8285:     if ($thisallowed eq 'A') {
 8286: 	return 'A';
 8287:     } elsif ($thisallowed eq 'B') {
 8288:         return 'B';
 8289:     } elsif ($thisallowed eq 'D') {
 8290:         return 'D';
 8291:     }
 8292:    return 'F';
 8293: }
 8294: 
 8295: # ------------------------------------------- Check construction space access
 8296: 
 8297: sub constructaccess {
 8298:     my ($url,$setpriv)=@_;
 8299: 
 8300: # We do not allow editing of previous versions of files
 8301:     if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
 8302: 
 8303: # Get username and domain from URL
 8304:     my ($ownername,$ownerdomain,$ownerhome);
 8305: 
 8306:     ($ownerdomain,$ownername) =
 8307:         ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)(?:/daxepage|/daxeopen)?/priv/($match_domain)/($match_username)(?:/|$)});
 8308: 
 8309: # The URL does not really point to any authorspace, forget it
 8310:     unless (($ownername) && ($ownerdomain)) { return ''; }
 8311: 
 8312: # Now we need to see if the user has access to the authorspace of
 8313: # $ownername at $ownerdomain
 8314: 
 8315:     if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
 8316: # Real author for this?
 8317:        $ownerhome = $env{'user.home'};
 8318:        if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
 8319:           return ($ownername,$ownerdomain,$ownerhome);
 8320:        }
 8321:     } else {
 8322: # Co-author for this?
 8323:         if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
 8324:             exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
 8325:             $ownerhome = &homeserver($ownername,$ownerdomain);
 8326:             return ($ownername,$ownerdomain,$ownerhome);
 8327:         }
 8328:         if ($env{'request.course.id'}) {
 8329:             if (($ownername eq $env{'course.'.$env{'request.course.id'}.'.num'}) &&
 8330:                 ($ownerdomain eq $env{'course.'.$env{'request.course.id'}.'.domain'})) {
 8331:                 if (&allowed('mdc',$env{'request.course.id'})) {
 8332:                     $ownerhome = $env{'course.'.$env{'request.course.id'}.'.home'};
 8333:                     return ($ownername,$ownerdomain,$ownerhome);
 8334:                 }
 8335:             }
 8336:         }
 8337:     }
 8338: 
 8339: # We don't have any access right now. If we are not possibly going to do anything about this,
 8340: # we might as well leave
 8341:    unless ($setpriv) { return ''; }
 8342: 
 8343: # Backdoor access?
 8344:     my $allowed=&allowed('eco',$ownerdomain);
 8345: # Nope
 8346:     unless ($allowed) { return ''; }
 8347: # Looks like we may have access, but could be locked by the owner of the construction space
 8348:     if ($allowed eq 'U') {
 8349:         my %blocked=&get('environment',['domcoord.author'],
 8350:                          $ownerdomain,$ownername);
 8351: # Is blocked by owner
 8352:         if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
 8353:     }
 8354:     if (($allowed eq 'F') || ($allowed eq 'U')) {
 8355: # Grant temporary access
 8356:         my $then=$env{'user.login.time'};
 8357:         my $update=$env{'user.update.time'};
 8358:         if (!$update) { $update = $then; }
 8359:         my $refresh=$env{'user.refresh.time'};
 8360:         if (!$refresh) { $refresh = $update; }
 8361:         my $now = time;
 8362:         &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
 8363:                            $now,'ca','constructaccess');
 8364:         $ownerhome = &homeserver($ownername,$ownerdomain);
 8365:         return($ownername,$ownerdomain,$ownerhome);
 8366:     }
 8367: # No business here
 8368:     return '';
 8369: }
 8370: 
 8371: # ----------------------------------------------------------- Content Blocking
 8372: 
 8373: {
 8374: # Caches for faster Course Contents display where content blocking
 8375: # is in operation (i.e., interval param set) for timed quiz.
 8376: #
 8377: # User for whom data are being temporarily cached.
 8378: my $cacheduser='';
 8379: # Cached blockers for this user (a hash of blocking items). 
 8380: my %cachedblockers=();
 8381: # When the data were last cached.
 8382: my $cachedlast='';
 8383: 
 8384: sub load_all_blockers {
 8385:     my ($uname,$udom,$blocks)=@_;
 8386:     if (($uname ne '') && ($udom ne '')) { 
 8387:         if (($cacheduser eq $uname.':'.$udom) &&
 8388:             (abs($cachedlast-time)<5)) {
 8389:             return;
 8390:         }
 8391:     }
 8392:     $cachedlast=time;
 8393:     $cacheduser=$uname.':'.$udom;
 8394:     %cachedblockers = &get_commblock_resources($blocks);
 8395: }
 8396: 
 8397: sub get_comm_blocks {
 8398:     my ($cdom,$cnum) = @_;
 8399:     if ($cdom eq '' || $cnum eq '') {
 8400:         return unless ($env{'request.course.id'});
 8401:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 8402:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 8403:     }
 8404:     my %commblocks;
 8405:     my $hashid=$cdom.'_'.$cnum;
 8406:     my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
 8407:     if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
 8408:         %commblocks = %{$blocksref};
 8409:     } else {
 8410:         %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
 8411:         my $cachetime = 600;
 8412:         &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
 8413:     }
 8414:     return %commblocks;
 8415: }
 8416: 
 8417: sub get_commblock_resources {
 8418:     my ($blocks) = @_;
 8419:     my %blockers = ();
 8420:     return %blockers unless ($env{'request.course.id'});
 8421:     return %blockers if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
 8422:     my %commblocks;
 8423:     if (ref($blocks) eq 'HASH') {
 8424:         %commblocks = %{$blocks};
 8425:     } else {
 8426:         %commblocks = &get_comm_blocks();
 8427:     }
 8428:     return %blockers unless (keys(%commblocks) > 0); 
 8429:     my $navmap = Apache::lonnavmaps::navmap->new();
 8430:     return %blockers unless (ref($navmap));
 8431:     my $now = time;
 8432:     foreach my $block (keys(%commblocks)) {
 8433:         if ($block =~ /^(\d+)____(\d+)$/) {
 8434:             my ($start,$end) = ($1,$2);
 8435:             if ($start <= $now && $end >= $now) {
 8436:                 if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
 8437:                     if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
 8438:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
 8439:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
 8440:                                 $blockers{$block}{maps} = $commblocks{$block}{'blocks'}{'docs'}{'maps'}; 
 8441:                             }
 8442:                         }
 8443:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
 8444:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
 8445:                                 $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
 8446:                             }
 8447:                         }
 8448:                     }
 8449:                 }
 8450:             }
 8451:         } elsif ($block =~ /^firstaccess____(.+)$/) {
 8452:             my $item = $1;
 8453:             my @to_test;
 8454:             if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
 8455:                 if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
 8456:                     my @interval;
 8457:                     my $type = 'map';
 8458:                     if ($item eq 'course') {
 8459:                         $type = 'course';
 8460:                         @interval=&EXT("resource.0.interval");
 8461:                     } else {
 8462:                         if ($item =~ /___\d+___/) {
 8463:                             $type = 'resource';
 8464:                             @interval=&EXT("resource.0.interval",$item);
 8465:                             if (ref($navmap)) {                        
 8466:                                 my $res = $navmap->getBySymb($item); 
 8467:                                 push(@to_test,$res);
 8468:                             }
 8469:                         } else {
 8470:                             my $mapsymb = &symbread($item,1);
 8471:                             if ($mapsymb) {
 8472:                                 if (ref($navmap)) {
 8473:                                     my $mapres = $navmap->getBySymb($mapsymb);
 8474:                                     @to_test = $mapres->retrieveResources($mapres,undef,0,0,0,1);
 8475:                                     foreach my $res (@to_test) {
 8476:                                         my $symb = $res->symb();
 8477:                                         next if ($symb eq $mapsymb);
 8478:                                         if ($symb ne '') {
 8479:                                             @interval=&EXT("resource.0.interval",$symb);
 8480:                                             if ($interval[1] eq 'map') {
 8481:                                                 last;
 8482:                                             }
 8483:                                         }
 8484:                                     }
 8485:                                 }
 8486:                             }
 8487:                         }
 8488:                     }
 8489:                     if ($interval[0] =~ /^(\d+)/) {
 8490:                         my $timelimit = $1; 
 8491:                         my $first_access;
 8492:                         if ($type eq 'resource') {
 8493:                             $first_access=&get_first_access($interval[1],$item);
 8494:                         } elsif ($type eq 'map') {
 8495:                             $first_access=&get_first_access($interval[1],undef,$item);
 8496:                         } else {
 8497:                             $first_access=&get_first_access($interval[1]);
 8498:                         }
 8499:                         if ($first_access) {
 8500:                             my $timesup = $first_access+$timelimit;
 8501:                             if ($timesup > $now) {
 8502:                                 my $activeblock;
 8503:                                 foreach my $res (@to_test) {
 8504:                                     if ($res->answerable()) {
 8505:                                         $activeblock = 1;
 8506:                                         last;
 8507:                                     }
 8508:                                 }
 8509:                                 if ($activeblock) {
 8510:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
 8511:                                          if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
 8512:                                              $blockers{$block}{'maps'} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
 8513:                                          }
 8514:                                     }
 8515:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
 8516:                                         if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
 8517:                                             $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
 8518:                                         }
 8519:                                     }
 8520:                                 }
 8521:                             }
 8522:                         }
 8523:                     }
 8524:                 }
 8525:             }
 8526:         }
 8527:     }
 8528:     return %blockers;
 8529: }
 8530: 
 8531: sub has_comm_blocking {
 8532:     my ($priv,$symb,$uri,$blocks) = @_;
 8533:     my @blockers;
 8534:     return unless ($env{'request.course.id'});
 8535:     return unless ($priv eq 'bre');
 8536:     return if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
 8537:     return if ($env{'request.state'} eq 'construct');
 8538:     &load_all_blockers($env{'user.name'},$env{'user.domain'},$blocks);
 8539:     return unless (keys(%cachedblockers) > 0);
 8540:     my (%possibles,@symbs);
 8541:     if (!$symb) {
 8542:         $symb = &symbread($uri,1,1,1,\%possibles);
 8543:     }
 8544:     if ($symb) {
 8545:         @symbs = ($symb);
 8546:     } elsif (keys(%possibles)) { 
 8547:         @symbs = keys(%possibles);
 8548:     }
 8549:     my $noblock;
 8550:     foreach my $symb (@symbs) {
 8551:         last if ($noblock);
 8552:         my ($map,$resid,$resurl)=&decode_symb($symb);
 8553:         foreach my $block (keys(%cachedblockers)) {
 8554:             if ($block =~ /^firstaccess____(.+)$/) {
 8555:                 my $item = $1;
 8556:                 if (($item eq $map) || ($item eq $symb)) {
 8557:                     $noblock = 1;
 8558:                     last;
 8559:                 }
 8560:             }
 8561:             if (ref($cachedblockers{$block}) eq 'HASH') {
 8562:                 if (ref($cachedblockers{$block}{'resources'}) eq 'HASH') {
 8563:                     if ($cachedblockers{$block}{'resources'}{$symb}) {
 8564:                         unless (grep(/^\Q$block\E$/,@blockers)) {
 8565:                             push(@blockers,$block);
 8566:                         }
 8567:                     }
 8568:                 }
 8569:             }
 8570:             if (ref($cachedblockers{$block}{'maps'}) eq 'HASH') {
 8571:                 if ($cachedblockers{$block}{'maps'}{$map}) {
 8572:                     unless (grep(/^\Q$block\E$/,@blockers)) {
 8573:                         push(@blockers,$block);
 8574:                     }
 8575:                 }
 8576:             }
 8577:         }
 8578:     }
 8579:     return if ($noblock);
 8580:     return @blockers;
 8581: }
 8582: }
 8583: 
 8584: sub deeplink_check {
 8585:     my ($priv,$symb,$uri) = @_;
 8586:     return unless ($env{'request.course.id'});
 8587:     return unless ($priv eq 'bre');
 8588:     return if ($env{'request.state'} eq 'construct');
 8589:     return if ($env{'request.role.adv'});
 8590:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 8591:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 8592:     my (%possibles,@symbs);
 8593:     if (!$symb) {
 8594:         $symb = &symbread($uri,1,1,1,\%possibles);
 8595:     }
 8596:     if ($symb) {
 8597:         @symbs = ($symb);
 8598:     } elsif (keys(%possibles)) {
 8599:         @symbs = keys(%possibles);
 8600:     }
 8601: 
 8602:     my ($login,$switchrole,$allow);
 8603:     if ($env{'request.deeplink.login'} =~ m{^\Q/tiny/$cdom/\E(\w+)$}) {
 8604:         my $key = $1;
 8605:         my $tinyurl;
 8606:         my ($result,$cached)=&Apache::lonnet::is_cached_new('tiny',$cdom."\0".$key);
 8607:         if (defined($cached)) {
 8608:              $tinyurl = $result;
 8609:         } else {
 8610:              my $configuname = &Apache::lonnet::get_domainconfiguser($cdom);
 8611:              my %currtiny = &Apache::lonnet::get('tiny',[$key],$cdom,$configuname);
 8612:              if ($currtiny{$key} ne '') {
 8613:                  $tinyurl = $currtiny{$key};
 8614:                  &Apache::lonnet::do_cache_new('tiny',$cdom."\0".$key,$currtiny{$key},600);
 8615:              }
 8616:         }
 8617:         if ($tinyurl ne '') {
 8618:             my ($cnumreq,$posslogin) = split(/\&/,$tinyurl);
 8619:             if ($cnumreq eq $cnum) {
 8620:                 $login = $posslogin;
 8621:             } else {
 8622:                 $switchrole = 1;
 8623:             }
 8624:         }
 8625:     }
 8626:     foreach my $symb (@symbs) {
 8627:         last if ($allow);
 8628:         my $deeplink = &EXT("resource.0.deeplink",$symb);
 8629:         if ($deeplink eq '') {
 8630:             $allow = 1;
 8631:         } else {
 8632:             my ($listed,$scope,$access) = split(/,/,$deeplink);
 8633:             if ($access eq 'any') {
 8634:                 $allow = 1;
 8635:             } elsif ($login) {
 8636:                 if ($access eq 'only') {
 8637:                     if ($scope eq 'res') {
 8638:                         if ($symb eq $login) {
 8639:                             $allow = 1;
 8640:                         }
 8641:                     } elsif ($scope eq 'map') {
 8642: #FIXME Compare map for $env{'request.deeplink.login'} with map for $symb
 8643:                     } elsif ($scope eq 'rec') {
 8644: #FIXME Recurse up for $env{'request.deeplink.login'} with map for $symb
 8645:                     }
 8646:                 } else {
 8647:                     my ($acctype,$item) = split(/:/,$access);
 8648:                     if (($acctype eq 'lti') && ($env{'user.linkprotector'})) {
 8649:                         if (grep(/^\Q$item\E$/,split(/,/,$env{'user.linkprotector'}))) {
 8650:                             my %tinyurls = &get('tiny',[$symb],$cdom,$cnum);
 8651:                             if (grep(/\Q$tinyurls{$symb}\E$/,split(/,/,$env{'user.linkproturis'}))) {
 8652:                                 $allow = 1;
 8653:                             }
 8654:                         }
 8655:                     } elsif (($acctype eq 'key') && ($env{'user.deeplinkkey'})) {
 8656:                         if (grep(/^\Q$item\E$/,split(/,/,$env{'user.deeplinkkey'}))) {
 8657:                             my %tinyurls = &get('tiny',[$symb],$cdom,$cnum);
 8658:                             if (grep(/\Q$tinyurls{$symb}\E$/,split(/,/,$env{'user.keyedlinkuri'}))) {
 8659:                                 $allow = 1;
 8660:                             }
 8661:                         }
 8662:                     }
 8663:                 }
 8664:             }
 8665:         }
 8666:     }
 8667:     return if ($allow);
 8668:     return 1;
 8669: }
 8670: 
 8671: # -------------------------------- Deversion and split uri into path an filename   
 8672: 
 8673: #
 8674: #   Removes the version from a URI and
 8675: #   splits it in to its filename and path to the filename.
 8676: #   Seems like File::Basename could have done this more clearly.
 8677: #   Parameters:
 8678: #      $uri   - input URI
 8679: #   Returns:
 8680: #     Two element list consisting of 
 8681: #     $pathname  - the URI up to and excluding the trailing /
 8682: #     $filename  - The part of the URI following the last /
 8683: #  NOTE:
 8684: #    Another realization of this is simply:
 8685: #    use File::Basename;
 8686: #    ...
 8687: #    $uri = shift;
 8688: #    $filename = basename($uri);
 8689: #    $path     = dirname($uri);
 8690: #    return ($filename, $path);
 8691: #
 8692: #     The implementation below is probably faster however.
 8693: #
 8694: sub split_uri_for_cond {
 8695:     my $uri=&deversion(&declutter(shift));
 8696:     my @uriparts=split(/\//,$uri);
 8697:     my $filename=pop(@uriparts);
 8698:     my $pathname=join('/',@uriparts);
 8699:     return ($pathname,$filename);
 8700: }
 8701: # --------------------------------------------------- Is a resource on the map?
 8702: 
 8703: sub is_on_map {
 8704:     my ($pathname,$filename) = &split_uri_for_cond(shift);
 8705:     #Trying to find the conditional for the file
 8706:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
 8707: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
 8708:     if ($match) {
 8709: 	return (1,$1);
 8710:     } else {
 8711: 	return (0,0);
 8712:     }
 8713: }
 8714: 
 8715: # --------------------------------------------------------- Get symb from alias
 8716: 
 8717: sub get_symb_from_alias {
 8718:     my $symb=shift;
 8719:     my ($map,$resid,$url)=&decode_symb($symb);
 8720: # Already is a symb
 8721:     if ($url) { return $symb; }
 8722: # Must be an alias
 8723:     my $aliassymb='';
 8724:     my %bighash;
 8725:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 8726:                             &GDBM_READER(),0640)) {
 8727:         my $rid=$bighash{'mapalias_'.$symb};
 8728: 	if ($rid) {
 8729: 	    my ($mapid,$resid)=split(/\./,$rid);
 8730: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
 8731: 				    $resid,$bighash{'src_'.$rid});
 8732: 	}
 8733:         untie %bighash;
 8734:     }
 8735:     return $aliassymb;
 8736: }
 8737: 
 8738: # ----------------------------------------------------------------- Define Role
 8739: 
 8740: sub definerole {
 8741:   if (allowed('mcr','/')) {
 8742:     my ($rolename,$sysrole,$domrole,$courole,$uname,$udom)=@_;
 8743:     foreach my $role (split(':',$sysrole)) {
 8744: 	my ($crole,$cqual)=split(/\&/,$role);
 8745:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
 8746:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
 8747: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 8748:                return "refused:s:$crole&$cqual"; 
 8749:             }
 8750:         }
 8751:     }
 8752:     foreach my $role (split(':',$domrole)) {
 8753: 	my ($crole,$cqual)=split(/\&/,$role);
 8754:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
 8755:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
 8756: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
 8757:                return "refused:d:$crole&$cqual"; 
 8758:             }
 8759:         }
 8760:     }
 8761:     foreach my $role (split(':',$courole)) {
 8762: 	my ($crole,$cqual)=split(/\&/,$role);
 8763:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
 8764:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
 8765: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 8766:                return "refused:c:$crole&$cqual"; 
 8767:             }
 8768:         }
 8769:     }
 8770:     my $uhome;
 8771:     if (($uname ne '') && ($udom ne '')) {
 8772:         $uhome = &homeserver($uname,$udom);
 8773:         return $uhome if ($uhome eq 'no_host');
 8774:     } else {
 8775:         $uname = $env{'user.name'};
 8776:         $udom = $env{'user.domain'};
 8777:         $uhome = $env{'user.home'};
 8778:     }
 8779:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
 8780:                 "$udom:$uname:rolesdef_$rolename=".
 8781:                 escape($sysrole.'_'.$domrole.'_'.$courole);
 8782:     return reply($command,$uhome);
 8783:   } else {
 8784:     return 'refused';
 8785:   }
 8786: }
 8787: 
 8788: # ---------------- Make a metadata query against the network of library servers
 8789: 
 8790: sub metadata_query {
 8791:     my ($query,$custom,$customshow,$server_array,$domains_hash)=@_;
 8792:     my %rhash;
 8793:     my %libserv = &all_library();
 8794:     my @server_list = (defined($server_array) ? @$server_array
 8795:                                               : keys(%libserv) );
 8796:     for my $server (@server_list) {
 8797:         my $domains = ''; 
 8798:         if (ref($domains_hash) eq 'HASH') {
 8799:             $domains = $domains_hash->{$server}; 
 8800:         }
 8801: 	unless ($custom or $customshow) {
 8802: 	    my $reply=&reply("querysend:".&escape($query).':::'.&escape($domains),$server);
 8803: 	    $rhash{$server}=$reply;
 8804: 	}
 8805: 	else {
 8806: 	    my $reply=&reply("querysend:".&escape($query).':'.
 8807: 			     &escape($custom).':'.&escape($customshow).':'.&escape($domains),
 8808: 			     $server);
 8809: 	    $rhash{$server}=$reply;
 8810: 	}
 8811:     }
 8812:     return \%rhash;
 8813: }
 8814: 
 8815: # ----------------------------------------- Send log queries and wait for reply
 8816: 
 8817: sub log_query {
 8818:     my ($uname,$udom,$query,%filters)=@_;
 8819:     my $uhome=&homeserver($uname,$udom);
 8820:     if ($uhome eq 'no_host') { return 'error: no_host'; }
 8821:     my $uhost=&hostname($uhome);
 8822:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
 8823:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
 8824:                        $uhome);
 8825:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
 8826:     return get_query_reply($queryid);
 8827: }
 8828: 
 8829: # -------------------------- Update MySQL table for portfolio file
 8830: 
 8831: sub update_portfolio_table {
 8832:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
 8833:     if ($group ne '') {
 8834:         $file_name =~s /^\Q$group\E//;
 8835:     }
 8836:     my $homeserver = &homeserver($uname,$udom);
 8837:     my $queryid=
 8838:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
 8839:                ':'.&escape($file_name).':'.$action,$homeserver);
 8840:     my $reply = &get_query_reply($queryid);
 8841:     return $reply;
 8842: }
 8843: 
 8844: # -------------------------- Update MySQL allusers table
 8845: 
 8846: sub update_allusers_table {
 8847:     my ($uname,$udom,$names) = @_;
 8848:     my $homeserver = &homeserver($uname,$udom);
 8849:     my $queryid=
 8850:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
 8851:                'lastname='.&escape($names->{'lastname'}).'%%'.
 8852:                'firstname='.&escape($names->{'firstname'}).'%%'.
 8853:                'middlename='.&escape($names->{'middlename'}).'%%'.
 8854:                'generation='.&escape($names->{'generation'}).'%%'.
 8855:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
 8856:                'id='.&escape($names->{'id'}),$homeserver);
 8857:     return;
 8858: }
 8859: 
 8860: # ------- Request retrieval of institutional classlists for course(s)
 8861: 
 8862: sub fetch_enrollment_query {
 8863:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
 8864:     my ($homeserver,$sleep,$loopmax);
 8865:     my $maxtries = 1;
 8866:     if ($context eq 'automated') {
 8867:         $homeserver = $perlvar{'lonHostID'};
 8868:         $sleep = 2;
 8869:         $loopmax = 100;
 8870:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
 8871:     } else {
 8872:         $homeserver = &homeserver($cnum,$dom);
 8873:     }
 8874:     my $host=&hostname($homeserver);
 8875:     my $cmd = '';
 8876:     foreach my $affiliate (keys(%{$affiliatesref})) {
 8877:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
 8878:     }
 8879:     $cmd =~ s/%%$//;
 8880:     $cmd = &escape($cmd);
 8881:     my $query = 'fetchenrollment';
 8882:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
 8883:     unless ($queryid=~/^\Q$host\E\_/) { 
 8884:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
 8885:         return 'error: '.$queryid;
 8886:     }
 8887:     my $reply = &get_query_reply($queryid,$sleep,$loopmax);
 8888:     my $tries = 1;
 8889:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 8890:         $reply = &get_query_reply($queryid,$sleep,$loopmax);
 8891:         $tries ++;
 8892:     }
 8893:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 8894:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 8895:     } else {
 8896:         my @responses = split(/:/,$reply);
 8897:         if (grep { $_ eq $homeserver } &current_machine_ids()) {
 8898:             foreach my $line (@responses) {
 8899:                 my ($key,$value) = split(/=/,$line,2);
 8900:                 $$replyref{$key} = $value;
 8901:             }
 8902:         } else {
 8903:             my $pathname = LONCAPA::tempdir();
 8904:             foreach my $line (@responses) {
 8905:                 my ($key,$value) = split(/=/,$line);
 8906:                 $$replyref{$key} = $value;
 8907:                 if ($value > 0) {
 8908:                     foreach my $item (@{$$affiliatesref{$key}}) {
 8909:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
 8910:                         my $destname = $pathname.'/'.$filename;
 8911:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
 8912:                         if ($xml_classlist =~ /^error/) {
 8913:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
 8914:                         } else {
 8915:                             if ( open(FILE,">",$destname) ) {
 8916:                                 print FILE &unescape($xml_classlist);
 8917:                                 close(FILE);
 8918:                             } else {
 8919:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
 8920:                             }
 8921:                         }
 8922:                     }
 8923:                 }
 8924:             }
 8925:         }
 8926:         return 'ok';
 8927:     }
 8928:     return 'error';
 8929: }
 8930: 
 8931: sub get_query_reply {
 8932:     my ($queryid,$sleep,$loopmax) = @_;;
 8933:     if (($sleep eq '') || ($sleep !~ /^\d+\.?\d*$/)) {
 8934:         $sleep = 0.2;
 8935:     }
 8936:     if (($loopmax eq '') || ($loopmax =~ /\D/)) {
 8937:         $loopmax = 100;
 8938:     }
 8939:     my $replyfile=LONCAPA::tempdir().$queryid;
 8940:     my $reply='';
 8941:     for (1..$loopmax) {
 8942: 	sleep($sleep);
 8943:         if (-e $replyfile.'.end') {
 8944: 	    if (open(my $fh,"<",$replyfile)) {
 8945: 		$reply = join('',<$fh>);
 8946: 		close($fh);
 8947: 	   } else { return 'error: reply_file_error'; }
 8948:            return &unescape($reply);
 8949: 	}
 8950:     }
 8951:     return 'timeout:'.$queryid;
 8952: }
 8953: 
 8954: sub courselog_query {
 8955: #
 8956: # possible filters:
 8957: # url: url or symb
 8958: # username
 8959: # domain
 8960: # action: view, submit, grade
 8961: # start: timestamp
 8962: # end: timestamp
 8963: #
 8964:     my (%filters)=@_;
 8965:     unless ($env{'request.course.id'}) { return 'no_course'; }
 8966:     if ($filters{'url'}) {
 8967: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
 8968:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
 8969:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
 8970:     }
 8971:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 8972:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 8973:     return &log_query($cname,$cdom,'courselog',%filters);
 8974: }
 8975: 
 8976: sub userlog_query {
 8977: #
 8978: # possible filters:
 8979: # action: log check role
 8980: # start: timestamp
 8981: # end: timestamp
 8982: #
 8983:     my ($uname,$udom,%filters)=@_;
 8984:     return &log_query($uname,$udom,'userlog',%filters);
 8985: }
 8986: 
 8987: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
 8988: 
 8989: sub auto_run {
 8990:     my ($cnum,$cdom) = @_;
 8991:     my $response = 0;
 8992:     my $settings;
 8993:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
 8994:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
 8995:         $settings = $domconfig{'autoenroll'};
 8996:         if ($settings->{'run'} eq '1') {
 8997:             $response = 1;
 8998:         }
 8999:     } else {
 9000:         my $homeserver;
 9001:         if (&is_course($cdom,$cnum)) {
 9002:             $homeserver = &homeserver($cnum,$cdom);
 9003:         } else {
 9004:             $homeserver = &domain($cdom,'primary');
 9005:         }
 9006:         if ($homeserver ne 'no_host') {
 9007:             $response = &reply('autorun:'.$cdom,$homeserver);
 9008:         }
 9009:     }
 9010:     return $response;
 9011: }
 9012: 
 9013: sub auto_get_sections {
 9014:     my ($cnum,$cdom,$inst_coursecode) = @_;
 9015:     my $homeserver;
 9016:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) { 
 9017:         $homeserver = &homeserver($cnum,$cdom);
 9018:     }
 9019:     if (!defined($homeserver)) { 
 9020:         if ($cdom =~ /^$match_domain$/) {
 9021:             $homeserver = &domain($cdom,'primary');
 9022:         }
 9023:     }
 9024:     my @secs;
 9025:     if (defined($homeserver)) {
 9026:         my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
 9027:         unless ($response eq 'refused') {
 9028:             @secs = split(/:/,$response);
 9029:         }
 9030:     }
 9031:     return @secs;
 9032: }
 9033: 
 9034: sub auto_new_course {
 9035:     my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
 9036:     my $homeserver = &homeserver($cnum,$cdom);
 9037:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
 9038:     return $response;
 9039: }
 9040: 
 9041: sub auto_validate_courseID {
 9042:     my ($cnum,$cdom,$inst_course_id) = @_;
 9043:     my $homeserver = &homeserver($cnum,$cdom);
 9044:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
 9045:     return $response;
 9046: }
 9047: 
 9048: sub auto_validate_instcode {
 9049:     my ($cnum,$cdom,$instcode,$owner) = @_;
 9050:     my ($homeserver,$response);
 9051:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
 9052:         $homeserver = &homeserver($cnum,$cdom);
 9053:     }
 9054:     if (!defined($homeserver)) {
 9055:         if ($cdom =~ /^$match_domain$/) {
 9056:             $homeserver = &domain($cdom,'primary');
 9057:         }
 9058:     }
 9059:     $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
 9060:                         &escape($instcode).':'.&escape($owner),$homeserver));
 9061:     my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
 9062:     return ($outcome,$description,$defaultcredits);
 9063: }
 9064: 
 9065: sub auto_create_password {
 9066:     my ($cnum,$cdom,$authparam,$udom) = @_;
 9067:     my ($homeserver,$response);
 9068:     my $create_passwd = 0;
 9069:     my $authchk = '';
 9070:     if ($udom =~ /^$match_domain$/) {
 9071:         $homeserver = &domain($udom,'primary');
 9072:     }
 9073:     if ($homeserver eq '') {
 9074:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
 9075:             $homeserver = &homeserver($cnum,$cdom);
 9076:         }
 9077:     }
 9078:     if ($homeserver eq '') {
 9079:         $authchk = 'nodomain';
 9080:     } else {
 9081:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
 9082:         if ($response eq 'refused') {
 9083:             $authchk = 'refused';
 9084:         } else {
 9085:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
 9086:         }
 9087:     }
 9088:     return ($authparam,$create_passwd,$authchk);
 9089: }
 9090: 
 9091: sub auto_photo_permission {
 9092:     my ($cnum,$cdom,$students) = @_;
 9093:     my $homeserver = &homeserver($cnum,$cdom);
 9094:     my ($outcome,$perm_reqd,$conditions) = 
 9095: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
 9096:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 9097: 	return (undef,undef);
 9098:     }
 9099:     return ($outcome,$perm_reqd,$conditions);
 9100: }
 9101: 
 9102: sub auto_checkphotos {
 9103:     my ($uname,$udom,$pid) = @_;
 9104:     my $homeserver = &homeserver($uname,$udom);
 9105:     my ($result,$resulttype);
 9106:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
 9107: 				   &escape($uname).':'.&escape($pid),
 9108: 				   $homeserver));
 9109:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 9110: 	return (undef,undef);
 9111:     }
 9112:     if ($outcome) {
 9113:         ($result,$resulttype) = split(/:/,$outcome);
 9114:     } 
 9115:     return ($result,$resulttype);
 9116: }
 9117: 
 9118: sub auto_photochoice {
 9119:     my ($cnum,$cdom) = @_;
 9120:     my $homeserver = &homeserver($cnum,$cdom);
 9121:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
 9122: 						       &escape($cdom),
 9123: 						       $homeserver)));
 9124:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 9125: 	return (undef,undef);
 9126:     }
 9127:     return ($update,$comment);
 9128: }
 9129: 
 9130: sub auto_photoupdate {
 9131:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
 9132:     my $homeserver = &homeserver($cnum,$dom);
 9133:     my $host=&hostname($homeserver);
 9134:     my $cmd = '';
 9135:     my $maxtries = 1;
 9136:     foreach my $affiliate (keys(%{$affiliatesref})) {
 9137:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
 9138:     }
 9139:     $cmd =~ s/%%$//;
 9140:     $cmd = &escape($cmd);
 9141:     my $query = 'institutionalphotos';
 9142:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
 9143:     unless ($queryid=~/^\Q$host\E\_/) {
 9144:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
 9145:         return 'error: '.$queryid;
 9146:     }
 9147:     my $reply = &get_query_reply($queryid);
 9148:     my $tries = 1;
 9149:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 9150:         $reply = &get_query_reply($queryid);
 9151:         $tries ++;
 9152:     }
 9153:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 9154:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 9155:     } else {
 9156:         my @responses = split(/:/,$reply);
 9157:         my $outcome = shift(@responses); 
 9158:         foreach my $item (@responses) {
 9159:             my ($key,$value) = split(/=/,$item);
 9160:             $$photo{$key} = $value;
 9161:         }
 9162:         return $outcome;
 9163:     }
 9164:     return 'error';
 9165: }
 9166: 
 9167: sub auto_instcode_format {
 9168:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
 9169: 	$cat_order) = @_;
 9170:     my $courses = '';
 9171:     my @homeservers;
 9172:     if ($caller eq 'global') {
 9173: 	my %servers = &get_servers($codedom,'library');
 9174: 	foreach my $tryserver (keys(%servers)) {
 9175: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 9176: 		push(@homeservers,$tryserver);
 9177: 	    }
 9178:         }
 9179:     } elsif ($caller eq 'requests') {
 9180:         if ($codedom =~ /^$match_domain$/) {
 9181:             my $chome = &domain($codedom,'primary');
 9182:             unless ($chome eq 'no_host') {
 9183:                 push(@homeservers,$chome);
 9184:             }
 9185:         }
 9186:     } else {
 9187:         push(@homeservers,&homeserver($caller,$codedom));
 9188:     }
 9189:     foreach my $code (keys(%{$instcodes})) {
 9190:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
 9191:     }
 9192:     chop($courses);
 9193:     my $ok_response = 0;
 9194:     my $response;
 9195:     while (@homeservers > 0 && $ok_response == 0) {
 9196:         my $server = shift(@homeservers); 
 9197:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
 9198:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
 9199:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
 9200: 		split(/:/,$response);
 9201:             %{$codes} = (%{$codes},&str2hash($codes_str));
 9202:             push(@{$codetitles},&str2array($codetitles_str));
 9203:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
 9204:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
 9205:             $ok_response = 1;
 9206:         }
 9207:     }
 9208:     if ($ok_response) {
 9209:         return 'ok';
 9210:     } else {
 9211:         return $response;
 9212:     }
 9213: }
 9214: 
 9215: sub auto_instcode_defaults {
 9216:     my ($domain,$returnhash,$code_order) = @_;
 9217:     my @homeservers;
 9218: 
 9219:     my %servers = &get_servers($domain,'library');
 9220:     foreach my $tryserver (keys(%servers)) {
 9221: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 9222: 	    push(@homeservers,$tryserver);
 9223: 	}
 9224:     }
 9225: 
 9226:     my $response;
 9227:     foreach my $server (@homeservers) {
 9228:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
 9229:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
 9230: 	
 9231: 	foreach my $pair (split(/\&/,$response)) {
 9232: 	    my ($name,$value)=split(/\=/,$pair);
 9233: 	    if ($name eq 'code_order') {
 9234: 		@{$code_order} = split(/\&/,&unescape($value));
 9235: 	    } else {
 9236: 		$returnhash->{&unescape($name)}=&unescape($value);
 9237: 	    }
 9238: 	}
 9239: 	return 'ok';
 9240:     }
 9241: 
 9242:     return $response;
 9243: }
 9244: 
 9245: sub auto_possible_instcodes {
 9246:     my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
 9247:     unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') && 
 9248:             (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
 9249:         return;
 9250:     }
 9251:     my (@homeservers,$uhome);
 9252:     if (defined(&domain($domain,'primary'))) {
 9253:         $uhome=&domain($domain,'primary');
 9254:         push(@homeservers,&domain($domain,'primary'));
 9255:     } else {
 9256:         my %servers = &get_servers($domain,'library');
 9257:         foreach my $tryserver (keys(%servers)) {
 9258:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 9259:                 push(@homeservers,$tryserver);
 9260:             }
 9261:         }
 9262:     }
 9263:     my $response;
 9264:     foreach my $server (@homeservers) {
 9265:         $response=&reply('autopossibleinstcodes:'.$domain,$server);
 9266:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
 9267:         my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) = 
 9268:             split(':',$response);
 9269:         @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
 9270:         @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
 9271:         foreach my $item (split('&',$cat_title)) {   
 9272:             my ($name,$value)=split('=',$item);
 9273:             $cat_titles->{&unescape($name)}=&thaw_unescape($value);
 9274:         }
 9275:         foreach my $item (split('&',$cat_order)) {
 9276:             my ($name,$value)=split('=',$item);
 9277:             $cat_orders->{&unescape($name)}=&thaw_unescape($value);
 9278:         }
 9279:         return 'ok';
 9280:     }
 9281:     return $response;
 9282: }
 9283: 
 9284: sub auto_courserequest_checks {
 9285:     my ($dom) = @_;
 9286:     my ($homeserver,%validations);
 9287:     if ($dom =~ /^$match_domain$/) {
 9288:         $homeserver = &domain($dom,'primary');
 9289:     }
 9290:     unless ($homeserver eq 'no_host') {
 9291:         my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
 9292:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
 9293:             my @items = split(/&/,$response);
 9294:             foreach my $item (@items) {
 9295:                 my ($key,$value) = split('=',$item);
 9296:                 $validations{&unescape($key)} = &thaw_unescape($value);
 9297:             }
 9298:         }
 9299:     }
 9300:     return %validations; 
 9301: }
 9302: 
 9303: sub auto_courserequest_validation {
 9304:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist,$custominfo) = @_;
 9305:     my ($homeserver,$response);
 9306:     if ($dom =~ /^$match_domain$/) {
 9307:         $homeserver = &domain($dom,'primary');
 9308:     }
 9309:     unless ($homeserver eq 'no_host') {
 9310:         my $customdata;
 9311:         if (ref($custominfo) eq 'HASH') {
 9312:             $customdata = &freeze_escape($custominfo);
 9313:         }
 9314:         $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
 9315:                                     ':'.&escape($crstype).':'.&escape($inststatuslist).
 9316:                                     ':'.&escape($instcode).':'.&escape($instseclist).':'.
 9317:                                     $customdata,$homeserver));
 9318:     }
 9319:     return $response;
 9320: }
 9321: 
 9322: sub auto_validate_class_sec {
 9323:     my ($cdom,$cnum,$owners,$inst_class) = @_;
 9324:     my $homeserver = &homeserver($cnum,$cdom);
 9325:     my $ownerlist;
 9326:     if (ref($owners) eq 'ARRAY') {
 9327:         $ownerlist = join(',',@{$owners});
 9328:     } else {
 9329:         $ownerlist = $owners;
 9330:     }
 9331:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
 9332:                         &escape($ownerlist).':'.$cdom,$homeserver);
 9333:     return $response;
 9334: }
 9335: 
 9336: sub auto_validate_instclasses {
 9337:     my ($cdom,$cnum,$owners,$classesref) = @_;
 9338:     my ($homeserver,%validations);
 9339:     $homeserver = &homeserver($cnum,$cdom);
 9340:     unless ($homeserver eq 'no_host') {
 9341:         my $ownerlist;
 9342:         if (ref($owners) eq 'ARRAY') {
 9343:             $ownerlist = join(',',@{$owners});
 9344:         } else {
 9345:             $ownerlist = $owners;
 9346:         }
 9347:         if (ref($classesref) eq 'HASH') {
 9348:             my $classes = &freeze_escape($classesref);
 9349:             my $response=&reply('autovalidateinstclasses:'.&escape($ownerlist).
 9350:                                 ':'.$cdom.':'.$classes,$homeserver);
 9351:             unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
 9352:                 my @items = split(/&/,$response);
 9353:                 foreach my $item (@items) {
 9354:                     my ($key,$value) = split('=',$item);
 9355:                     $validations{&unescape($key)} = &thaw_unescape($value);
 9356:                 }
 9357:             }
 9358:         }
 9359:     }
 9360:     return %validations;
 9361: }
 9362: 
 9363: sub auto_crsreq_update {
 9364:     my ($cdom,$cnum,$crstype,$action,$ownername,$ownerdomain,$fullname,$title,
 9365:         $code,$accessstart,$accessend,$inbound) = @_;
 9366:     my ($homeserver,%crsreqresponse);
 9367:     if ($cdom =~ /^$match_domain$/) {
 9368:         $homeserver = &domain($cdom,'primary');
 9369:     }
 9370:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
 9371:         my $info;
 9372:         if (ref($inbound) eq 'HASH') {
 9373:             $info = &freeze_escape($inbound);
 9374:         }
 9375:         my $response=&reply('autocrsrequpdate:'.$cdom.':'.$cnum.':'.&escape($crstype).
 9376:                             ':'.&escape($action).':'.&escape($ownername).':'.
 9377:                             &escape($ownerdomain).':'.&escape($fullname).':'.
 9378:                             &escape($title).':'.&escape($code).':'.
 9379:                             &escape($accessstart).':'.&escape($accessend).':'.$info,
 9380:                             $homeserver);
 9381:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
 9382:             my @items = split(/&/,$response);
 9383:             foreach my $item (@items) {
 9384:                 my ($key,$value) = split('=',$item);
 9385:                 $crsreqresponse{&unescape($key)} = &thaw_unescape($value);
 9386:             }
 9387:         }
 9388:     }
 9389:     return \%crsreqresponse;
 9390: }
 9391: 
 9392: sub auto_export_grades {
 9393:     my ($cdom,$cnum,$inforef,$gradesref) = @_;
 9394:     my ($homeserver,%exportresponse);
 9395:     if ($cdom =~ /^$match_domain$/) {
 9396:         $homeserver = &domain($cdom,'primary');
 9397:     }
 9398:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
 9399:         my $info;
 9400:         if (ref($inforef) eq 'HASH') {
 9401:             $info = &freeze_escape($inforef);
 9402:         }
 9403:         if (ref($gradesref) eq 'HASH') {
 9404:             my $grades = &freeze_escape($gradesref);
 9405:             my $response=&reply('encrypt:autoexportgrades:'.$cdom.':'.$cnum.':'.
 9406:                                 $info.':'.$grades,$homeserver);
 9407:             unless ($response =~ /(con_lost|error|no_such_host|refused|unknown_command)/) {
 9408:                 my @items = split(/&/,$response);
 9409:                 foreach my $item (@items) {
 9410:                     my ($key,$value) = split('=',$item);
 9411:                     $exportresponse{&unescape($key)} = &thaw_unescape($value);
 9412:                 }
 9413:             }
 9414:         }
 9415:     }
 9416:     return \%exportresponse;
 9417: }
 9418: 
 9419: sub check_instcode_cloning {
 9420:     my ($codedefaults,$code_order,$cloner,$clonefromcode,$clonetocode) = @_;
 9421:     unless ((ref($codedefaults) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
 9422:         return;
 9423:     }
 9424:     my $canclone;
 9425:     if (@{$code_order} > 0) {
 9426:         my $instcoderegexp ='^';
 9427:         my @clonecodes = split(/\&/,$cloner);
 9428:         foreach my $item (@{$code_order}) {
 9429:             if (grep(/^\Q$item\E=/,@clonecodes)) {
 9430:                 foreach my $pair (@clonecodes) {
 9431:                     my ($key,$val) = split(/\=/,$pair,2);
 9432:                     $val = &unescape($val);
 9433:                     if ($key eq $item) {
 9434:                         $instcoderegexp .= '('.$val.')';
 9435:                         last;
 9436:                     }
 9437:                 }
 9438:             } else {
 9439:                 $instcoderegexp .= $codedefaults->{$item};
 9440:             }
 9441:         }
 9442:         $instcoderegexp .= '$';
 9443:         my (@from,@to);
 9444:         eval {
 9445:                (@from) = ($clonefromcode =~ /$instcoderegexp/);
 9446:                (@to) = ($clonetocode =~ /$instcoderegexp/);
 9447:         };
 9448:         if ((@from > 0) && (@to > 0)) {
 9449:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
 9450:             if (!@diffs) {
 9451:                 $canclone = 1;
 9452:             }
 9453:         }
 9454:     }
 9455:     return $canclone;
 9456: }
 9457: 
 9458: sub default_instcode_cloning {
 9459:     my ($clonedom,$domdefclone,$clonefromcode,$clonetocode,$codedefaultsref,$codeorderref) = @_;
 9460:     my (%codedefaults,@code_order,$canclone);
 9461:     if ((ref($codedefaultsref) eq 'HASH') && (ref($codeorderref) eq 'ARRAY')) {
 9462:         %codedefaults = %{$codedefaultsref};
 9463:         @code_order = @{$codeorderref};
 9464:     } elsif ($clonedom) {
 9465:         &auto_instcode_defaults($clonedom,\%codedefaults,\@code_order);
 9466:     }
 9467:     if (($domdefclone) && (@code_order)) {
 9468:         my @clonecodes = split(/\+/,$domdefclone);
 9469:         my $instcoderegexp ='^';
 9470:         foreach my $item (@code_order) {
 9471:             if (grep(/^\Q$item\E$/,@clonecodes)) {
 9472:                 $instcoderegexp .= '('.$codedefaults{$item}.')';
 9473:             } else {
 9474:                 $instcoderegexp .= $codedefaults{$item};
 9475:             }
 9476:         }
 9477:         $instcoderegexp .= '$';
 9478:         my (@from,@to);
 9479:         eval {
 9480:             (@from) = ($clonefromcode =~ /$instcoderegexp/);
 9481:             (@to) = ($clonetocode =~ /$instcoderegexp/);
 9482:         };
 9483:         if ((@from > 0) && (@to > 0)) {
 9484:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
 9485:             if (!@diffs) {
 9486:                 $canclone = 1;
 9487:             }
 9488:         }
 9489:     }
 9490:     return $canclone;
 9491: }
 9492: 
 9493: # ------------------------------------------------------- Course Group routines
 9494: 
 9495: sub get_coursegroups {
 9496:     my ($cdom,$cnum,$group,$namespace) = @_;
 9497:     return(&dump($namespace,$cdom,$cnum,$group));
 9498: }
 9499: 
 9500: sub modify_coursegroup {
 9501:     my ($cdom,$cnum,$groupsettings) = @_;
 9502:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
 9503: }
 9504: 
 9505: sub toggle_coursegroup_status {
 9506:     my ($cdom,$cnum,$group,$action) = @_;
 9507:     my ($from_namespace,$to_namespace);
 9508:     if ($action eq 'delete') {
 9509:         $from_namespace = 'coursegroups';
 9510:         $to_namespace = 'deleted_groups';
 9511:     } else {
 9512:         $from_namespace = 'deleted_groups';
 9513:         $to_namespace = 'coursegroups';
 9514:     }
 9515:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
 9516:     if (my $tmp = &error(%curr_group)) {
 9517:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
 9518:         return ('read error',$tmp);
 9519:     } else {
 9520:         my %savedsettings = %curr_group; 
 9521:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
 9522:         my $deloutcome;
 9523:         if ($result eq 'ok') {
 9524:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
 9525:         } else {
 9526:             return ('write error',$result);
 9527:         }
 9528:         if ($deloutcome eq 'ok') {
 9529:             return 'ok';
 9530:         } else {
 9531:             return ('delete error',$deloutcome);
 9532:         }
 9533:     }
 9534: }
 9535: 
 9536: sub modify_group_roles {
 9537:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
 9538:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
 9539:     my $role = 'gr/'.&escape($userprivs);
 9540:     my ($uname,$udom) = split(/:/,$user);
 9541:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
 9542:     if ($result eq 'ok') {
 9543:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
 9544:     }
 9545:     return $result;
 9546: }
 9547: 
 9548: sub modify_coursegroup_membership {
 9549:     my ($cdom,$cnum,$membership) = @_;
 9550:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
 9551:     return $result;
 9552: }
 9553: 
 9554: sub get_active_groups {
 9555:     my ($udom,$uname,$cdom,$cnum) = @_;
 9556:     my $now = time;
 9557:     my %groups = ();
 9558:     foreach my $key (keys(%env)) {
 9559:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
 9560:             my ($start,$end) = split(/\./,$env{$key});
 9561:             if (($end!=0) && ($end<$now)) { next; }
 9562:             if (($start!=0) && ($start>$now)) { next; }
 9563:             if ($1 eq $cdom && $2 eq $cnum) {
 9564:                 $groups{$3} = $env{$key} ;
 9565:             }
 9566:         }
 9567:     }
 9568:     return %groups;
 9569: }
 9570: 
 9571: sub get_group_membership {
 9572:     my ($cdom,$cnum,$group) = @_;
 9573:     return(&dump('groupmembership',$cdom,$cnum,$group));
 9574: }
 9575: 
 9576: sub get_users_groups {
 9577:     my ($udom,$uname,$courseid) = @_;
 9578:     my @usersgroups;
 9579:     my $cachetime=1800;
 9580: 
 9581:     my $hashid="$udom:$uname:$courseid";
 9582:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
 9583:     if (defined($cached)) {
 9584:         @usersgroups = split(/:/,$grouplist);
 9585:     } else {  
 9586:         $grouplist = '';
 9587:         my $courseurl = &courseid_to_courseurl($courseid);
 9588:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
 9589:         my $access_end = $env{'course.'.$courseid.
 9590:                               '.default_enrollment_end_date'};
 9591:         my $now = time;
 9592:         foreach my $key (keys(%roleshash)) {
 9593:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
 9594:                 my $group = $1;
 9595:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
 9596:                     my $start = $2;
 9597:                     my $end = $1;
 9598:                     if ($start == -1) { next; } # deleted from group
 9599:                     if (($start!=0) && ($start>$now)) { next; }
 9600:                     if (($end!=0) && ($end<$now)) {
 9601:                         if ($access_end && $access_end < $now) {
 9602:                             if ($access_end - $end < 86400) {
 9603:                                 push(@usersgroups,$group);
 9604:                             }
 9605:                         }
 9606:                         next;
 9607:                     }
 9608:                     push(@usersgroups,$group);
 9609:                 }
 9610:             }
 9611:         }
 9612:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
 9613:         $grouplist = join(':',@usersgroups);
 9614:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
 9615:     }
 9616:     return @usersgroups;
 9617: }
 9618: 
 9619: sub devalidate_getgroups_cache {
 9620:     my ($udom,$uname,$cdom,$cnum)=@_;
 9621:     my $courseid = $cdom.'_'.$cnum;
 9622: 
 9623:     my $hashid="$udom:$uname:$courseid";
 9624:     &devalidate_cache_new('getgroups',$hashid);
 9625: }
 9626: 
 9627: # ------------------------------------------------------------------ Plain Text
 9628: 
 9629: sub plaintext {
 9630:     my ($short,$type,$cid,$forcedefault) = @_;
 9631:     if ($short =~ m{^cr/}) {
 9632: 	return (split('/',$short))[-1];
 9633:     }
 9634:     if (!defined($cid)) {
 9635:         $cid = $env{'request.course.id'};
 9636:     }
 9637:     my %rolenames = (
 9638:                       Course    => 'std',
 9639:                       Community => 'alt1',
 9640:                       Placement => 'std',
 9641:                     );
 9642:     if ($cid ne '') {
 9643:         if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
 9644:             unless ($forcedefault) {
 9645:                 my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
 9646:                 &Apache::lonlocal::mt_escape(\$roletext);
 9647:                 return &Apache::lonlocal::mt($roletext);
 9648:             }
 9649:         }
 9650:     }
 9651:     if ((defined($type)) && (defined($rolenames{$type})) &&
 9652:         (defined($rolenames{$type})) && 
 9653:         (defined($prp{$short}{$rolenames{$type}}))) {
 9654:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
 9655:     } elsif ($cid ne '') {
 9656:         my $crstype = $env{'course.'.$cid.'.type'};
 9657:         if (($crstype ne '') && (defined($rolenames{$crstype})) &&
 9658:             (defined($prp{$short}{$rolenames{$crstype}}))) {
 9659:             return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
 9660:         }
 9661:     }
 9662:     return &Apache::lonlocal::mt($prp{$short}{'std'});
 9663: }
 9664: 
 9665: # ----------------------------------------------------------------- Assign Role
 9666: 
 9667: sub assignrole {
 9668:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
 9669:         $context)=@_;
 9670:     my $mrole;
 9671:     if ($role =~ /^cr\//) {
 9672:         my $cwosec=$url;
 9673:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
 9674: 	unless (&allowed('ccr',$cwosec)) {
 9675:            my $refused = 1;
 9676:            if ($context eq 'requestcourses') {
 9677:                if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
 9678:                    if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
 9679:                        if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
 9680:                            my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
 9681:                            my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
 9682:                            if ($crsenv{'internal.courseowner'} eq
 9683:                                $env{'user.name'}.':'.$env{'user.domain'}) {
 9684:                                $refused = '';
 9685:                            }
 9686:                        }
 9687:                    }
 9688:                }
 9689:            }
 9690:            if ($refused) {
 9691:                &logthis('Refused custom assignrole: '.
 9692:                         $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
 9693:                         ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
 9694:                return 'refused';
 9695:            }
 9696:         }
 9697:         $mrole='cr';
 9698:     } elsif ($role =~ /^gr\//) {
 9699:         my $cwogrp=$url;
 9700:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
 9701:         unless (&allowed('mdg',$cwogrp)) {
 9702:             &logthis('Refused group assignrole: '.
 9703:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
 9704:                     $env{'user.name'}.' at '.$env{'user.domain'});
 9705:             return 'refused';
 9706:         }
 9707:         $mrole='gr';
 9708:     } else {
 9709:         my $cwosec=$url;
 9710:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
 9711:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
 9712:             my $refused;
 9713:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
 9714:                 if (!(&allowed('c'.$role,$url))) {
 9715:                     $refused = 1;
 9716:                 }
 9717:             } else {
 9718:                 $refused = 1;
 9719:             }
 9720:             if ($refused) {
 9721:                 my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
 9722:                 if (!$selfenroll && (($context eq 'course') || ($context eq 'ltienroll' && $env{'request.lti.login'}))) {
 9723:                     my %crsenv;
 9724:                     if ($role eq 'cc' || $role eq 'co') {
 9725:                         %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
 9726:                         if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
 9727:                             if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
 9728:                                 if ($crsenv{'internal.courseowner'} eq 
 9729:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
 9730:                                     $refused = '';
 9731:                                 }
 9732:                             }
 9733:                         } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) { 
 9734:                             if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
 9735:                                 if ($crsenv{'internal.courseowner'} eq 
 9736:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
 9737:                                     $refused = '';
 9738:                                 }
 9739:                             }
 9740:                         }
 9741:                     }
 9742:                 } elsif (($selfenroll == 1) && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 9743:                     if ($role eq 'st') {
 9744:                         $refused = '';
 9745:                     } elsif (($context eq 'ltienroll') && ($env{'request.lti.login'})) {
 9746:                         $refused = '';
 9747:                     }
 9748:                 } elsif ($context eq 'requestcourses') {
 9749:                     my @possroles = ('st','ta','ep','in','cc','co');
 9750:                     if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
 9751:                         my $wrongcc;
 9752:                         if ($cnum =~ /^$match_community$/) {
 9753:                             $wrongcc = 1 if ($role eq 'cc');
 9754:                         } else {
 9755:                             $wrongcc = 1 if ($role eq 'co');
 9756:                         }
 9757:                         unless ($wrongcc) {
 9758:                             my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
 9759:                             if ($crsenv{'internal.courseowner'} eq 
 9760:                                  $env{'user.name'}.':'.$env{'user.domain'}) {
 9761:                                 $refused = '';
 9762:                             }
 9763:                         }
 9764:                     }
 9765:                 } elsif ($context eq 'requestauthor') {
 9766:                     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) && 
 9767:                         ($url eq '/'.$udom.'/') && ($role eq 'au')) {
 9768:                         if ($env{'environment.requestauthor'} eq 'automatic') {
 9769:                             $refused = '';
 9770:                         } else {
 9771:                             my %domdefaults = &get_domain_defaults($udom);
 9772:                             if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
 9773:                                 my $checkbystatus;
 9774:                                 if ($env{'user.adv'}) { 
 9775:                                     my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
 9776:                                     if ($disposition eq 'automatic') {
 9777:                                         $refused = '';
 9778:                                     } elsif ($disposition eq '') {
 9779:                                         $checkbystatus = 1;
 9780:                                     } 
 9781:                                 } else {
 9782:                                     $checkbystatus = 1;
 9783:                                 }
 9784:                                 if ($checkbystatus) {
 9785:                                     if ($env{'environment.inststatus'}) {
 9786:                                         my @inststatuses = split(/,/,$env{'environment.inststatus'});
 9787:                                         foreach my $type (@inststatuses) {
 9788:                                             if (($type ne '') &&
 9789:                                                 ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
 9790:                                                 $refused = '';
 9791:                                             }
 9792:                                         }
 9793:                                     } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
 9794:                                         $refused = '';
 9795:                                     }
 9796:                                 }
 9797:                             }
 9798:                         }
 9799:                     }
 9800:                 }
 9801:                 if ($refused) {
 9802:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
 9803:                              ' '.$role.' '.$end.' '.$start.' by '.
 9804: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
 9805:                     return 'refused';
 9806:                 }
 9807:             }
 9808:         } elsif ($role eq 'au') {
 9809:             if ($url ne '/'.$udom.'/') {
 9810:                 &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
 9811:                          ' to assign author role for '.$uname.':'.$udom.
 9812:                          ' in domain: '.$url.' refused (wrong domain).');
 9813:                 return 'refused';
 9814:             }
 9815:         }
 9816:         $mrole=$role;
 9817:     }
 9818:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
 9819:                 "$udom:$uname:$url".'_'."$mrole=$role";
 9820:     if ($end) { $command.='_'.$end; }
 9821:     if ($start) {
 9822: 	if ($end) { 
 9823:            $command.='_'.$start; 
 9824:         } else {
 9825:            $command.='_0_'.$start;
 9826:         }
 9827:     }
 9828:     my $origstart = $start;
 9829:     my $origend = $end;
 9830:     my $delflag;
 9831: # actually delete
 9832:     if ($deleteflag) {
 9833: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
 9834: # modify command to delete the role
 9835:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
 9836:                 "$udom:$uname:$url".'_'."$mrole";
 9837: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
 9838: # set start and finish to negative values for userrolelog
 9839:            $start=-1;
 9840:            $end=-1;
 9841:            $delflag = 1;
 9842:         }
 9843:     }
 9844: # send command
 9845:     my $answer=&reply($command,&homeserver($uname,$udom));
 9846: # log new user role if status is ok
 9847:     if ($answer eq 'ok') {
 9848: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
 9849:         if (($role eq 'cc') || ($role eq 'in') ||
 9850:             ($role eq 'ep') || ($role eq 'ad') ||
 9851:             ($role eq 'ta') || ($role eq 'st') ||
 9852:             ($role=~/^cr/) || ($role eq 'gr') ||
 9853:             ($role eq 'co')) {
 9854: # for course roles, perform group memberships changes triggered by role change.
 9855:             unless ($role =~ /^gr/) {
 9856:                 &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
 9857:                                                  $origstart,$selfenroll,$context);
 9858:             }
 9859:             &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
 9860:                            $selfenroll,$context);
 9861:         } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
 9862:                  ($role eq 'au') || ($role eq 'dc') || ($role eq 'dh') ||
 9863:                  ($role eq 'da')) {
 9864:             &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
 9865:                            $context);
 9866:         } elsif (($role eq 'ca') || ($role eq 'aa')) {
 9867:             &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
 9868:                              $context); 
 9869:         }
 9870:         if ($role eq 'cc') {
 9871:             &autoupdate_coowners($url,$end,$start,$uname,$udom);
 9872:         }
 9873:     }
 9874:     return $answer;
 9875: }
 9876: 
 9877: sub autoupdate_coowners {
 9878:     my ($url,$end,$start,$uname,$udom) = @_;
 9879:     my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
 9880:     if (($cdom ne '') && ($cnum ne '')) {
 9881:         my $now = time;
 9882:         my %domdesign = &Apache::loncommon::get_domainconf($cdom);
 9883:         if ($domdesign{$cdom.'.autoassign.co-owners'}) {
 9884:             my %coursehash = &coursedescription($cdom.'_'.$cnum);
 9885:             my $instcode = $coursehash{'internal.coursecode'};
 9886:             if ($instcode ne '') {
 9887:                 if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
 9888:                     unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
 9889:                         my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
 9890:                         my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
 9891:                         if ($result eq 'valid') {
 9892:                             if ($coursehash{'internal.co-owners'}) {
 9893:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
 9894:                                     push(@newcoowners,$coowner);
 9895:                                 }
 9896:                                 unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
 9897:                                     push(@newcoowners,$uname.':'.$udom);
 9898:                                 }
 9899:                                 @newcoowners = sort(@newcoowners);
 9900:                             } else {
 9901:                                 push(@newcoowners,$uname.':'.$udom);
 9902:                             }
 9903:                         } else {
 9904:                             if ($coursehash{'internal.co-owners'}) {
 9905:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
 9906:                                     unless ($coowner eq $uname.':'.$udom) {
 9907:                                         push(@newcoowners,$coowner);
 9908:                                     }
 9909:                                 }
 9910:                                 unless (@newcoowners > 0) {
 9911:                                     $delcoowners = 1;
 9912:                                     $coowners = '';
 9913:                                 }
 9914:                             }
 9915:                         }
 9916:                         if (@newcoowners || $delcoowners) {
 9917:                             &store_coowners($cdom,$cnum,$coursehash{'home'},
 9918:                                             $delcoowners,@newcoowners);
 9919:                         }
 9920:                     }
 9921:                 }
 9922:             }
 9923:         }
 9924:     }
 9925: }
 9926: 
 9927: sub store_coowners {
 9928:     my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
 9929:     my $cid = $cdom.'_'.$cnum;
 9930:     my ($coowners,$delresult,$putresult);
 9931:     if (@newcoowners) {
 9932:         $coowners = join(',',@newcoowners);
 9933:         my %coownershash = (
 9934:                             'internal.co-owners' => $coowners,
 9935:                            );
 9936:         $putresult = &put('environment',\%coownershash,$cdom,$cnum);
 9937:         if ($putresult eq 'ok') {
 9938:             if ($env{'course.'.$cid.'.num'} eq $cnum) {
 9939:                 &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
 9940:             }
 9941:         }
 9942:     }
 9943:     if ($delcoowners) {
 9944:         $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
 9945:         if ($delresult eq 'ok') {
 9946:             if ($env{'course.'.$cid.'.internal.co-owners'}) {
 9947:                 &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
 9948:             }
 9949:         }
 9950:     }
 9951:     if (($putresult eq 'ok') || ($delresult eq 'ok')) {
 9952:         my %crsinfo =
 9953:             &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
 9954:         if (ref($crsinfo{$cid}) eq 'HASH') {
 9955:             $crsinfo{$cid}{'co-owners'} = \@newcoowners;
 9956:             my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
 9957:         }
 9958:     }
 9959: }
 9960: 
 9961: # -------------------------------------------------- Modify user authentication
 9962: # Overrides without validation
 9963: 
 9964: sub modifyuserauth {
 9965:     my ($udom,$uname,$umode,$upass)=@_;
 9966:     my $uhome=&homeserver($uname,$udom);
 9967:     unless (&allowed('mau',$udom)) { return 'refused'; }
 9968:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
 9969:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
 9970:              ' in domain '.$env{'request.role.domain'});  
 9971:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
 9972: 		     &escape($upass),$uhome);
 9973:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
 9974:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
 9975:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
 9976:     &log($udom,,$uname,$uhome,
 9977:         'Authentication changed by '.$env{'user.domain'}.', '.
 9978:                                      $env{'user.name'}.', '.$umode.
 9979:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
 9980:     unless ($reply eq 'ok') {
 9981:         &logthis('Authentication mode error: '.$reply);
 9982: 	return 'error: '.$reply;
 9983:     }   
 9984:     return 'ok';
 9985: }
 9986: 
 9987: # --------------------------------------------------------------- Modify a user
 9988: 
 9989: sub modifyuser {
 9990:     my ($udom,    $uname, $uid,
 9991:         $umode,   $upass, $first,
 9992:         $middle,  $last,  $gene,
 9993:         $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
 9994:     $udom= &LONCAPA::clean_domain($udom);
 9995:     $uname=&LONCAPA::clean_username($uname);
 9996:     my $showcandelete = 'none';
 9997:     if (ref($candelete) eq 'ARRAY') {
 9998:         if (@{$candelete} > 0) {
 9999:             $showcandelete = join(', ',@{$candelete});
10000:         }
10001:     }
10002:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
10003:              $umode.', '.$first.', '.$middle.', '.
10004: 	     $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
10005:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
10006:                                      ' desiredhome not specified'). 
10007:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
10008:              ' in domain '.$env{'request.role.domain'});
10009:     my $uhome=&homeserver($uname,$udom,'true');
10010:     my $newuser;
10011:     if ($uhome eq 'no_host') {
10012:         $newuser = 1;
10013:         unless (($umode && ($upass ne '')) || ($umode eq 'localauth') ||
10014:                 ($umode eq 'lti')) {
10015:             return 'error: more information needed to create new user';
10016:         }
10017:     }
10018: # ----------------------------------------------------------------- Create User
10019:     if (($uhome eq 'no_host') && 
10020: 	(($umode && $upass) || ($umode eq 'localauth') || ($umode eq 'lti'))) {
10021:         my $unhome='';
10022:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
10023:             $unhome = $desiredhome;
10024: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
10025: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
10026:         } else { # load balancing routine for determining $unhome
10027:             my $loadm=10000000;
10028: 	    my %servers = &get_servers($udom,'library');
10029: 	    foreach my $tryserver (keys(%servers)) {
10030: 		my $answer=reply('load',$tryserver);
10031: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
10032: 		    $loadm=$answer;
10033: 		    $unhome=$tryserver;
10034: 		}
10035: 	    }
10036:         }
10037:         if (($unhome eq '') || ($unhome eq 'no_host')) {
10038: 	    return 'error: unable to find a home server for '.$uname.
10039:                    ' in domain '.$udom;
10040:         }
10041:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
10042:                          &escape($upass),$unhome);
10043: 	unless ($reply eq 'ok') {
10044:             return 'error: '.$reply;
10045:         }   
10046:         $uhome=&homeserver($uname,$udom,'true');
10047:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
10048: 	    return 'error: unable verify users home machine.';
10049:         }
10050:     }   # End of creation of new user
10051: # ---------------------------------------------------------------------- Add ID
10052:     if ($uid) {
10053:        $uid=~tr/A-Z/a-z/;
10054:        my %uidhash=&idrget($udom,$uname);
10055:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
10056:          && (!$forceid)) {
10057: 	  unless ($uid eq $uidhash{$uname}) {
10058: 	      return 'error: user id "'.$uid.'" does not match '.
10059:                   'current user id "'.$uidhash{$uname}.'".';
10060:           }
10061:        } else {
10062: 	  &idput($udom,{$uname => $uid},$uhome,'ids');
10063:        }
10064:     }
10065: # -------------------------------------------------------------- Add names, etc
10066:     my @tmp=&get('environment',
10067: 		   ['firstname','middlename','lastname','generation','id',
10068:                     'permanentemail','inststatus'],
10069: 		   $udom,$uname);
10070:     my (%names,%oldnames);
10071:     if ($tmp[0] =~ m/^error:.*/) { 
10072:         %names=(); 
10073:     } else {
10074:         %names = @tmp;
10075:         %oldnames = %names;
10076:     }
10077: #
10078: # If name, email and/or uid are blank (e.g., because an uploaded file
10079: # of users did not contain them), do not overwrite existing values
10080: # unless field is in $candelete array ref.  
10081: #
10082: 
10083:     my @fields = ('firstname','middlename','lastname','generation',
10084:                   'permanentemail','id');
10085:     my %newvalues;
10086:     if (ref($candelete) eq 'ARRAY') {
10087:         foreach my $field (@fields) {
10088:             if (grep(/^\Q$field\E$/,@{$candelete})) {
10089:                 if ($field eq 'firstname') {
10090:                     $names{$field} = $first;
10091:                 } elsif ($field eq 'middlename') {
10092:                     $names{$field} = $middle;
10093:                 } elsif ($field eq 'lastname') {
10094:                     $names{$field} = $last;
10095:                 } elsif ($field eq 'generation') { 
10096:                     $names{$field} = $gene;
10097:                 } elsif ($field eq 'permanentemail') {
10098:                     $names{$field} = $email;
10099:                 } elsif ($field eq 'id') {
10100:                     $names{$field}  = $uid;
10101:                 }
10102:             }
10103:         }
10104:     }
10105:     if ($first)  { $names{'firstname'}  = $first; }
10106:     if (defined($middle)) { $names{'middlename'} = $middle; }
10107:     if ($last)   { $names{'lastname'}   = $last; }
10108:     if (defined($gene))   { $names{'generation'} = $gene; }
10109:     if ($email) {
10110:        $email=~s/[^\w\@\.\-\,]//gs;
10111:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
10112:     }
10113:     if ($uid) { $names{'id'}  = $uid; }
10114:     if (defined($inststatus)) {
10115:         $names{'inststatus'} = '';
10116:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
10117:         if (ref($usertypes) eq 'HASH') {
10118:             my @okstatuses; 
10119:             foreach my $item (split(/:/,$inststatus)) {
10120:                 if (defined($usertypes->{$item})) {
10121:                     push(@okstatuses,$item);  
10122:                 }
10123:             }
10124:             if (@okstatuses) {
10125:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
10126:             }
10127:         }
10128:     }
10129:     my $logmsg = $udom.', '.$uname.', '.$uid.', '.
10130:                  $umode.', '.$first.', '.$middle.', '.
10131:                  $last.', '.$gene.', '.$email.', '.$inststatus;
10132:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
10133:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
10134:     } else {
10135:         $logmsg .= ' during self creation';
10136:     }
10137:     my $changed;
10138:     if ($newuser) {
10139:         $changed = 1;
10140:     } else {
10141:         foreach my $field (@fields) {
10142:             if ($names{$field} ne $oldnames{$field}) {
10143:                 $changed = 1;
10144:                 last;
10145:             }
10146:         }
10147:     }
10148:     unless ($changed) {
10149:         $logmsg = 'No changes in user information needed for: '.$logmsg;
10150:         &logthis($logmsg);
10151:         return 'ok';
10152:     }
10153:     my $reply = &put('environment', \%names, $udom,$uname);
10154:     if ($reply ne 'ok') { 
10155:         return 'error: '.$reply;
10156:     }
10157:     if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
10158:         &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
10159:     }
10160:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
10161:     &devalidate_cache_new('namescache',$uname.':'.$udom);
10162:     $logmsg = 'Success modifying user '.$logmsg;
10163:     &logthis($logmsg);
10164:     return 'ok';
10165: }
10166: 
10167: # -------------------------------------------------------------- Modify student
10168: 
10169: sub modifystudent {
10170:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
10171:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
10172:         $selfenroll,$context,$inststatus,$credits,$instsec)=@_;
10173:     if (!$cid) {
10174: 	unless ($cid=$env{'request.course.id'}) {
10175: 	    return 'not_in_class';
10176: 	}
10177:     }
10178: # --------------------------------------------------------------- Make the user
10179:     my $reply=&modifyuser
10180: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
10181:          $desiredhome,$email,$inststatus);
10182:     unless ($reply eq 'ok') { return $reply; }
10183:     # This will cause &modify_student_enrollment to get the uid from the
10184:     # student's environment
10185:     $uid = undef if (!$forceid);
10186:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
10187:                                         $gene,$usec,$end,$start,$type,$locktype,
10188:                                         $cid,$selfenroll,$context,$credits,$instsec);
10189:     return $reply;
10190: }
10191: 
10192: sub modify_student_enrollment {
10193:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,
10194:         $locktype,$cid,$selfenroll,$context,$credits,$instsec) = @_;
10195:     my ($cdom,$cnum,$chome);
10196:     if (!$cid) {
10197: 	unless ($cid=$env{'request.course.id'}) {
10198: 	    return 'not_in_class';
10199: 	}
10200: 	$cdom=$env{'course.'.$cid.'.domain'};
10201: 	$cnum=$env{'course.'.$cid.'.num'};
10202:     } else {
10203: 	($cdom,$cnum)=split(/_/,$cid);
10204:     }
10205:     $chome=$env{'course.'.$cid.'.home'};
10206:     if (!$chome) {
10207: 	$chome=&homeserver($cnum,$cdom);
10208:     }
10209:     if (!$chome) { return 'unknown_course'; }
10210:     # Make sure the user exists
10211:     my $uhome=&homeserver($uname,$udom);
10212:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
10213: 	return 'error: no such user';
10214:     }
10215:     # Get student data if we were not given enough information
10216:     if (!defined($first)  || $first  eq '' || 
10217:         !defined($last)   || $last   eq '' || 
10218:         !defined($uid)    || $uid    eq '' || 
10219:         !defined($middle) || $middle eq '' || 
10220:         !defined($gene)   || $gene   eq '') {
10221:         # They did not supply us with enough data to enroll the student, so
10222:         # we need to pick up more information.
10223:         my %tmp = &get('environment',
10224:                        ['firstname','middlename','lastname', 'generation','id']
10225:                        ,$udom,$uname);
10226: 
10227:         #foreach my $key (keys(%tmp)) {
10228:         #    &logthis("key $key = ".$tmp{$key});
10229:         #}
10230:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
10231:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
10232:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
10233:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
10234:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
10235:     }
10236:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
10237:     my $user = "$uname:$udom";
10238:     my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
10239:     my $reply=cput('classlist',
10240: 		   {$user => 
10241: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits,$instsec) },
10242: 		   $cdom,$cnum);
10243:     if (($reply eq 'ok') || ($reply eq 'delayed')) {
10244:         &devalidate_getsection_cache($udom,$uname,$cid);
10245:     } else { 
10246: 	return 'error: '.$reply;
10247:     }
10248:     # Add student role to user
10249:     my $uurl='/'.$cid;
10250:     $uurl=~s/\_/\//g;
10251:     if ($usec) {
10252: 	$uurl.='/'.$usec;
10253:     }
10254:     my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
10255:                              $selfenroll,$context);
10256:     if ($result ne 'ok') {
10257:         if ($old_entry{$user} ne '') {
10258:             $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
10259:         } else {
10260:             $reply = &del('classlist',[$user],$cdom,$cnum);
10261:         }
10262:     }
10263:     return $result; 
10264: }
10265: 
10266: sub format_name {
10267:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
10268:     my $name;
10269:     if ($first ne 'lastname') {
10270: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
10271:     } else {
10272: 	if ($lastname=~/\S/) {
10273: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
10274: 	    $name=~s/\s+,/,/;
10275: 	} else {
10276: 	    $name.= $firstname.' '.$middlename.' '.$generation;
10277: 	}
10278:     }
10279:     $name=~s/^\s+//;
10280:     $name=~s/\s+$//;
10281:     $name=~s/\s+/ /g;
10282:     return $name;
10283: }
10284: 
10285: # ------------------------------------------------- Write to course preferences
10286: 
10287: sub writecoursepref {
10288:     my ($courseid,%prefs)=@_;
10289:     $courseid=~s/^\///;
10290:     $courseid=~s/\_/\//g;
10291:     my ($cdomain,$cnum)=split(/\//,$courseid);
10292:     my $chome=homeserver($cnum,$cdomain);
10293:     if (($chome eq '') || ($chome eq 'no_host')) { 
10294: 	return 'error: no such course';
10295:     }
10296:     my $cstring='';
10297:     foreach my $pref (keys(%prefs)) {
10298: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
10299:     }
10300:     $cstring=~s/\&$//;
10301:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
10302: }
10303: 
10304: # ---------------------------------------------------------- Make/modify course
10305: 
10306: sub createcourse {
10307:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
10308:         $course_owner,$crstype,$cnum,$context,$category)=@_;
10309:     $url=&declutter($url);
10310:     my $cid='';
10311:     if ($context eq 'requestcourses') {
10312:         my $can_create = 0;
10313:         my ($ownername,$ownerdom) = split(':',$course_owner);
10314:         if ($udom eq $ownerdom) {
10315:             if (&usertools_access($ownername,$ownerdom,$category,undef,
10316:                                   $context)) {
10317:                 $can_create = 1;
10318:             }
10319:         } else {
10320:             my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
10321:                                            $category);
10322:             if ($userenv{'reqcrsotherdom.'.$category} ne '') {
10323:                 my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
10324:                 if (@curr > 0) {
10325:                     my @options = qw(approval validate autolimit);
10326:                     my $optregex = join('|',@options);
10327:                     if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
10328:                         $can_create = 1;
10329:                     }
10330:                 }
10331:             }
10332:         }
10333:         if ($can_create) {
10334:             unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
10335:                 unless (&allowed('ccc',$udom)) {
10336:                     return 'refused'; 
10337:                 }
10338:             }
10339:         } else {
10340:             return 'refused';
10341:         }
10342:     } elsif (!&allowed('ccc',$udom)) {
10343:         return 'refused';
10344:     }
10345: # --------------------------------------------------------------- Get Unique ID
10346:     my $uname;
10347:     if ($cnum =~ /^$match_courseid$/) {
10348:         my $chome=&homeserver($cnum,$udom,'true');
10349:         if (($chome eq '') || ($chome eq 'no_host')) {
10350:             $uname = $cnum;
10351:         } else {
10352:             $uname = &generate_coursenum($udom,$crstype);
10353:         }
10354:     } else {
10355:         $uname = &generate_coursenum($udom,$crstype);
10356:     }
10357:     return $uname if ($uname =~ /^error/);
10358: # -------------------------------------------------- Check supplied server name
10359:     if (!defined($course_server)) {
10360:         if (defined(&domain($udom,'primary'))) {
10361:             $course_server = &domain($udom,'primary');
10362:         } else {
10363:             $course_server = $env{'user.home'}; 
10364:         }
10365:     }
10366:     my %host_servers =
10367:         &Apache::lonnet::get_servers($udom,'library');
10368:     unless ($host_servers{$course_server}) {
10369:         return 'error: invalid home server for course: '.$course_server;
10370:     }
10371: # ------------------------------------------------------------- Make the course
10372:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
10373:                       $course_server);
10374:     unless ($reply eq 'ok') { return 'error: '.$reply; }
10375:     my $uhome=&homeserver($uname,$udom,'true');
10376:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
10377: 	return 'error: no such course';
10378:     }
10379: # ----------------------------------------------------------------- Course made
10380: # log existence
10381:     my $now = time;
10382:     my $newcourse = {
10383:                     $udom.'_'.$uname => {
10384:                                      description => $description,
10385:                                      inst_code   => $inst_code,
10386:                                      owner       => $course_owner,
10387:                                      type        => $crstype,
10388:                                      creator     => $env{'user.name'}.':'.
10389:                                                     $env{'user.domain'},
10390:                                      created     => $now,
10391:                                      context     => $context,
10392:                                                 },
10393:                     };
10394:     &courseidput($udom,$newcourse,$uhome,'notime');
10395: # set toplevel url
10396:     my $topurl=$url;
10397:     unless ($nonstandard) {
10398: # ------------------------------------------ For standard courses, make top url
10399:         my $mapurl=&clutter($url);
10400:         if ($mapurl eq '/res/') { $mapurl=''; }
10401:         $env{'form.initmap'}=(<<ENDINITMAP);
10402: <map>
10403: <resource id="1" type="start"></resource>
10404: <resource id="2" src="$mapurl"></resource>
10405: <resource id="3" type="finish"></resource>
10406: <link index="1" from="1" to="2"></link>
10407: <link index="2" from="2" to="3"></link>
10408: </map>
10409: ENDINITMAP
10410:         $topurl=&declutter(
10411:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
10412:                           );
10413:     }
10414: # ----------------------------------------------------------- Write preferences
10415:     &writecoursepref($udom.'_'.$uname,
10416:                      ('description'              => $description,
10417:                       'url'                      => $topurl,
10418:                       'internal.creator'         => $env{'user.name'}.':'.
10419:                                                     $env{'user.domain'},
10420:                       'internal.created'         => $now,
10421:                       'internal.creationcontext' => $context)
10422:                     );
10423:     return '/'.$udom.'/'.$uname;
10424: }
10425: 
10426: # ------------------------------------------------------------------- Create ID
10427: sub generate_coursenum {
10428:     my ($udom,$crstype) = @_;
10429:     my $domdesc = &domain($udom);
10430:     return 'error: invalid domain' if ($domdesc eq '');
10431:     my $first;
10432:     if ($crstype eq 'Community') {
10433:         $first = '0';
10434:     } else {
10435:         $first = int(1+rand(9)); 
10436:     } 
10437:     my $uname=$first.
10438:         ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
10439:         substr($$.time,0,5).unpack("H8",pack("I32",time)).
10440:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
10441: # ----------------------------------------------- Make sure that does not exist
10442:     my $uhome=&homeserver($uname,$udom,'true');
10443:     unless (($uhome eq '') || ($uhome eq 'no_host')) {
10444:         if ($crstype eq 'Community') {
10445:             $first = '0';
10446:         } else {
10447:             $first = int(1+rand(9));
10448:         }
10449:         $uname=$first.
10450:                ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
10451:                substr($$.time,0,5).unpack("H8",pack("I32",time)).
10452:                unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
10453:         $uhome=&homeserver($uname,$udom,'true');
10454:         unless (($uhome eq '') || ($uhome eq 'no_host')) {
10455:             return 'error: unable to generate unique course-ID';
10456:         }
10457:     }
10458:     return $uname;
10459: }
10460: 
10461: sub is_course {
10462:     my ($cdom, $cnum) = scalar(@_) == 1 ? 
10463:          ($_[0] =~ /^($match_domain)_($match_courseid)$/)  :  @_;
10464: 
10465:     return unless (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/));
10466:     my $uhome=&homeserver($cnum,$cdom);
10467:     my $iscourse;
10468:     if (grep { $_ eq $uhome } current_machine_ids()) {
10469:         $iscourse = &LONCAPA::Lond::is_course($cdom,$cnum);
10470:     } else {
10471:         my $hashid = $cdom.':'.$cnum;
10472:         ($iscourse,my $cached) = &is_cached_new('iscourse',$hashid);
10473:         unless (defined($cached)) {
10474:             my %courses = &courseiddump($cdom, '.', 1, '.', '.',
10475:                                         $cnum,undef,undef,'.');
10476:             $iscourse = 0;
10477:             if (exists($courses{$cdom.'_'.$cnum})) {
10478:                 $iscourse = 1;
10479:             }
10480:             &do_cache_new('iscourse',$hashid,$iscourse,3600);
10481:         }
10482:     }
10483:     return unless ($iscourse);
10484:     return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
10485: }
10486: 
10487: sub store_userdata {
10488:     my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
10489:     my $result;
10490:     if ($datakey ne '') {
10491:         if (ref($storehash) eq 'HASH') {
10492:             if ($udom eq '' || $uname eq '') {
10493:                 $udom = $env{'user.domain'};
10494:                 $uname = $env{'user.name'};
10495:             }
10496:             my $uhome=&homeserver($uname,$udom);
10497:             if (($uhome eq '') || ($uhome eq 'no_host')) {
10498:                 $result = 'error: no_host';
10499:             } else {
10500:                 $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
10501:                 $storehash->{'host'} = $perlvar{'lonHostID'};
10502: 
10503:                 my $namevalue='';
10504:                 foreach my $key (keys(%{$storehash})) {
10505:                     $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
10506:                 }
10507:                 $namevalue=~s/\&$//;
10508:                 unless ($namespace eq 'courserequests') {
10509:                     $datakey = &escape($datakey);
10510:                 }
10511:                 $result =  &reply("store:$udom:$uname:$namespace:$datakey:".
10512:                                   $namevalue,$uhome);
10513:             }
10514:         } else {
10515:             $result = 'error: data to store was not a hash reference'; 
10516:         }
10517:     } else {
10518:         $result= 'error: invalid requestkey'; 
10519:     }
10520:     return $result;
10521: }
10522: 
10523: # ---------------------------------------------------------- Assign Custom Role
10524: 
10525: sub assigncustomrole {
10526:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
10527:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
10528:                        $end,$start,$deleteflag,$selfenroll,$context);
10529: }
10530: 
10531: # ----------------------------------------------------------------- Revoke Role
10532: 
10533: sub revokerole {
10534:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
10535:     my $now=time;
10536:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
10537: }
10538: 
10539: # ---------------------------------------------------------- Revoke Custom Role
10540: 
10541: sub revokecustomrole {
10542:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
10543:     my $now=time;
10544:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
10545:            $deleteflag,$selfenroll,$context);
10546: }
10547: 
10548: # ------------------------------------------------------------ Disk usage
10549: sub diskusage {
10550:     my ($udom,$uname,$directorypath,$getpropath)=@_;
10551:     $directorypath =~ s/\/$//;
10552:     my $listing=&reply('du2:'.&escape($directorypath).':'
10553:                        .&escape($getpropath).':'.&escape($uname).':'
10554:                        .&escape($udom),homeserver($uname,$udom));
10555:     if ($listing eq 'unknown_cmd') {
10556:         if ($getpropath) {
10557:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
10558:         }
10559:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
10560:     }
10561:     return $listing;
10562: }
10563: 
10564: sub is_locked {
10565:     my ($file_name, $domain, $user, $which) = @_;
10566:     my @check;
10567:     my $is_locked;
10568:     push (@check,$file_name);
10569:     my %locked = &get('file_permissions',\@check,
10570: 		      $env{'user.domain'},$env{'user.name'});
10571:     my ($tmp)=keys(%locked);
10572:     if ($tmp=~/^error:/) { undef(%locked); }
10573:     
10574:     if (ref($locked{$file_name}) eq 'ARRAY') {
10575:         $is_locked = 'false';
10576:         foreach my $entry (@{$locked{$file_name}}) {
10577:            if (ref($entry) eq 'ARRAY') {
10578:                $is_locked = 'true';
10579:                if (ref($which) eq 'ARRAY') {
10580:                    push(@{$which},$entry);
10581:                } else {
10582:                    last;
10583:                }
10584:            }
10585:        }
10586:     } else {
10587:         $is_locked = 'false';
10588:     }
10589:     return $is_locked;
10590: }
10591: 
10592: sub declutter_portfile {
10593:     my ($file) = @_;
10594:     $file =~ s{^(/portfolio/|portfolio/)}{/};
10595:     return $file;
10596: }
10597: 
10598: # ------------------------------------------------------------- Mark as Read Only
10599: 
10600: sub mark_as_readonly {
10601:     my ($domain,$user,$files,$what) = @_;
10602:     my %current_permissions = &dump('file_permissions',$domain,$user);
10603:     my ($tmp)=keys(%current_permissions);
10604:     if ($tmp=~/^error:/) { undef(%current_permissions); }
10605:     foreach my $file (@{$files}) {
10606: 	$file = &declutter_portfile($file);
10607:         push(@{$current_permissions{$file}},$what);
10608:     }
10609:     &put('file_permissions',\%current_permissions,$domain,$user);
10610:     return;
10611: }
10612: 
10613: # ------------------------------------------------------------Save Selected Files
10614: 
10615: sub save_selected_files {
10616:     my ($user, $path, @files) = @_;
10617:     my $filename = $user."savedfiles";
10618:     my @other_files = &files_not_in_path($user, $path);
10619:     open (OUT,'>',LONCAPA::tempdir().$filename);
10620:     foreach my $file (@files) {
10621:         print (OUT $env{'form.currentpath'}.$file."\n");
10622:     }
10623:     foreach my $file (@other_files) {
10624:         print (OUT $file."\n");
10625:     }
10626:     close (OUT);
10627:     return 'ok';
10628: }
10629: 
10630: sub clear_selected_files {
10631:     my ($user) = @_;
10632:     my $filename = $user."savedfiles";
10633:     open (OUT,'>',LONCAPA::tempdir().$filename);
10634:     print (OUT undef);
10635:     close (OUT);
10636:     return ("ok");    
10637: }
10638: 
10639: sub files_in_path {
10640:     my ($user, $path) = @_;
10641:     my $filename = $user."savedfiles";
10642:     my %return_files;
10643:     open (IN,'<',LONCAPA::tempdir().$filename);
10644:     while (my $line_in = <IN>) {
10645:         chomp ($line_in);
10646:         my @paths_and_file = split (m!/!, $line_in);
10647:         my $file_part = pop (@paths_and_file);
10648:         my $path_part = join ('/', @paths_and_file);
10649:         $path_part.='/';
10650:         my $path_and_file = $path_part.$file_part;
10651:         if ($path_part eq $path) {
10652:             $return_files{$file_part}= 'selected';
10653:         }
10654:     }
10655:     close (IN);
10656:     return (\%return_files);
10657: }
10658: 
10659: # called in portfolio select mode, to show files selected NOT in current directory
10660: sub files_not_in_path {
10661:     my ($user, $path) = @_;
10662:     my $filename = $user."savedfiles";
10663:     my @return_files;
10664:     my $path_part;
10665:     open(IN, '<',LONCAPA::tempdir().$filename);
10666:     while (my $line = <IN>) {
10667:         #ok, I know it's clunky, but I want it to work
10668:         my @paths_and_file = split(m|/|, $line);
10669:         my $file_part = pop(@paths_and_file);
10670:         chomp($file_part);
10671:         my $path_part = join('/', @paths_and_file);
10672:         $path_part .= '/';
10673:         my $path_and_file = $path_part.$file_part;
10674:         if ($path_part ne $path) {
10675:             push(@return_files, ($path_and_file));
10676:         }
10677:     }
10678:     close(OUT);
10679:     return (@return_files);
10680: }
10681: 
10682: #------------------------------Submitted/Handedback Portfolio Files Versioning
10683:  
10684: sub portfiles_versioning {
10685:     my ($symb,$domain,$stu_name,$portfiles,$versioned_portfiles) = @_;
10686:     my $portfolio_root = '/userfiles/portfolio';
10687:     return unless ((ref($portfiles) eq 'ARRAY') && (ref($versioned_portfiles) eq 'ARRAY'));
10688:     foreach my $file (@{$portfiles}) {
10689:         &unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
10690:         my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
10691:         my ($answer_name,$answer_ver,$answer_ext) = &file_name_version_ext($answer_file);
10692:         my $getpropath = 1;
10693:         my ($dir_list,$listerror) = &dirlist($portfolio_root.$directory,$domain,
10694:                                              $stu_name,$getpropath);
10695:         my $version = &get_next_version($answer_name,$answer_ext,$dir_list);
10696:         my $new_answer = 
10697:             &version_selected_portfile($domain,$stu_name,$directory,$answer_file,$version);
10698:         if ($new_answer ne 'problem getting file') {
10699:             push(@{$versioned_portfiles}, $directory.$new_answer);
10700:             &mark_as_readonly($domain,$stu_name,[$directory.$new_answer],
10701:                               [$symb,$env{'request.course.id'},'graded']);
10702:         }
10703:     }
10704: }
10705: 
10706: sub get_next_version {
10707:     my ($answer_name, $answer_ext, $dir_list) = @_;
10708:     my $version;
10709:     if (ref($dir_list) eq 'ARRAY') {
10710:         foreach my $row (@{$dir_list}) {
10711:             my ($file) = split(/\&/,$row,2);
10712:             my ($file_name,$file_version,$file_ext) =
10713:                 &file_name_version_ext($file);
10714:             if (($file_name eq $answer_name) &&
10715:                 ($file_ext eq $answer_ext)) {
10716:                      # gets here if filename and extension match,
10717:                      # regardless of version
10718:                 if ($file_version ne '') {
10719:                     # a versioned file is found  so save it for later
10720:                     if ($file_version > $version) {
10721:                         $version = $file_version;
10722:                     }
10723:                 }
10724:             }
10725:         }
10726:     }
10727:     $version ++;
10728:     return($version);
10729: }
10730: 
10731: sub version_selected_portfile {
10732:     my ($domain,$stu_name,$directory,$file_name,$version) = @_;
10733:     my ($answer_name,$answer_ver,$answer_ext) =
10734:         &file_name_version_ext($file_name);
10735:     my $new_answer;
10736:     $env{'form.copy'} =
10737:         &getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
10738:     if($env{'form.copy'} eq '-1') {
10739:         $new_answer = 'problem getting file';
10740:     } else {
10741:         $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
10742:         my $copy_result = 
10743:             &finishuserfileupload($stu_name,$domain,'copy',
10744:                                   '/portfolio'.$directory.$new_answer);
10745:     }
10746:     undef($env{'form.copy'});
10747:     return ($new_answer);
10748: }
10749: 
10750: sub file_name_version_ext {
10751:     my ($file)=@_;
10752:     my @file_parts = split(/\./, $file);
10753:     my ($name,$version,$ext);
10754:     if (@file_parts > 1) {
10755:         $ext=pop(@file_parts);
10756:         if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
10757:             $version=pop(@file_parts);
10758:         }
10759:         $name=join('.',@file_parts);
10760:     } else {
10761:         $name=join('.',@file_parts);
10762:     }
10763:     return($name,$version,$ext);
10764: }
10765: 
10766: #----------------------------------------------Get portfolio file permissions
10767: 
10768: sub get_portfile_permissions {
10769:     my ($domain,$user) = @_;
10770:     my %current_permissions = &dump('file_permissions',$domain,$user);
10771:     my ($tmp)=keys(%current_permissions);
10772:     if ($tmp=~/^error:/) { undef(%current_permissions); }
10773:     return \%current_permissions;
10774: }
10775: 
10776: #---------------------------------------------Get portfolio file access controls
10777: 
10778: sub get_access_controls {
10779:     my ($current_permissions,$group,$file) = @_;
10780:     my %access;
10781:     my $real_file = $file;
10782:     $file =~ s/\.meta$//;
10783:     if (defined($file)) {
10784:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
10785:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
10786:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
10787:             }
10788:         }
10789:     } else {
10790:         foreach my $key (keys(%{$current_permissions})) {
10791:             if ($key =~ /\0accesscontrol$/) {
10792:                 if (defined($group)) {
10793:                     if ($key !~ m-^\Q$group\E/-) {
10794:                         next;
10795:                     }
10796:                 }
10797:                 my ($fullpath) = split(/\0/,$key);
10798:                 if (ref($$current_permissions{$key}) eq 'HASH') {
10799:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
10800:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
10801:                     }
10802:                 }
10803:             }
10804:         }
10805:     }
10806:     return %access;
10807: }
10808: 
10809: sub modify_access_controls {
10810:     my ($file_name,$changes,$domain,$user)=@_;
10811:     my ($outcome,$deloutcome);
10812:     my %store_permissions;
10813:     my %new_values;
10814:     my %new_control;
10815:     my %translation;
10816:     my @deletions = ();
10817:     my $now = time;
10818:     if (exists($$changes{'activate'})) {
10819:         if (ref($$changes{'activate'}) eq 'HASH') {
10820:             my @newitems = sort(keys(%{$$changes{'activate'}}));
10821:             my $numnew = scalar(@newitems);
10822:             for (my $i=0; $i<$numnew; $i++) {
10823:                 my $newkey = $newitems[$i];
10824:                 my $newid = &Apache::loncommon::get_cgi_id();
10825:                 if ($newkey =~ /^\d+:/) { 
10826:                     $newkey =~ s/^(\d+)/$newid/;
10827:                     $translation{$1} = $newid;
10828:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
10829:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
10830:                     $translation{$1} = $newid;
10831:                 }
10832:                 $new_values{$file_name."\0".$newkey} = 
10833:                                           $$changes{'activate'}{$newitems[$i]};
10834:                 $new_control{$newkey} = $now;
10835:             }
10836:         }
10837:     }
10838:     my %todelete;
10839:     my %changed_items;
10840:     foreach my $action ('delete','update') {
10841:         if (exists($$changes{$action})) {
10842:             if (ref($$changes{$action}) eq 'HASH') {
10843:                 foreach my $key (keys(%{$$changes{$action}})) {
10844:                     my ($itemnum) = ($key =~ /^([^:]+):/);
10845:                     if ($action eq 'delete') { 
10846:                         $todelete{$itemnum} = 1;
10847:                     } else {
10848:                         $changed_items{$itemnum} = $key;
10849:                     }
10850:                 }
10851:             }
10852:         }
10853:     }
10854:     # get lock on access controls for file.
10855:     my $lockhash = {
10856:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
10857:                                                        ':'.$env{'user.domain'},
10858:                    }; 
10859:     my $tries = 0;
10860:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
10861:    
10862:     while (($gotlock ne 'ok') && $tries < 10) {
10863:         $tries ++;
10864:         sleep(0.1);
10865:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
10866:     }
10867:     if ($gotlock eq 'ok') {
10868:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
10869:         my ($tmp)=keys(%curr_permissions);
10870:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
10871:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
10872:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
10873:             if (ref($curr_controls) eq 'HASH') {
10874:                 foreach my $control_item (keys(%{$curr_controls})) {
10875:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
10876:                     if (defined($todelete{$itemnum})) {
10877:                         push(@deletions,$file_name."\0".$control_item);
10878:                     } else {
10879:                         if (defined($changed_items{$itemnum})) {
10880:                             $new_control{$changed_items{$itemnum}} = $now;
10881:                             push(@deletions,$file_name."\0".$control_item);
10882:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
10883:                         } else {
10884:                             $new_control{$control_item} = $$curr_controls{$control_item};
10885:                         }
10886:                     }
10887:                 }
10888:             }
10889:         }
10890:         my ($group);
10891:         if (&is_course($domain,$user)) {
10892:             ($group,my $file) = split(/\//,$file_name,2);
10893:         }
10894:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
10895:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
10896:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
10897:         #  remove lock
10898:         my @del_lock = ($file_name."\0".'locked_access_records');
10899:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
10900:         my $sqlresult =
10901:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
10902:                                     $group);
10903:     } else {
10904:         $outcome = "error: could not obtain lockfile\n";  
10905:     }
10906:     return ($outcome,$deloutcome,\%new_values,\%translation);
10907: }
10908: 
10909: sub make_public_indefinitely {
10910:     my (@requrl) = @_;
10911:     return &automated_portfile_access('public',\@requrl);
10912: }
10913: 
10914: sub automated_portfile_access {
10915:     my ($accesstype,$addsref,$delsref,$info) = @_;
10916:     unless (($accesstype eq 'public') || ($accesstype eq 'ip')) {
10917:         return 'invalid';
10918:     }
10919:     my %urls;
10920:     if (ref($addsref) eq 'ARRAY') {
10921:         foreach my $requrl (@{$addsref}) {
10922:             if (&is_portfolio_url($requrl)) {
10923:                 unless (exists($urls{$requrl})) {
10924:                     $urls{$requrl} = 'add';
10925:                 }
10926:             }
10927:         }
10928:     }
10929:     if (ref($delsref) eq 'ARRAY') {
10930:         foreach my $requrl (@{$delsref}) { 
10931:             if (&is_portfolio_url($requrl)) {
10932:                 unless (exists($urls{$requrl})) {
10933:                     $urls{$requrl} = 'delete'; 
10934:                 }
10935:             }
10936:         }
10937:     }
10938:     unless (keys(%urls)) {
10939:         return 'invalid';
10940:     }
10941:     my $ip;
10942:     if ($accesstype eq 'ip') {
10943:         if (ref($info) eq 'HASH') {
10944:             if ($info->{'ip'} ne '') {
10945:                 $ip = $info->{'ip'};
10946:             }
10947:         }
10948:         if ($ip eq '') {
10949:             return 'invalid';
10950:         }
10951:     }
10952:     my $errors;
10953:     my $now = time;
10954:     my %current_perms;
10955:     foreach my $requrl (sort(keys(%urls))) {
10956:         my $action;
10957:         if ($urls{$requrl} eq 'add') {
10958:             $action = 'activate';
10959:         } else {
10960:             $action = 'none';
10961:         }
10962:         my $aclnum = 0;
10963:         my (undef,$udom,$unum,$file_name,$group) =
10964:             &parse_portfolio_url($requrl);
10965:         unless (exists($current_perms{$unum.':'.$udom})) {
10966:             $current_perms{$unum.':'.$udom} = &get_portfile_permissions($udom,$unum);
10967:         }
10968:         my %access_controls = &get_access_controls($current_perms{$unum.':'.$udom},
10969:                                                    $group,$file_name);
10970:         foreach my $key (keys(%{$access_controls{$file_name}})) {
10971:             my ($num,$scope,$end,$start) = 
10972:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
10973:             if ($scope eq $accesstype) {
10974:                 if (($start <= $now) && ($end == 0)) {
10975:                     if ($accesstype eq 'ip') {
10976:                         if (ref($access_controls{$file_name}{$key}) eq 'HASH') {
10977:                             if (ref($access_controls{$file_name}{$key}{'ip'}) eq 'ARRAY') {
10978:                                 if (grep(/^\Q$ip\E$/,@{$access_controls{$file_name}{$key}{'ip'}})) {
10979:                                     if ($urls{$requrl} eq 'add') {
10980:                                         $action = 'none';
10981:                                         last;
10982:                                     } else {
10983:                                         $action = 'delete';
10984:                                         $aclnum = $num;
10985:                                         last;
10986:                                     }
10987:                                 }
10988:                             }
10989:                         }
10990:                     } elsif ($accesstype eq 'public') {
10991:                         if ($urls{$requrl} eq 'add') {
10992:                             $action = 'none';
10993:                             last;
10994:                         } else {
10995:                             $action = 'delete';
10996:                             $aclnum = $num;
10997:                             last;
10998:                         }
10999:                     }
11000:                 } elsif ($accesstype eq 'public') {
11001:                     $action = 'update';
11002:                     $aclnum = $num;
11003:                     last;
11004:                 }
11005:             }
11006:         }
11007:         if ($action eq 'none') {
11008:             next;
11009:         } else {
11010:             my %changes;
11011:             my $newend = 0;
11012:             my $newstart = $now;
11013:             my $newkey = $aclnum.':'.$accesstype.'_'.$newend.'_'.$newstart;
11014:             $changes{$action}{$newkey} = {
11015:                 type => $accesstype,
11016:                 time => {
11017:                     start => $newstart,
11018:                     end   => $newend,
11019:                 },
11020:             };
11021:             if ($accesstype eq 'ip') {
11022:                 $changes{$action}{$newkey}{'ip'} = [$ip];
11023:             }
11024:             my ($outcome,$deloutcome,$new_values,$translation) =
11025:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
11026:             unless ($outcome eq 'ok') {
11027:                 $errors .= $outcome.' ';
11028:             }
11029:         }
11030:     }
11031:     if ($errors) {
11032:         $errors =~ s/\s$//;
11033:         return $errors;
11034:     } else {
11035:         return 'ok';
11036:     }
11037: }
11038: 
11039: #------------------------------------------------------Get Marked as Read Only
11040: 
11041: sub get_marked_as_readonly {
11042:     my ($domain,$user,$what,$group) = @_;
11043:     my $current_permissions = &get_portfile_permissions($domain,$user);
11044:     my @readonly_files;
11045:     my $cmp1=$what;
11046:     if (ref($what)) { $cmp1=join('',@{$what}) };
11047:     while (my ($file_name,$value) = each(%{$current_permissions})) {
11048:         if (defined($group)) {
11049:             if ($file_name !~ m-^\Q$group\E/-) {
11050:                 next;
11051:             }
11052:         }
11053:         if (ref($value) eq "ARRAY"){
11054:             foreach my $stored_what (@{$value}) {
11055:                 my $cmp2=$stored_what;
11056:                 if (ref($stored_what) eq 'ARRAY') {
11057:                     $cmp2=join('',@{$stored_what});
11058:                 }
11059:                 if ($cmp1 eq $cmp2) {
11060:                     push(@readonly_files, $file_name);
11061:                     last;
11062:                 } elsif (!defined($what)) {
11063:                     push(@readonly_files, $file_name);
11064:                     last;
11065:                 }
11066:             }
11067:         }
11068:     }
11069:     return @readonly_files;
11070: }
11071: #-----------------------------------------------------------Get Marked as Read Only Hash
11072: 
11073: sub get_marked_as_readonly_hash {
11074:     my ($current_permissions,$group,$what) = @_;
11075:     my %readonly_files;
11076:     while (my ($file_name,$value) = each(%{$current_permissions})) {
11077:         if (defined($group)) {
11078:             if ($file_name !~ m-^\Q$group\E/-) {
11079:                 next;
11080:             }
11081:         }
11082:         if (ref($value) eq "ARRAY"){
11083:             foreach my $stored_what (@{$value}) {
11084:                 if (ref($stored_what) eq 'ARRAY') {
11085:                     foreach my $lock_descriptor(@{$stored_what}) {
11086:                         if ($lock_descriptor eq 'graded') {
11087:                             $readonly_files{$file_name} = 'graded';
11088:                         } elsif ($lock_descriptor eq 'handback') {
11089:                             $readonly_files{$file_name} = 'handback';
11090:                         } else {
11091:                             if (!exists($readonly_files{$file_name})) {
11092:                                 $readonly_files{$file_name} = 'locked';
11093:                             }
11094:                         }
11095:                     }
11096:                 } 
11097:             }
11098:         } 
11099:     }
11100:     return %readonly_files;
11101: }
11102: # ------------------------------------------------------------ Unmark as Read Only
11103: 
11104: sub unmark_as_readonly {
11105:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
11106:     # for portfolio submissions, $what contains [$symb,$crsid] 
11107:     my ($domain,$user,$what,$file_name,$group) = @_;
11108:     $file_name = &declutter_portfile($file_name);
11109:     my $symb_crs = $what;
11110:     if (ref($what)) { $symb_crs=join('',@$what); }
11111:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
11112:     my ($tmp)=keys(%current_permissions);
11113:     if ($tmp=~/^error:/) { undef(%current_permissions); }
11114:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
11115:     foreach my $file (@readonly_files) {
11116: 	my $clean_file = &declutter_portfile($file);
11117: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
11118: 	my $current_locks = $current_permissions{$file};
11119:         my @new_locks;
11120:         my @del_keys;
11121:         if (ref($current_locks) eq "ARRAY"){
11122:             foreach my $locker (@{$current_locks}) {
11123:                 my $compare=$locker;
11124:                 if (ref($locker) eq 'ARRAY') {
11125:                     $compare=join('',@{$locker});
11126:                     if ($compare ne $symb_crs) {
11127:                         push(@new_locks, $locker);
11128:                     }
11129:                 }
11130:             }
11131:             if (scalar(@new_locks) > 0) {
11132:                 $current_permissions{$file} = \@new_locks;
11133:             } else {
11134:                 push(@del_keys, $file);
11135:                 &del('file_permissions',\@del_keys, $domain, $user);
11136:                 delete($current_permissions{$file});
11137:             }
11138:         }
11139:     }
11140:     &put('file_permissions',\%current_permissions,$domain,$user);
11141:     return;
11142: }
11143: 
11144: # ------------------------------------------------------------ Directory lister
11145: 
11146: sub dirlist {
11147:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
11148:     $uri=~s/^\///;
11149:     $uri=~s/\/$//;
11150:     my ($udom, $uname);
11151:     if ($getuserdir) {
11152:         $udom = $userdomain;
11153:         $uname = $username;
11154:     } else {
11155:         (undef,$udom,$uname)=split(/\//,$uri);
11156:         if(defined($userdomain)) {
11157:             $udom = $userdomain;
11158:         }
11159:         if(defined($username)) {
11160:             $uname = $username;
11161:         }
11162:     }
11163:     my ($dirRoot,$listing,@listing_results);
11164: 
11165:     $dirRoot = $perlvar{'lonDocRoot'};
11166:     if (defined($getpropath)) {
11167:         $dirRoot = &propath($udom,$uname);
11168:         $dirRoot =~ s/\/$//;
11169:     } elsif (defined($getuserdir)) {
11170:         my $subdir=$uname.'__';
11171:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
11172:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
11173:                    ."/$udom/$subdir/$uname";
11174:     } elsif (defined($alternateRoot)) {
11175:         $dirRoot = $alternateRoot;
11176:     }
11177: 
11178:     if($udom) {
11179:         if($uname) {
11180:             my $uhome = &homeserver($uname,$udom);
11181:             if ($uhome eq 'no_host') {
11182:                 return ([],'no_host');
11183:             }
11184:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
11185:                               .$getuserdir.':'.&escape($dirRoot)
11186:                               .':'.&escape($uname).':'.&escape($udom),$uhome);
11187:             if ($listing eq 'unknown_cmd') {
11188:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
11189:             } else {
11190:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
11191:             }
11192:             if ($listing eq 'unknown_cmd') {
11193:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
11194:                 @listing_results = split(/:/,$listing);
11195:             } else {
11196:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
11197:             }
11198:             if (($listing eq 'no_such_host') || ($listing eq 'con_lost') || 
11199:                 ($listing eq 'rejected') || ($listing eq 'refused') ||
11200:                 ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
11201:                 return ([],$listing);
11202:             } else {
11203:                 return (\@listing_results);
11204:             }
11205:         } elsif(!$alternateRoot) {
11206:             my (%allusers,%listerror);
11207: 	    my %servers = &get_servers($udom,'library');
11208:  	    foreach my $tryserver (keys(%servers)) {
11209:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
11210:                                   &escape($udom),$tryserver);
11211:                 if ($listing eq 'unknown_cmd') {
11212: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
11213: 				      $udom, $tryserver);
11214:                 } else {
11215:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
11216:                 }
11217: 		if ($listing eq 'unknown_cmd') {
11218: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
11219: 				      $udom, $tryserver);
11220: 		    @listing_results = split(/:/,$listing);
11221: 		} else {
11222: 		    @listing_results =
11223: 			map { &unescape($_); } split(/:/,$listing);
11224: 		}
11225:                 if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
11226:                     ($listing eq 'rejected') || ($listing eq 'refused') ||
11227:                     ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
11228:                     $listerror{$tryserver} = $listing;
11229:                 } else {
11230: 		    foreach my $line (@listing_results) {
11231: 			my ($entry) = split(/&/,$line,2);
11232: 			$allusers{$entry} = 1;
11233: 		    }
11234: 		}
11235:             }
11236:             my @alluserslist=();
11237:             foreach my $user (sort(keys(%allusers))) {
11238:                 push(@alluserslist,$user.'&user');
11239:             }
11240: 
11241:             if (!%listerror) {
11242:                 # no errors
11243:                 return (\@alluserslist);
11244:             } elsif (scalar(keys(%servers)) == 1) {
11245:                 # one library server, one error 
11246:                 my ($key) = keys(%listerror);
11247:                 return (\@alluserslist, $listerror{$key});
11248:             } elsif ( grep { $_ eq 'con_lost' } values(%listerror) ) {
11249:                 # con_lost indicates that we might miss data from at least one
11250:                 # library server
11251:                 return (\@alluserslist, 'con_lost');
11252:             } else {
11253:                 # multiple library servers and no con_lost -> data should be
11254:                 # complete. 
11255:                 return (\@alluserslist);
11256:             }
11257: 
11258:         } else {
11259:             return ([],'missing username');
11260:         }
11261:     } elsif(!defined($getpropath)) {
11262:         my $path = $perlvar{'lonDocRoot'}.'/res/'; 
11263:         my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
11264:         return (\@all_domains);
11265:     } else {
11266:         return ([],'missing domain');
11267:     }
11268: }
11269: 
11270: # --------------------------------------------- GetFileTimestamp
11271: # This function utilizes dirlist and returns the date stamp for
11272: # when it was last modified.  It will also return an error of -1
11273: # if an error occurs
11274: 
11275: sub GetFileTimestamp {
11276:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
11277:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
11278:     $studentName   = &LONCAPA::clean_username($studentName);
11279:     my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
11280:                                     undef,$getuserdir);
11281:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
11282:         return -1;
11283:     }
11284:     if (ref($fileref) eq 'ARRAY') {
11285:         my @stats = split('&',$fileref->[0]);
11286:         # @stats contains first the filename, then the stat output
11287:         return $stats[10]; # so this is 10 instead of 9.
11288:     } else {
11289:         return -1;
11290:     }
11291: }
11292: 
11293: sub stat_file {
11294:     my ($uri) = @_;
11295:     $uri = &clutter_with_no_wrapper($uri);
11296: 
11297:     my ($udom,$uname,$file);
11298:     if ($uri =~ m-^/(uploaded|editupload)/-) {
11299: 	($udom,$uname,$file) =
11300: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
11301: 	$file = 'userfiles/'.$file;
11302:     }
11303:     if ($uri =~ m-^/res/-) {
11304: 	($udom,$uname) = 
11305: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
11306: 	$file = $uri;
11307:     }
11308: 
11309:     if (!$udom || !$uname || !$file) {
11310: 	# unable to handle the uri
11311: 	return ();
11312:     }
11313:     my $getpropath;
11314:     if ($file =~ /^userfiles\//) {
11315:         $getpropath = 1;
11316:     }
11317:     my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
11318:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
11319:         return ();
11320:     } else {
11321:         if (ref($listref) eq 'ARRAY') {
11322:             my @stats = split('&',$listref->[0]);
11323: 	    shift(@stats); #filename is first
11324: 	    return @stats;
11325:         }
11326:     }
11327:     return ();
11328: }
11329: 
11330: # --------------------------------------------------------- recursedirs
11331: # Recursive function to traverse either a specific user's Authoring Space
11332: # or corresponding Published Resource Space, and populate the hash ref:
11333: # $dirhashref with URLs of all directories, and if $filehashref hash
11334: # ref arg is provided, the URLs of any files, excluding versioned, .meta,
11335: # or .rights files in resource space, and .meta, .save, .log, and .bak
11336: # files in Authoring Space.
11337: #
11338: # Inputs:
11339: #
11340: # $is_home - true if current server is home server for user's space
11341: # $context - either: priv, or res respectively for Authoring or Resource Space.
11342: # $docroot - Document root (i.e., /home/httpd/html
11343: # $toppath - Top level directory (i.e., /res/$dom/$uname or /priv/$dom/$uname
11344: # $relpath - Current path (relative to top level).
11345: # $dirhashref - reference to hash to populate with URLs of directories (Required)
11346: # $filehashref - reference to hash to populate with URLs of files (Optional)
11347: #
11348: # Returns: nothing
11349: #
11350: # Side Effects: populates $dirhashref, and $filehashref (if provided).
11351: #
11352: # Currently used by interface/londocs.pm to create linked select boxes for
11353: # directory and filename to import a Course "Author" resource into a course, and
11354: # also to create linked select boxes for Authoring Space and Directory to choose
11355: # save location for creation of a new "standard" problem from the Course Editor.
11356: #
11357: 
11358: sub recursedirs {
11359:     my ($is_home,$context,$docroot,$toppath,$relpath,$dirhashref,$filehashref) = @_;
11360:     return unless (ref($dirhashref) eq 'HASH');
11361:     my $currpath = $docroot.$toppath;
11362:     if ($relpath) {
11363:         $currpath .= "/$relpath";
11364:     }
11365:     my $savefile;
11366:     if (ref($filehashref)) {
11367:         $savefile = 1;
11368:     }
11369:     if ($is_home) {
11370:         if (opendir(my $dirh,$currpath)) {
11371:             foreach my $item (sort { lc($a) cmp lc($b) } grep(!/^\.+$/,readdir($dirh))) {
11372:                 next if ($item eq '');
11373:                 if (-d "$currpath/$item") {
11374:                     my $newpath;
11375:                     if ($relpath) {
11376:                         $newpath = "$relpath/$item";
11377:                     } else {
11378:                         $newpath = $item;
11379:                     }
11380:                     $dirhashref->{&Apache::lonlocal::js_escape($newpath)} = 1;
11381:                     &recursedirs($is_home,$context,$docroot,$toppath,$newpath,$dirhashref,$filehashref);
11382:                 } elsif ($savefile) {
11383:                     if ($context eq 'priv') {
11384:                         unless ($item =~ /\.(meta|save|log|bak|DS_Store)$/) {
11385:                             $filehashref->{&Apache::lonlocal::js_escape($relpath)}{$item} = 1;
11386:                         }
11387:                     } else {
11388:                         unless (($item =~ /\.meta$/) || ($item =~ /\.\d+\.\w+$/) || ($item =~ /\.rights$/)) {
11389:                             $filehashref->{&Apache::lonlocal::js_escape($relpath)}{$item} = 1;
11390:                         }
11391:                     }
11392:                 }
11393:             }
11394:             closedir($dirh);
11395:         }
11396:     } else {
11397:         my ($dirlistref,$listerror) =
11398:             &dirlist($toppath.$relpath);
11399:         my @dir_lines;
11400:         my $dirptr=16384;
11401:         if (ref($dirlistref) eq 'ARRAY') {
11402:             foreach my $dir_line (sort
11403:                               {
11404:                                   my ($afile)=split('&',$a,2);
11405:                                   my ($bfile)=split('&',$b,2);
11406:                                   return (lc($afile) cmp lc($bfile));
11407:                               } (@{$dirlistref})) {
11408:                 my ($item,$dom,undef,$testdir,undef,undef,undef,undef,$size,undef,$mtime,undef,undef,undef,$obs,undef) =
11409:                     split(/\&/,$dir_line,16);
11410:                 $item =~ s/\s+$//;
11411:                 next if (($item =~ /^\.\.?$/) || ($obs));
11412:                 if ($dirptr&$testdir) {
11413:                     my $newpath;
11414:                     if ($relpath) {
11415:                         $newpath = "$relpath/$item";
11416:                     } else {
11417:                         $relpath = '/';
11418:                         $newpath = $item;
11419:                     }
11420:                     $dirhashref->{&Apache::lonlocal::js_escape($newpath)} = 1;
11421:                     &recursedirs($is_home,$context,$docroot,$toppath,$newpath,$dirhashref,$filehashref);
11422:                 } elsif ($savefile) {
11423:                     if ($context eq 'priv') {
11424:                         unless ($item =~ /\.(meta|save|log|bak|DS_Store)$/) {
11425:                             $filehashref->{$relpath}{$item} = 1;
11426:                         }
11427:                     } else {
11428:                         unless (($item =~ /\.meta$/) || ($item =~ /\.\d+\.\w+$/)) {
11429:                             $filehashref->{$relpath}{$item} = 1;
11430:                         }
11431:                     }
11432:                 }
11433:             }
11434:         }
11435:     }
11436:     return;
11437: }
11438: 
11439: # -------------------------------------------------------- Value of a Condition
11440: 
11441: # gets the value of a specific preevaluated condition
11442: #    stored in the string  $env{user.state.<cid>}
11443: # or looks up a condition reference in the bighash and if if hasn't
11444: # already been evaluated recurses into docondval to get the value of
11445: # the condition, then memoizing it to 
11446: #   $env{user.state.<cid>.<condition>}
11447: sub directcondval {
11448:     my $number=shift;
11449:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
11450: 	&Apache::lonuserstate::evalstate();
11451:     }
11452:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
11453: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
11454:     } elsif ($number =~ /^_/) {
11455: 	my $sub_condition;
11456: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
11457: 		&GDBM_READER(),0640)) {
11458: 	    $sub_condition=$bighash{'conditions'.$number};
11459: 	    untie(%bighash);
11460: 	}
11461: 	my $value = &docondval($sub_condition);
11462: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
11463: 	return $value;
11464:     }
11465:     if ($env{'user.state.'.$env{'request.course.id'}}) {
11466:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
11467:     } else {
11468:        return 2;
11469:     }
11470: }
11471: 
11472: # get the collection of conditions for this resource
11473: sub condval {
11474:     my $condidx=shift;
11475:     my $allpathcond='';
11476:     foreach my $cond (split(/\|/,$condidx)) {
11477: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
11478: 	    $allpathcond.=
11479: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
11480: 	}
11481:     }
11482:     $allpathcond=~s/\|$//;
11483:     return &docondval($allpathcond);
11484: }
11485: 
11486: #evaluates an expression of conditions
11487: sub docondval {
11488:     my ($allpathcond) = @_;
11489:     my $result=0;
11490:     if ($env{'request.course.id'}
11491: 	&& defined($allpathcond)) {
11492: 	my $operand='|';
11493: 	my @stack;
11494: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
11495: 	    if ($chunk eq '(') {
11496: 		push @stack,($operand,$result);
11497: 	    } elsif ($chunk eq ')') {
11498: 		my $before=pop @stack;
11499: 		if (pop @stack eq '&') {
11500: 		    $result=$result>$before?$before:$result;
11501: 		} else {
11502: 		    $result=$result>$before?$result:$before;
11503: 		}
11504: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
11505: 		$operand=$chunk;
11506: 	    } else {
11507: 		my $new=directcondval($chunk);
11508: 		if ($operand eq '&') {
11509: 		    $result=$result>$new?$new:$result;
11510: 		} else {
11511: 		    $result=$result>$new?$result:$new;
11512: 		}
11513: 	    }
11514: 	}
11515:     }
11516:     return $result;
11517: }
11518: 
11519: # ---------------------------------------------------- Devalidate courseresdata
11520: 
11521: sub devalidatecourseresdata {
11522:     my ($coursenum,$coursedomain)=@_;
11523:     my $hashid=$coursenum.':'.$coursedomain;
11524:     &devalidate_cache_new('courseres',$hashid);
11525: }
11526: 
11527: 
11528: # --------------------------------------------------- Course Resourcedata Query
11529: #
11530: #  Parameters:
11531: #      $coursenum    - Number of the course.
11532: #      $coursedomain - Domain at which the course was created.
11533: #  Returns:
11534: #     A hash of the course parameters along (I think) with timestamps
11535: #     and version info.
11536: 
11537: sub get_courseresdata {
11538:     my ($coursenum,$coursedomain)=@_;
11539:     my $coursehom=&homeserver($coursenum,$coursedomain);
11540:     my $hashid=$coursenum.':'.$coursedomain;
11541:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
11542:     my %dumpreply;
11543:     unless (defined($cached)) {
11544: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
11545: 	$result=\%dumpreply;
11546: 	my ($tmp) = keys(%dumpreply);
11547: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
11548: 	    &do_cache_new('courseres',$hashid,$result,600);
11549: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
11550: 	    return $tmp;
11551: 	} elsif ($tmp =~ /^(error)/) {
11552: 	    $result=undef;
11553: 	    &do_cache_new('courseres',$hashid,$result,600);
11554: 	}
11555:     }
11556:     return $result;
11557: }
11558: 
11559: sub devalidateuserresdata {
11560:     my ($uname,$udom)=@_;
11561:     my $hashid="$udom:$uname";
11562:     &devalidate_cache_new('userres',$hashid);
11563: }
11564: 
11565: sub get_userresdata {
11566:     my ($uname,$udom)=@_;
11567:     #most student don\'t have any data set, check if there is some data
11568:     if (&EXT_cache_status($udom,$uname)) { return undef; }
11569: 
11570:     my $hashid="$udom:$uname";
11571:     my ($result,$cached)=&is_cached_new('userres',$hashid);
11572:     if (!defined($cached)) {
11573: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
11574: 	$result=\%resourcedata;
11575: 	&do_cache_new('userres',$hashid,$result,600);
11576:     }
11577:     my ($tmp)=keys(%$result);
11578:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
11579: 	return $result;
11580:     }
11581:     #error 2 occurs when the .db doesn't exist
11582:     if ($tmp!~/error: 2 /) {
11583:         if ((!defined($cached)) || ($tmp ne 'con_lost')) {
11584: 	    &logthis("<font color=\"blue\">WARNING:".
11585: 		     " Trying to get resource data for ".
11586: 		     $uname." at ".$udom.": ".
11587: 		     $tmp."</font>");
11588:         }
11589:     } elsif ($tmp=~/error: 2 /) {
11590: 	#&EXT_cache_set($udom,$uname);
11591: 	&do_cache_new('userres',$hashid,undef,600);
11592: 	undef($tmp); # not really an error so don't send it back
11593:     }
11594:     return $tmp;
11595: }
11596: #----------------------------------------------- resdata - return resource data
11597: #  Purpose:
11598: #    Return resource data for either users or for a course.
11599: #  Parameters:
11600: #     $name      - Course/user name.
11601: #     $domain    - Name of the domain the user/course is registered on.
11602: #     $type      - Type of thing $name is (must be 'course' or 'user')
11603: #     $mapp      - decluttered URL of enclosing map  
11604: #     $recursed  - Ref to scalar -- set to 1, if nested maps have been recursed.
11605: #     $recurseup - Ref to array of map URLs, starting with map containing
11606: #                  $mapp up through hierarchy of nested maps to top level map.  
11607: #     $courseid  - CourseID (first part of param identifier).
11608: #     $modifier  - Middle part of param identifier.
11609: #     $what      - Last part of param identifier.
11610: #     @which     - Array of names of resources desired.
11611: #  Returns:
11612: #     The value of the first reasource in @which that is found in the
11613: #     resource hash.
11614: #  Exceptional Conditions:
11615: #     If the $type passed in is not valid (not the string 'course' or 
11616: #     'user', an undefined  reference is returned.
11617: #     If none of the resources are found, an undef is returned
11618: sub resdata {
11619:     my ($name,$domain,$type,$mapp,$recursed,$recurseup,$courseid,
11620:         $modifier,$what,@which)=@_;
11621:     my $result;
11622:     if ($type eq 'course') {
11623: 	$result=&get_courseresdata($name,$domain);
11624:     } elsif ($type eq 'user') {
11625: 	$result=&get_userresdata($name,$domain);
11626:     }
11627:     if (!ref($result)) { return $result; }    
11628:     foreach my $item (@which) {
11629:         if ($item->[1] eq 'course') {
11630:             if ((ref($recurseup) eq 'ARRAY') && (ref($recursed) eq 'SCALAR')) {
11631:                 unless ($$recursed) {
11632:                     @{$recurseup} = &get_map_hierarchy($mapp,$courseid);
11633:                     $$recursed = 1;
11634:                 }
11635:                 foreach my $item (@${recurseup}) {
11636:                     my $norecursechk=$courseid.$modifier.$item.'___(all).'.$what;
11637:                     last if (defined($result->{$norecursechk}));
11638:                     my $recursechk=$courseid.$modifier.$item.'___(rec).'.$what;
11639:                     if (defined($result->{$recursechk})) { return [$result->{$recursechk},'map']; }
11640:                 }
11641:             }
11642:         }
11643:         if (defined($result->{$item->[0]})) {
11644: 	    return [$result->{$item->[0]},$item->[1]];
11645: 	}
11646:     }
11647:     return undef;
11648: }
11649: 
11650: sub get_domain_lti {
11651:     my ($cdom,$context) = @_;
11652:     my ($name,%lti);
11653:     if ($context eq 'consumer') {
11654:         $name = 'ltitools';
11655:     } elsif ($context eq 'provider') {
11656:         $name = 'lti';
11657:     } else {
11658:         return %lti;
11659:     }
11660:     my ($result,$cached)=&is_cached_new($name,$cdom);
11661:     if (defined($cached)) {
11662:         if (ref($result) eq 'HASH') {
11663:             %lti = %{$result};
11664:         }
11665:     } else {
11666:         my %domconfig = &get_dom('configuration',[$name],$cdom);
11667:         if (ref($domconfig{$name}) eq 'HASH') {
11668:             %lti = %{$domconfig{$name}};
11669:             my %encdomconfig = &get_dom('encconfig',[$name],$cdom);
11670:             if (ref($encdomconfig{$name}) eq 'HASH') {
11671:                 foreach my $id (keys(%lti)) {
11672:                     if (ref($encdomconfig{$name}{$id}) eq 'HASH') {
11673:                         foreach my $item ('key','secret') {
11674:                             $lti{$id}{$item} = $encdomconfig{$name}{$id}{$item};
11675:                         }
11676:                     }
11677:                 }
11678:             }
11679:         }
11680:         my $cachetime = 24*60*60;
11681:         &do_cache_new($name,$cdom,\%lti,$cachetime);
11682:     }
11683:     return %lti;
11684: }
11685: 
11686: sub get_numsuppfiles {
11687:     my ($cnum,$cdom,$ignorecache)=@_;
11688:     my $hashid=$cnum.':'.$cdom;
11689:     my ($suppcount,$cached);
11690:     unless ($ignorecache) {
11691:         ($suppcount,$cached) = &is_cached_new('suppcount',$hashid);
11692:     }
11693:     unless (defined($cached)) {
11694:         my $chome=&homeserver($cnum,$cdom);
11695:         unless ($chome eq 'no_host') {
11696:             ($suppcount,my $supptools,my $errors) = (0,0,0);
11697:             my $suppmap = 'supplemental.sequence';
11698:             ($suppcount,$supptools,$errors) =
11699:                 &Apache::loncommon::recurse_supplemental($cnum,$cdom,$suppmap,$suppcount,
11700:                                                          $supptools,$errors);
11701:         }
11702:         &do_cache_new('suppcount',$hashid,$suppcount,600);
11703:     }
11704:     return $suppcount;
11705: }
11706: 
11707: #
11708: # EXT resource caching routines
11709: #
11710: 
11711: {
11712: # Cache (5 seconds) of map hierarchy for speedup of navmaps display
11713: #
11714: # The course for which we cache
11715: my $cachedmapkey='';
11716: # The cached recursive maps for this course
11717: my %cachedmaps=();
11718: # When this was last done
11719: my $cachedmaptime='';
11720: 
11721: sub clear_EXT_cache_status {
11722:     &delenv('cache.EXT.');
11723: }
11724: 
11725: sub EXT_cache_status {
11726:     my ($target_domain,$target_user) = @_;
11727:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
11728:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
11729:         # We know already the user has no data
11730:         return 1;
11731:     } else {
11732:         return 0;
11733:     }
11734: }
11735: 
11736: sub EXT_cache_set {
11737:     my ($target_domain,$target_user) = @_;
11738:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
11739:     #&appenv({$cachename => time});
11740: }
11741: 
11742: # --------------------------------------------------------- Value of a Variable
11743: sub EXT {
11744: 
11745:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse,$cid)=@_;
11746:     unless ($varname) { return ''; }
11747:     #get real user name/domain, courseid and symb
11748:     my $courseid;
11749:     my $publicuser;
11750:     if ($symbparm) {
11751: 	$symbparm=&get_symb_from_alias($symbparm);
11752:     }
11753:     if (!($uname && $udom)) {
11754:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
11755:       if (!$symbparm) {	$symbparm=$cursymb; }
11756:     } else {
11757: 	$courseid=$env{'request.course.id'};
11758:     }
11759:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
11760:     my $rest;
11761:     if (defined($therest[0])) {
11762:        $rest=join('.',@therest);
11763:     } else {
11764:        $rest='';
11765:     }
11766: 
11767:     my $qualifierrest=$qualifier;
11768:     if ($rest) { $qualifierrest.='.'.$rest; }
11769:     my $spacequalifierrest=$space;
11770:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
11771:     if ($realm eq 'user') {
11772: # --------------------------------------------------------------- user.resource
11773: 	if ($space eq 'resource') {
11774: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
11775: 		  || defined($Apache::lonhomework::parsing_a_task))
11776: 		 &&
11777: 		 ($symbparm eq &symbread()) ) {	
11778: 		# if we are in the middle of processing the resource the
11779: 		# get the value we are planning on committing
11780:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
11781:                     return $Apache::lonhomework::results{$qualifierrest};
11782:                 } else {
11783:                     return $Apache::lonhomework::history{$qualifierrest};
11784:                 }
11785: 	    } else {
11786: 		my %restored;
11787: 		if ($publicuser || $env{'request.state'} eq 'construct') {
11788: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
11789: 		} else {
11790: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
11791: 		}
11792: 		return $restored{$qualifierrest};
11793: 	    }
11794: # ----------------------------------------------------------------- user.access
11795:         } elsif ($space eq 'access') {
11796: 	    # FIXME - not supporting calls for a specific user
11797:             return &allowed($qualifier,$rest);
11798: # ------------------------------------------ user.preferences, user.environment
11799:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
11800: 	    if (($uname eq $env{'user.name'}) &&
11801: 		($udom eq $env{'user.domain'})) {
11802: 		return $env{join('.',('environment',$qualifierrest))};
11803: 	    } else {
11804: 		my %returnhash;
11805: 		if (!$publicuser) {
11806: 		    %returnhash=&userenvironment($udom,$uname,
11807: 						 $qualifierrest);
11808: 		}
11809: 		return $returnhash{$qualifierrest};
11810: 	    }
11811: # ----------------------------------------------------------------- user.course
11812:         } elsif ($space eq 'course') {
11813: 	    # FIXME - not supporting calls for a specific user
11814:             return $env{join('.',('request.course',$qualifier))};
11815: # ------------------------------------------------------------------- user.role
11816:         } elsif ($space eq 'role') {
11817: 	    # FIXME - not supporting calls for a specific user
11818:             my ($role,$where)=split(/\./,$env{'request.role'});
11819:             if ($qualifier eq 'value') {
11820: 		return $role;
11821:             } elsif ($qualifier eq 'extent') {
11822:                 return $where;
11823:             }
11824: # ----------------------------------------------------------------- user.domain
11825:         } elsif ($space eq 'domain') {
11826:             return $udom;
11827: # ------------------------------------------------------------------- user.name
11828:         } elsif ($space eq 'name') {
11829:             return $uname;
11830: # ---------------------------------------------------- Any other user namespace
11831:         } else {
11832: 	    my %reply;
11833: 	    if (!$publicuser) {
11834: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
11835: 	    }
11836: 	    return $reply{$qualifierrest};
11837:         }
11838:     } elsif ($realm eq 'query') {
11839: # ---------------------------------------------- pull stuff out of query string
11840:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
11841: 						[$spacequalifierrest]);
11842: 	return $env{'form.'.$spacequalifierrest}; 
11843:    } elsif ($realm eq 'request') {
11844: # ------------------------------------------------------------- request.browser
11845:         if ($space eq 'browser') {
11846:             return $env{'browser.'.$qualifier};
11847: # ------------------------------------------------------------ request.filename
11848:         } else {
11849:             return $env{'request.'.$spacequalifierrest};
11850:         }
11851:     } elsif ($realm eq 'course') {
11852: # ---------------------------------------------------------- course.description
11853:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
11854:     } elsif ($realm eq 'resource') {
11855: 
11856: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
11857: 	    if (!$symbparm) { $symbparm=&symbread(); }
11858: 	}
11859: 
11860:         if ($qualifier eq '') {
11861: 	    if ($space eq 'title') {
11862: 	        if (!$symbparm) { $symbparm = $env{'request.filename'}; }
11863: 	        return &gettitle($symbparm);
11864: 	    }
11865: 	
11866: 	    if ($space eq 'map') {
11867: 	        my ($map) = &decode_symb($symbparm);
11868: 	        return &symbread($map);
11869: 	    }
11870:             if ($space eq 'maptitle') {
11871:                 my ($map) = &decode_symb($symbparm);
11872:                 return &gettitle($map);
11873:             }
11874: 	    if ($space eq 'filename') {
11875: 	        if ($symbparm) {
11876: 		    return &clutter((&decode_symb($symbparm))[2]);
11877: 	        }
11878: 	        return &hreflocation('',$env{'request.filename'});
11879: 	    }
11880: 
11881:             if ((defined($courseid)) && ($courseid eq $env{'request.course.id'}) && $symbparm) {
11882:                 if ($space eq 'visibleparts') {
11883:                     my $navmap = Apache::lonnavmaps::navmap->new();
11884:                     my $item;
11885:                     if (ref($navmap)) {
11886:                         my $res = $navmap->getBySymb($symbparm);
11887:                         my $parts = $res->parts();
11888:                         if (ref($parts) eq 'ARRAY') {
11889:                             $item = join(',',@{$parts});
11890:                         }
11891:                         undef($navmap);
11892:                     }
11893:                     return $item;
11894:                 }
11895:             }
11896:         }
11897: 
11898: 	my ($section, $group, @groups, @recurseup, $recursed);
11899: 	my ($courselevelm,$courseleveli,$courselevel,$mapp);
11900:         if (($courseid eq '') && ($cid)) {
11901:             $courseid = $cid;
11902:         }
11903: 	if (($symbparm && $courseid) && 
11904: 	    (($courseid eq $env{'request.course.id'}) || ($courseid eq $cid)))  {
11905: 
11906: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
11907: 
11908: # ----------------------------------------------------- Cascading lookup scheme
11909: 	    my $symbp=$symbparm;
11910: 	    $mapp=&deversion((&decode_symb($symbp))[0]);
11911: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
11912:             my $recurseparm=$mapp.'___(rec).'.$spacequalifierrest;
11913: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
11914: 	    if (($env{'user.name'} eq $uname) &&
11915: 		($env{'user.domain'} eq $udom)) {
11916: 		$section=$env{'request.course.sec'};
11917:                 @groups = split(/:/,$env{'request.course.groups'});  
11918:                 @groups=&sort_course_groups($courseid,@groups); 
11919: 	    } else {
11920: 		if (! defined($usection)) {
11921: 		    $section=&getsection($udom,$uname,$courseid);
11922: 		} else {
11923: 		    $section = $usection;
11924: 		}
11925:                 @groups = &get_users_groups($udom,$uname,$courseid);
11926: 	    }
11927: 
11928: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
11929: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
11930:             my $secleveli=$courseid.'.['.$section.'].'.$recurseparm;
11931: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
11932: 
11933: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
11934: 	    my $courselevelr=$courseid.'.'.$symbparm;
11935:             $courseleveli=$courseid.'.'.$recurseparm;
11936: 	    $courselevelm=$courseid.'.'.$mapparm;
11937: 
11938: # ----------------------------------------------------------- first, check user
11939: 
11940: 	    my $userreply=&resdata($uname,$udom,'user',$mapp,\$recursed,
11941:                                    \@recurseup,$courseid,'.',$spacequalifierrest, 
11942: 				       ([$courselevelr,'resource'],
11943: 					[$courselevelm,'map'     ],
11944:                                         [$courseleveli,'map'     ],
11945: 					[$courselevel, 'course'  ]));
11946: 	    if (defined($userreply)) { return &get_reply($userreply); }
11947: 
11948: # ------------------------------------------------ second, check some of course
11949:             my $coursereply;
11950:             if (@groups > 0) {
11951:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
11952:                                        $recurseparm,$mapparm,$spacequalifierrest,
11953:                                        $mapp,\$recursed,\@recurseup);
11954:                 if (defined($coursereply)) { return &get_reply($coursereply); } 
11955:             }
11956: 
11957: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
11958: 				  $env{'course.'.$courseid.'.domain'},
11959: 				  'course',$mapp,\$recursed,\@recurseup,
11960:                                   $courseid,'.['.$section.'].',$spacequalifierrest,
11961: 				  ([$seclevelr,   'resource'],
11962: 				   [$seclevelm,   'map'     ],
11963:                                    [$secleveli,   'map'     ],
11964: 				   [$seclevel,    'course'  ],
11965: 				   [$courselevelr,'resource']));
11966: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
11967: 
11968: # ------------------------------------------------------ third, check map parms
11969: 	    my %parmhash=();
11970: 	    my $thisparm='';
11971: 	    if (tie(%parmhash,'GDBM_File',
11972: 		    $env{'request.course.fn'}.'_parms.db',
11973: 		    &GDBM_READER(),0640)) {
11974: 		$thisparm=$parmhash{$symbparm};
11975: 		untie(%parmhash);
11976: 	    }
11977: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
11978: 	}
11979: # ------------------------------------------ fourth, look in resource metadata
11980:  
11981:         my $what = $spacequalifierrest;
11982: 	$what=~s/\./\_/;
11983: 	my $filename;
11984: 	if (!$symbparm) { $symbparm=&symbread(); }
11985: 	if ($symbparm) {
11986: 	    $filename=(&decode_symb($symbparm))[2];
11987: 	} else {
11988: 	    $filename=$env{'request.filename'};
11989: 	}
11990:         my $toolsymb;
11991:         if (($filename =~ /ext\.tool$/) && ($what ne '0_gradable')) {
11992:             $toolsymb = $symbparm;
11993:         }
11994: 	my $metadata=&metadata($filename,$what,$toolsymb);
11995: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
11996: 	$metadata=&metadata($filename,'parameter_'.$what,$toolsymb);
11997: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
11998: 
11999: # ----------------------------------------------- fifth, look in rest of course
12000: 	if ($symbparm && defined($courseid) && 
12001: 	    $courseid eq $env{'request.course.id'}) {
12002: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
12003: 				     $env{'course.'.$courseid.'.domain'},
12004: 				     'course',$mapp,\$recursed,\@recurseup,
12005:                                      $courseid,'.',$spacequalifierrest,
12006: 				     ([$courselevelm,'map'   ],
12007:                                       [$courseleveli,'map'   ],
12008: 				      [$courselevel, 'course']));
12009: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
12010: 	}
12011: # ------------------------------------------------------------------ Cascade up
12012: 	unless ($space eq '0') {
12013: 	    my @parts=split(/_/,$space);
12014: 	    my $id=pop(@parts);
12015: 	    my $part=join('_',@parts);
12016: 	    if ($part eq '') { $part='0'; }
12017: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
12018: 				 $symbparm,$udom,$uname,$section,1);
12019: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
12020: 	}
12021: 	if ($recurse) { return undef; }
12022: 	my $pack_def=&packages_tab_default($filename,$varname,$toolsymb);
12023: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
12024: # ---------------------------------------------------- Any other user namespace
12025:     } elsif ($realm eq 'environment') {
12026: # ----------------------------------------------------------------- environment
12027: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
12028: 	    return $env{'environment.'.$spacequalifierrest};
12029: 	} else {
12030: 	    if ($uname eq 'anonymous' && $udom eq '') {
12031: 		return '';
12032: 	    }
12033: 	    my %returnhash=&userenvironment($udom,$uname,
12034: 					    $spacequalifierrest);
12035: 	    return $returnhash{$spacequalifierrest};
12036: 	}
12037:     } elsif ($realm eq 'system') {
12038: # ----------------------------------------------------------------- system.time
12039: 	if ($space eq 'time') {
12040: 	    return time;
12041:         }
12042:     } elsif ($realm eq 'server') {
12043: # ----------------------------------------------------------------- system.time
12044: 	if ($space eq 'name') {
12045: 	    return $ENV{'SERVER_NAME'};
12046:         }
12047:     }
12048:     return '';
12049: }
12050: 
12051: sub get_reply {
12052:     my ($reply_value) = @_;
12053:     if (ref($reply_value) eq 'ARRAY') {
12054:         if (wantarray) {
12055: 	    return @$reply_value;
12056:         }
12057:         return $reply_value->[0];
12058:     } else {
12059:         return $reply_value;
12060:     }
12061: }
12062: 
12063: sub check_group_parms {
12064:     my ($courseid,$groups,$symbparm,$recurseparm,$mapparm,$what,$mapp,
12065:         $recursed,$recurseupref) = @_;
12066:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$recurseparm,'map'],
12067:                   [$what,'course']);
12068:     my $coursereply;
12069:     foreach my $group (@{$groups}) {
12070:         my @groupitems = ();
12071:         foreach my $level (@levels) {
12072:              my $item = $courseid.'.['.$group.'].'.$level->[0];
12073:              push(@groupitems,[$item,$level->[1]]);
12074:         }
12075:         my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
12076:                                    $env{'course.'.$courseid.'.domain'},
12077:                                    'course',$mapp,$recursed,$recurseupref,
12078:                                    $courseid,'.['.$group.'].',$what,
12079:                                    @groupitems);
12080:         last if (defined($coursereply));
12081:     }
12082:     return $coursereply;
12083: }
12084: 
12085: sub get_map_hierarchy {
12086:     my ($mapname,$courseid) = @_;
12087:     my @recurseup = ();
12088:     if ($mapname) {
12089:         if (($cachedmapkey eq $courseid) &&
12090:             (abs($cachedmaptime-time)<5)) {
12091:             if (ref($cachedmaps{$mapname}) eq 'ARRAY') {
12092:                 return @{$cachedmaps{$mapname}};
12093:             }
12094:         }
12095:         my $navmap = Apache::lonnavmaps::navmap->new();
12096:         if (ref($navmap)) {
12097:             @recurseup = $navmap->recurseup_maps($mapname);
12098:             undef($navmap);
12099:             $cachedmaps{$mapname} = \@recurseup;
12100:             $cachedmaptime=time;
12101:             $cachedmapkey=$courseid;
12102:         }
12103:     }
12104:     return @recurseup;
12105: }
12106: 
12107: }
12108: 
12109: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
12110:     my ($courseid,@groups) = @_;
12111:     @groups = sort(@groups);
12112:     return @groups;
12113: }
12114: 
12115: sub packages_tab_default {
12116:     my ($uri,$varname,$toolsymb)=@_;
12117:     my (undef,$part,$name)=split(/\./,$varname);
12118: 
12119:     my (@extension,@specifics,$do_default);
12120:     foreach my $package (split(/,/,&metadata($uri,'packages',$toolsymb))) {
12121: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
12122: 	if ($pack_type eq 'default') {
12123: 	    $do_default=1;
12124: 	} elsif ($pack_type eq 'extension') {
12125: 	    push(@extension,[$package,$pack_type,$pack_part]);
12126: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
12127: 	    # only look at packages defaults for packages that this id is
12128: 	    push(@specifics,[$package,$pack_type,$pack_part]);
12129: 	}
12130:     }
12131:     # first look for a package that matches the requested part id
12132:     foreach my $package (@specifics) {
12133: 	my (undef,$pack_type,$pack_part)=@{$package};
12134: 	next if ($pack_part ne $part);
12135: 	if (defined($packagetab{"$pack_type&$name&default"})) {
12136: 	    return $packagetab{"$pack_type&$name&default"};
12137: 	}
12138:     }
12139:     # look for any possible matching non extension_ package
12140:     foreach my $package (@specifics) {
12141: 	my (undef,$pack_type,$pack_part)=@{$package};
12142: 	if (defined($packagetab{"$pack_type&$name&default"})) {
12143: 	    return $packagetab{"$pack_type&$name&default"};
12144: 	}
12145: 	if ($pack_type eq 'part') { $pack_part='0'; }
12146: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
12147: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
12148: 	}
12149:     }
12150:     # look for any posible extension_ match
12151:     foreach my $package (@extension) {
12152: 	my ($package,$pack_type)=@{$package};
12153: 	if (defined($packagetab{"$pack_type&$name&default"})) {
12154: 	    return $packagetab{"$pack_type&$name&default"};
12155: 	}
12156: 	if (defined($packagetab{$package."&$name&default"})) {
12157: 	    return $packagetab{$package."&$name&default"};
12158: 	}
12159:     }
12160:     # look for a global default setting
12161:     if ($do_default && defined($packagetab{"default&$name&default"})) {
12162: 	return $packagetab{"default&$name&default"};
12163:     }
12164:     return undef;
12165: }
12166: 
12167: sub add_prefix_and_part {
12168:     my ($prefix,$part)=@_;
12169:     my $keyroot;
12170:     if (defined($prefix) && $prefix !~ /^__/) {
12171: 	# prefix that has a part already
12172: 	$keyroot=$prefix;
12173:     } elsif (defined($prefix)) {
12174: 	# prefix that is missing a part
12175: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
12176:     } else {
12177: 	# no prefix at all
12178: 	if (defined($part)) { $keyroot='_'.$part; }
12179:     }
12180:     return $keyroot;
12181: }
12182: 
12183: # ---------------------------------------------------------------- Get metadata
12184: 
12185: my %metaentry;
12186: my %importedpartids;
12187: my %importedrespids;
12188: sub metadata {
12189:     my ($uri,$what,$toolsymb,$liburi,$prefix,$depthcount)=@_;
12190:     $uri=&declutter($uri);
12191:     # if it is a non metadata possible uri return quickly
12192:     if (($uri eq '') || 
12193: 	(($uri =~ m|^/*adm/|) && 
12194: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard|ext\.tool)$})) ||
12195:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
12196: 	return undef;
12197:     }
12198:     if (($uri =~ /^priv/ || $uri=~m{^home/httpd/html/priv}) 
12199: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
12200: 	return undef;
12201:     }
12202:     my $filename=$uri;
12203:     $uri=~s/\.meta$//;
12204: #
12205: # Is the metadata already cached?
12206: # Look at timestamp of caching
12207: # Everything is cached by the main uri, libraries are never directly cached
12208: #
12209:     if (!defined($liburi)) {
12210: 	my ($result,$cached)=&is_cached_new('meta',$uri);
12211: 	if (defined($cached)) { return $result->{':'.$what}; }
12212:     }
12213: 
12214: #
12215: # If the uri is for an external tool the file from
12216: # which metadata should be retrieved depends on whether
12217: # the tool had been configured to be gradable (set in the Course
12218: # Editor or Resource Editor).
12219: #
12220: # If a valid symb has been included as the third arg in the call
12221: # to &metadata() that can be used to retrieve the value of
12222: # parameter_0_gradable set for the resource, and included in the
12223: # uploaded map containing the tool. The value is retrieved via
12224: # &EXT(), if a valid symb is available.  Otherwise the value of
12225: # gradable in the exttool_$marker.db file for the tool instance
12226: # is retrieved via &get().
12227: #
12228: # When lonuserstate::traceroute() calls lonnet::EXT() for 
12229: # hiddenresource and encrypturl (during course initialization)
12230: # the map-level parameter for resource.0.gradable included in the 
12231: # uploaded map containing the tool will not yet have been stored
12232: # in the user_course_parms.db file for the user's session, so in 
12233: # this case fall back to retrieving gradable status from the
12234: # exttool_$marker.db file.
12235: #
12236: # In order to avoid an infinite loop, &metadata() will return
12237: # before a call to &EXT(), if the uri is for an external tool
12238: # and the $what for which metadata is being requested is
12239: # parameter_0_gradable or 0_gradable.
12240: #
12241: 
12242:     if ($uri =~ /ext\.tool$/) {
12243:         if (($what eq 'parameter_0_gradable') || ($what eq '0_gradable')) {
12244:             return;
12245:         } else {
12246:             my ($checked,$use_passback);
12247:             if ($toolsymb ne '') {
12248:                 (undef,undef,my $tooluri) = &decode_symb($toolsymb);
12249:                 if (($tooluri eq $uri) && (&EXT('resource.0.gradable',$toolsymb))) {
12250:                     $checked = 1;
12251:                     if (&EXT('resource.0.gradable',$toolsymb) =~ /^yes$/i) {
12252:                         $use_passback = 1;
12253:                     }
12254:                 }
12255:             }
12256:             unless ($checked) {
12257:                 my ($ignore,$cdom,$cnum,$marker) = split(m{/},$uri);
12258:                 $marker=~s/\D//g;
12259:                 if ($marker) {
12260:                     my %toolsettings=&get('exttool_'.$marker,['gradable'],$cdom,$cnum);
12261:                     $use_passback = $toolsettings{'gradable'};
12262:                 }
12263:             }
12264:             if ($use_passback) {
12265:                 $filename = '/home/httpd/html/res/lib/templates/LTIpassback.tool';
12266:             } else {
12267:                 $filename = '/home/httpd/html/res/lib/templates/LTIstandard.tool';
12268:             }
12269:         }
12270:     }
12271: 
12272:     {
12273: # Imported parts would go here
12274:         my @origfiletagids=();
12275:         my $importedparts=0;
12276: 
12277: # Imported responseids would go here
12278:         my $importedresponses=0;
12279: #
12280: # Is this a recursive call for a library?
12281: #
12282: #	if (! exists($metacache{$uri})) {
12283: #	    $metacache{$uri}={};
12284: #	}
12285: 	my $cachetime = 60*60;
12286:         if ($liburi) {
12287: 	    $liburi=&declutter($liburi);
12288:             $filename=$liburi;
12289:         } else {
12290: 	    &devalidate_cache_new('meta',$uri);
12291: 	    undef(%metaentry);
12292: 	}
12293:         my %metathesekeys=();
12294:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
12295: 	my $metastring;
12296: 	if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
12297: 	    my $which = &hreflocation('','/'.($liburi || $uri));
12298: 	    $metastring = 
12299: 		&Apache::lonnet::ssi_body($which,
12300: 					  ('grade_target' => 'meta'));
12301: 	    $cachetime = 1; # only want this cached in the child not long term
12302: 	} elsif (($uri !~ m -^(editupload)/-) && 
12303:                  ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
12304: 	    my $file=&filelocation('',&clutter($filename));
12305: 	    #push(@{$metaentry{$uri.'.file'}},$file);
12306: 	    $metastring=&getfile($file);
12307: 	}
12308:         my $parser=HTML::LCParser->new(\$metastring);
12309:         my $token;
12310:         undef %metathesekeys;
12311:         while ($token=$parser->get_token) {
12312: 	    if ($token->[0] eq 'S') {
12313: 		if (defined($token->[2]->{'package'})) {
12314: #
12315: # This is a package - get package info
12316: #
12317: 		    my $package=$token->[2]->{'package'};
12318: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
12319: 		    if (defined($token->[2]->{'id'})) { 
12320: 			$keyroot.='_'.$token->[2]->{'id'}; 
12321: 		    }
12322: 		    if ($metaentry{':packages'}) {
12323: 			$metaentry{':packages'}.=','.$package.$keyroot;
12324: 		    } else {
12325: 			$metaentry{':packages'}=$package.$keyroot;
12326: 		    }
12327: 		    foreach my $pack_entry (keys(%packagetab)) {
12328: 			my $part=$keyroot;
12329: 			$part=~s/^\_//;
12330: 			if ($pack_entry=~/^\Q$package\E\&/ || 
12331: 			    $pack_entry=~/^\Q$package\E_0\&/) {
12332: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
12333: 			    # ignore package.tab specified default values
12334:                             # here &package_tab_default() will fetch those
12335: 			    if ($subp eq 'default') { next; }
12336: 			    my $value=$packagetab{$pack_entry};
12337: 			    my $unikey;
12338: 			    if ($pack =~ /_0$/) {
12339: 				$unikey='parameter_0_'.$name;
12340: 				$part=0;
12341: 			    } else {
12342: 				$unikey='parameter'.$keyroot.'_'.$name;
12343: 			    }
12344: 			    if ($subp eq 'display') {
12345: 				$value.=' [Part: '.$part.']';
12346: 			    }
12347: 			    $metaentry{':'.$unikey.'.part'}=$part;
12348: 			    $metathesekeys{$unikey}=1;
12349: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
12350: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
12351: 			    }
12352: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
12353: 				$metaentry{':'.$unikey}=
12354: 				    $metaentry{':'.$unikey.'.default'};
12355: 			    }
12356: 			}
12357: 		    }
12358: 		} else {
12359: #
12360: # This is not a package - some other kind of start tag
12361: #
12362: 		    my $entry=$token->[1];
12363: 		    my $unikey='';
12364: 
12365: 		    if ($entry eq 'import') {
12366: #
12367: # Importing a library here
12368: #
12369:                         my $location=$parser->get_text('/import');
12370:                         my $dir=$filename;
12371:                         $dir=~s|[^/]*$||;
12372:                         $location=&filelocation($dir,$location);
12373: 
12374:                         my $importid=$token->[2]->{'id'};
12375:                         my $importmode=$token->[2]->{'importmode'};
12376: #
12377: # Check metadata for imported file to
12378: # see if it contained response items
12379: #
12380:                         my ($origfile,@libfilekeys);
12381:                         my %currmetaentry = %metaentry;
12382:                         @libfilekeys = split(/,/,&metadata($location,'keys',undef,undef,undef,
12383:                                                            $depthcount+1));
12384:                         if (grep(/^responseorder$/,@libfilekeys)) {
12385:                             my $libresponseorder = &metadata($location,'responseorder',undef,undef,
12386:                                                              undef,$depthcount+1);
12387:                             if ($libresponseorder ne '') {
12388:                                 if ($#origfiletagids<0) {
12389:                                     undef(%importedrespids);
12390:                                     undef(%importedpartids);
12391:                                 }
12392:                                 my @respids = split(/\s*,\s*/,$libresponseorder);
12393:                                 if (@respids) {
12394:                                     $importedrespids{$importid} = join(',',map { $importid.'_'.$_ } @respids);
12395:                                 }
12396:                                 if ($importedrespids{$importid} ne '') {
12397:                                     $importedresponses = 1;
12398: # We need to get the original file and the imported file to get the response order correct
12399: # Load and inspect original file
12400:                                     if ($#origfiletagids<0) {
12401:                                         my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
12402:                                         $origfile=&getfile($origfilelocation);
12403:                                         @origfiletagids=($origfile=~/<((?:\w+)response|import|part)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
12404:                                     }
12405:                                 }
12406:                             }
12407:                         }
12408: # Do not overwrite contents of %metaentry hash for resource itself with 
12409: # hash populated for imported library file
12410:                         %metaentry = %currmetaentry;
12411:                         undef(%currmetaentry);
12412:                         if ($importmode eq 'part') {
12413: # Import as part(s)
12414:                            $importedparts=1;
12415: # We need to get the original file and the imported file to get the part order correct
12416: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
12417: # Load and inspect original file if we didn't do that already
12418:                            if ($#origfiletagids<0) {
12419:                                undef(%importedrespids);
12420:                                undef(%importedpartids);
12421:                                if ($origfile eq '') {
12422:                                    my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
12423:                                    $origfile=&getfile($origfilelocation);
12424:                                    @origfiletagids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
12425:                                }
12426:                            }
12427:                            my @impfilepartids;
12428: # If <partorder> tag is included in metadata for the imported file
12429: # get the parts in the imported file from that.
12430:                            if (grep(/^partorder$/,@libfilekeys)) {
12431:                                %currmetaentry = %metaentry;
12432:                                my $libpartorder = &metadata($location,'partorder',undef,undef,undef,
12433:                                                             $depthcount+1);
12434:                                %metaentry = %currmetaentry;
12435:                                undef(%currmetaentry);
12436:                                if ($libpartorder ne '') {
12437:                                    @impfilepartids=split(/\s*,\s*/,$libpartorder);
12438:                                }
12439:                            } else {
12440: # If no <partorder> tag available, load and inspect imported file
12441:                                my $impfile=&getfile($location);
12442:                                @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
12443:                            }
12444:                            if ($#impfilepartids>=0) {
12445: # This problem had parts
12446:                                $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
12447:                            } else {
12448: # Importing by turning a single problem into a problem part
12449: # It gets the import-tags ID as part-ID
12450:                                $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
12451:                                $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
12452:                            }
12453:                         } else {
12454: # Import as problem or as normal import
12455:                             $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
12456:                             unless ($importmode eq 'problem') {
12457: # Normal import
12458:                                 if (defined($token->[2]->{'id'})) {
12459:                                     $unikey.='_'.$token->[2]->{'id'};
12460:                                 }
12461:                             }
12462: # Check metadata for imported file to
12463: # see if it contained parts
12464:                             if (grep(/^partorder$/,@libfilekeys)) {
12465:                                 %currmetaentry = %metaentry;
12466:                                 my $libpartorder = &metadata($location,'partorder',undef,undef,undef,
12467:                                                              $depthcount+1);
12468:                                 %metaentry = %currmetaentry;
12469:                                 undef(%currmetaentry);
12470:                                 if ($libpartorder ne '') {
12471:                                     $importedparts = 1;
12472:                                     $importedpartids{$token->[2]->{'id'}}=$libpartorder;
12473:                                 }
12474:                             }
12475:                         }
12476: 			if ($depthcount<20) {
12477: 			    my $metadata = 
12478: 				&metadata($uri,'keys',$toolsymb,$location,$unikey,
12479: 					  $depthcount+1);
12480: 			    foreach my $meta (split(',',$metadata)) {
12481: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
12482: 				$metathesekeys{$meta}=1;
12483: 			    }
12484:                         }
12485: 		    } else {
12486: #
12487: # Not importing, some other kind of non-package, non-library start tag
12488: # 
12489:                         $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
12490:                         if (defined($token->[2]->{'id'})) {
12491:                             $unikey.='_'.$token->[2]->{'id'};
12492:                         }
12493: 			if (defined($token->[2]->{'name'})) { 
12494: 			    $unikey.='_'.$token->[2]->{'name'}; 
12495: 			}
12496: 			$metathesekeys{$unikey}=1;
12497: 			foreach my $param (@{$token->[3]}) {
12498: 			    $metaentry{':'.$unikey.'.'.$param} =
12499: 				$token->[2]->{$param};
12500: 			}
12501: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
12502: 			my $default=$metaentry{':'.$unikey.'.default'};
12503: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
12504: 		 # only ws inside the tag, and not in default, so use default
12505: 		 # as value
12506: 			    $metaentry{':'.$unikey}=$default;
12507: 			} elsif ( $internaltext =~ /\S/ ) {
12508: 		  # something interesting inside the tag
12509: 			    $metaentry{':'.$unikey}=$internaltext;
12510: 			} else {
12511: 		  # no interesting values, don't set a default
12512: 			}
12513: # end of not-a-package not-a-library import
12514: 		    }
12515: # end of not-a-package start tag
12516: 		}
12517: # the next is the end of "start tag"
12518: 	    }
12519: 	}
12520: 	my ($extension) = ($uri =~ /\.(\w+)$/);
12521: 	$extension = lc($extension);
12522: 	if ($extension eq 'htm') { $extension='html'; }
12523: 
12524: 	foreach my $key (keys(%packagetab)) {
12525: 	    #no specific packages #how's our extension
12526: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
12527: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
12528: 					 \%metathesekeys);
12529: 	}
12530: 
12531: 	if (!exists($metaentry{':packages'})
12532: 	    || $packagetab{"import_defaults&extension_$extension"}) {
12533: 	    foreach my $key (keys(%packagetab)) {
12534: 		#no specific packages well let's get default then
12535: 		if ($key!~/^default&/) { next; }
12536: 		&metadata_create_package_def($uri,$key,'default',
12537: 					     \%metathesekeys);
12538: 	    }
12539: 	}
12540: # are there custom rights to evaluate
12541: 	if ($metaentry{':copyright'} eq 'custom') {
12542: 
12543:     #
12544:     # Importing a rights file here
12545:     #
12546: 	    unless ($depthcount) {
12547: 		my $location=$metaentry{':customdistributionfile'};
12548: 		my $dir=$filename;
12549: 		$dir=~s|[^/]*$||;
12550: 		$location=&filelocation($dir,$location);
12551: 		my $rights_metadata =
12552: 		    &metadata($uri,'keys',$toolsymb,$location,'_rights',
12553: 			      $depthcount+1);
12554: 		foreach my $rights (split(',',$rights_metadata)) {
12555: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
12556: 		    $metathesekeys{$rights}=1;
12557: 		}
12558: 	    }
12559: 	}
12560: 	# uniqifiy package listing
12561: 	my %seen;
12562: 	my @uniq_packages =
12563: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
12564: 	$metaentry{':packages'} = join(',',@uniq_packages);
12565: 
12566:         if (($importedresponses) || ($importedparts)) {
12567:             if ($importedparts) {
12568: # We had imported parts and need to rebuild partorder
12569:                 $metaentry{':partorder'}='';
12570:                 $metathesekeys{'partorder'}=1;
12571:             }
12572:             if ($importedresponses) {
12573: # We had imported responses and need to rebuil responseorder
12574:                 $metaentry{':responseorder'}='';
12575:                 $metathesekeys{'responseorder'}=1;
12576:             }
12577:             for (my $index=0;$index<$#origfiletagids;$index+=2) {
12578:                 my $origid = $origfiletagids[$index+1];
12579:                 if ($origfiletagids[$index] eq 'part') {
12580: # Original part, part of the problem
12581:                     if ($importedparts) {
12582:                         $metaentry{':partorder'}.=','.$origid;
12583:                     }
12584:                 } elsif ($origfiletagids[$index] eq 'import') {
12585:                     if ($importedparts) {
12586: # We have imported parts at this position
12587:                         if ($importedpartids{$origid} ne '') {
12588:                             $metaentry{':partorder'}.=','.$importedpartids{$origid};
12589:                         }
12590:                     }
12591:                     if ($importedresponses) {
12592: # We have imported responses at this position
12593:                         if ($importedrespids{$origid} ne '') {
12594:                             $metaentry{':responseorder'}.=','.$importedrespids{$origid};
12595:                         }
12596:                     }
12597:                 } else {
12598: # Original response item, part of the problem
12599:                     if ($importedresponses) {
12600:                         $metaentry{':responseorder'}.=','.$origid;
12601:                     }
12602:                 }
12603:             }
12604:             if ($importedparts) {
12605:                 $metaentry{':partorder'}=~s/^\,//;
12606:             }
12607:             if ($importedresponses) {
12608:                 $metaentry{':responseorder'}=~s/^\,//;
12609:             }
12610:         }
12611: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
12612: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
12613: 	$metaentry{':allpossiblekeys'}=join(',',keys(%metathesekeys));
12614:         unless ($liburi) {
12615: 	    &do_cache_new('meta',$uri,\%metaentry,$cachetime);
12616:         }
12617: # this is the end of "was not already recently cached
12618:     }
12619:     return $metaentry{':'.$what};
12620: }
12621: 
12622: sub metadata_create_package_def {
12623:     my ($uri,$key,$package,$metathesekeys)=@_;
12624:     my ($pack,$name,$subp)=split(/\&/,$key);
12625:     if ($subp eq 'default') { next; }
12626:     
12627:     if (defined($metaentry{':packages'})) {
12628: 	$metaentry{':packages'}.=','.$package;
12629:     } else {
12630: 	$metaentry{':packages'}=$package;
12631:     }
12632:     my $value=$packagetab{$key};
12633:     my $unikey;
12634:     $unikey='parameter_0_'.$name;
12635:     $metaentry{':'.$unikey.'.part'}=0;
12636:     $$metathesekeys{$unikey}=1;
12637:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
12638: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
12639:     }
12640:     if (defined($metaentry{':'.$unikey.'.default'})) {
12641: 	$metaentry{':'.$unikey}=
12642: 	    $metaentry{':'.$unikey.'.default'};
12643:     }
12644: }
12645: 
12646: sub metadata_generate_part0 {
12647:     my ($metadata,$metacache,$uri) = @_;
12648:     my %allnames;
12649:     foreach my $metakey (keys(%$metadata)) {
12650: 	if ($metakey=~/^parameter\_(.*)/) {
12651: 	  my $part=$$metacache{':'.$metakey.'.part'};
12652: 	  my $name=$$metacache{':'.$metakey.'.name'};
12653: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
12654: 	    $allnames{$name}=$part;
12655: 	  }
12656: 	}
12657:     }
12658:     foreach my $name (keys(%allnames)) {
12659:       $$metadata{"parameter_0_$name"}=1;
12660:       my $key=":parameter_0_$name";
12661:       $$metacache{"$key.part"}='0';
12662:       $$metacache{"$key.name"}=$name;
12663:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
12664: 					   $allnames{$name}.'_'.$name.
12665: 					   '.type'};
12666:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
12667: 			     '.display'};
12668:       my $expr='[Part: '.$allnames{$name}.']';
12669:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
12670:       $$metacache{"$key.display"}=$olddis;
12671:     }
12672: }
12673: 
12674: # ------------------------------------------------------ Devalidate title cache
12675: 
12676: sub devalidate_title_cache {
12677:     my ($url)=@_;
12678:     if (!$env{'request.course.id'}) { return; }
12679:     my $symb=&symbread($url);
12680:     if (!$symb) { return; }
12681:     my $key=$env{'request.course.id'}."\0".$symb;
12682:     &devalidate_cache_new('title',$key);
12683: }
12684: 
12685: # ------------------------------------------------- Get the title of a course
12686: 
12687: sub current_course_title {
12688:     return $env{ 'course.' . $env{'request.course.id'} . '.description' };
12689: }
12690: # ------------------------------------------------- Get the title of a resource
12691: 
12692: sub gettitle {
12693:     my $urlsymb=shift;
12694:     my $symb=&symbread($urlsymb);
12695:     if ($symb) {
12696: 	my $key=$env{'request.course.id'}."\0".$symb;
12697: 	my ($result,$cached)=&is_cached_new('title',$key);
12698: 	if (defined($cached)) { 
12699: 	    return $result;
12700: 	}
12701: 	my ($map,$resid,$url)=&decode_symb($symb);
12702: 	my $title='';
12703: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
12704: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
12705: 	} else {
12706: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
12707: 		    &GDBM_READER(),0640)) {
12708: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
12709: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
12710: 		untie(%bighash);
12711: 	    }
12712: 	}
12713: 	$title=~s/\&colon\;/\:/gs;
12714: 	if ($title) {
12715: # Remember both $symb and $title for dynamic metadata
12716:             $accesshash{$symb.'___crstitle'}=$title;
12717:             $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
12718: # Cache this title and then return it
12719: 	    return &do_cache_new('title',$key,$title,600);
12720: 	}
12721: 	$urlsymb=$url;
12722:     }
12723:     my $title=&metadata($urlsymb,'title');
12724:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
12725:     return $title;
12726: }
12727: 
12728: sub get_slot {
12729:     my ($which,$cnum,$cdom)=@_;
12730:     if (!$cnum || !$cdom) {
12731: 	(undef,my $courseid)=&whichuser();
12732: 	$cdom=$env{'course.'.$courseid.'.domain'};
12733: 	$cnum=$env{'course.'.$courseid.'.num'};
12734:     }
12735:     my $key=join("\0",'slots',$cdom,$cnum,$which);
12736:     my %slotinfo;
12737:     if (exists($remembered{$key})) {
12738: 	$slotinfo{$which} = $remembered{$key};
12739:     } else {
12740: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
12741: 	&Apache::lonhomework::showhash(%slotinfo);
12742: 	my ($tmp)=keys(%slotinfo);
12743: 	if ($tmp=~/^error:/) { return (); }
12744: 	$remembered{$key} = $slotinfo{$which};
12745:     }
12746:     if (ref($slotinfo{$which}) eq 'HASH') {
12747: 	return %{$slotinfo{$which}};
12748:     }
12749:     return $slotinfo{$which};
12750: }
12751: 
12752: sub get_reservable_slots {
12753:     my ($cnum,$cdom,$uname,$udom) = @_;
12754:     my $now = time;
12755:     my $reservable_info;
12756:     my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
12757:     if (exists($remembered{$key})) {
12758:         $reservable_info = $remembered{$key};
12759:     } else {
12760:         my %resv;
12761:         ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
12762:         &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
12763:         $reservable_info = \%resv;
12764:         $remembered{$key} = $reservable_info;
12765:     }
12766:     return $reservable_info;
12767: }
12768: 
12769: sub get_course_slots {
12770:     my ($cnum,$cdom) = @_;
12771:     my $hashid=$cnum.':'.$cdom;
12772:     my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
12773:     if (defined($cached)) {
12774:         if (ref($result) eq 'HASH') {
12775:             return %{$result};
12776:         }
12777:     } else {
12778:         my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
12779:         my ($tmp) = keys(%slots);
12780:         if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
12781:             &do_cache_new('allslots',$hashid,\%slots,600);
12782:             return %slots;
12783:         }
12784:     }
12785:     return;
12786: }
12787: 
12788: sub devalidate_slots_cache {
12789:     my ($cnum,$cdom)=@_;
12790:     my $hashid=$cnum.':'.$cdom;
12791:     &devalidate_cache_new('allslots',$hashid);
12792: }
12793: 
12794: sub get_coursechange {
12795:     my ($cdom,$cnum) = @_;
12796:     if ($cdom eq '' || $cnum eq '') {
12797:         return unless ($env{'request.course.id'});
12798:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
12799:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
12800:     }
12801:     my $hashid=$cdom.'_'.$cnum;
12802:     my ($change,$cached)=&is_cached_new('crschange',$hashid);
12803:     if ((defined($cached)) && ($change ne '')) {
12804:         return $change;
12805:     } else {
12806:         my %crshash;
12807:         %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
12808:         if ($crshash{'internal.contentchange'} eq '') {
12809:             $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
12810:             if ($change eq '') {
12811:                 %crshash = &get('environment',['internal.created'],$cdom,$cnum);
12812:                 $change = $crshash{'internal.created'};
12813:             }
12814:         } else {
12815:             $change = $crshash{'internal.contentchange'};
12816:         }
12817:         my $cachetime = 600;
12818:         &do_cache_new('crschange',$hashid,$change,$cachetime);
12819:     }
12820:     return $change;
12821: }
12822: 
12823: sub devalidate_coursechange_cache {
12824:     my ($cnum,$cdom)=@_;
12825:     my $hashid=$cnum.':'.$cdom;
12826:     &devalidate_cache_new('crschange',$hashid);
12827: }
12828: 
12829: # ------------------------------------------------- Update symbolic store links
12830: 
12831: sub symblist {
12832:     my ($mapname,%newhash)=@_;
12833:     $mapname=&deversion(&declutter($mapname));
12834:     my %hash;
12835:     if (($env{'request.course.fn'}) && (%newhash)) {
12836:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
12837:                       &GDBM_WRCREAT(),0640)) {
12838: 	    foreach my $url (keys(%newhash)) {
12839: 		next if ($url eq 'last_known'
12840: 			 && $env{'form.no_update_last_known'});
12841: 		$hash{declutter($url)}=&encode_symb($mapname,
12842: 						    $newhash{$url}->[1],
12843: 						    $newhash{$url}->[0]);
12844:             }
12845:             if (untie(%hash)) {
12846: 		return 'ok';
12847:             }
12848:         }
12849:     }
12850:     return 'error';
12851: }
12852: 
12853: # --------------------------------------------------------------- Verify a symb
12854: 
12855: sub symbverify {
12856:     my ($symb,$thisurl,$encstate)=@_;
12857:     my $thisfn=$thisurl;
12858:     $thisfn=&declutter($thisfn);
12859: # direct jump to resource in page or to a sequence - will construct own symbs
12860:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
12861: # check URL part
12862:     my ($map,$resid,$url)=&decode_symb($symb);
12863: 
12864:     unless ($url eq $thisfn) { return 0; }
12865: 
12866:     $symb=&symbclean($symb);
12867:     $thisurl=&deversion($thisurl);
12868:     $thisfn=&deversion($thisfn);
12869: 
12870:     my %bighash;
12871:     my $okay=0;
12872: 
12873:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
12874:                             &GDBM_READER(),0640)) {
12875:         my $noclutter;
12876:         if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
12877:             $thisurl =~ s/\?.+$//;
12878:             if ($map =~ m{^uploaded/.+\.page$}) {
12879:                 $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
12880:                 $thisurl =~ s{^\Qhttp://https://\E}{https://};
12881:                 $noclutter = 1;
12882:             }
12883:         }
12884:         my $ids;
12885:         if ($noclutter) {
12886:             $ids=$bighash{'ids_'.$thisurl};
12887:         } else {
12888:             $ids=$bighash{'ids_'.&clutter($thisurl)};
12889:         }
12890:         unless ($ids) {
12891:             my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;  
12892:             $ids=$bighash{$idkey};
12893:         }
12894:         if ($ids) {
12895: # ------------------------------------------------------------------- Has ID(s)
12896:             if ($thisfn =~ m{^/adm/wrapper/ext/}) {
12897:                 $symb =~ s/\?.+$//;
12898:             }
12899: 	    foreach my $id (split(/\,/,$ids)) {
12900: 	       my ($mapid,$resid)=split(/\./,$id);
12901:                if (
12902:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
12903:    eq $symb) {
12904:                    if (ref($encstate)) {
12905:                        $$encstate = $bighash{'encrypted_'.$id};
12906:                    }
12907: 		   if (($env{'request.role.adv'}) ||
12908: 		       ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
12909:                        ($thisurl eq '/adm/navmaps')) {
12910: 		       $okay=1;
12911:                        last;
12912: 		   }
12913: 	       }
12914: 	   }
12915:         }
12916: 	untie(%bighash);
12917:     }
12918:     return $okay;
12919: }
12920: 
12921: # --------------------------------------------------------------- Clean-up symb
12922: 
12923: sub symbclean {
12924:     my $symb=shift;
12925:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
12926: # remove version from map
12927:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
12928: 
12929: # remove version from URL
12930:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
12931: 
12932: # remove wrapper
12933: 
12934:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
12935:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
12936:     return $symb;
12937: }
12938: 
12939: # ---------------------------------------------- Split symb to find map and url
12940: 
12941: sub encode_symb {
12942:     my ($map,$resid,$url)=@_;
12943:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
12944: }
12945: 
12946: sub decode_symb {
12947:     my $symb=shift;
12948:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
12949:     my ($map,$resid,$url)=split(/___/,$symb);
12950:     return (&fixversion($map),$resid,&fixversion($url));
12951: }
12952: 
12953: sub fixversion {
12954:     my $fn=shift;
12955:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
12956:     my %bighash;
12957:     my $uri=&clutter($fn);
12958:     my $key=$env{'request.course.id'}.'_'.$uri;
12959: # is this cached?
12960:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
12961:     if (defined($cached)) { return $result; }
12962: # unfortunately not cached, or expired
12963:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
12964: 	    &GDBM_READER(),0640)) {
12965:  	if ($bighash{'version_'.$uri}) {
12966:  	    my $version=$bighash{'version_'.$uri};
12967:  	    unless (($version eq 'mostrecent') || 
12968: 		    ($version==&getversion($uri))) {
12969:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
12970:  	    }
12971:  	}
12972:  	untie %bighash;
12973:     }
12974:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
12975: }
12976: 
12977: sub deversion {
12978:     my $url=shift;
12979:     $url=~s/\.\d+\.(\w+)$/\.$1/;
12980:     return $url;
12981: }
12982: 
12983: # ------------------------------------------------------ Return symb list entry
12984: 
12985: sub symbread {
12986:     my ($thisfn,$donotrecurse,$ignorecachednull,$checkforblock,$possibles)=@_;
12987:     my $cache_str='request.symbread.cached.'.$thisfn;
12988:     if (defined($env{$cache_str})) {
12989:         if ($ignorecachednull) {
12990:             return $env{$cache_str} unless ($env{$cache_str} eq '');
12991:         } else {
12992:             return $env{$cache_str};
12993:         }
12994:     }
12995: # no filename provided? try from environment
12996:     unless ($thisfn) {
12997:         if ($env{'request.symb'}) {
12998: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
12999: 	}
13000: 	$thisfn=$env{'request.filename'};
13001:     }
13002:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
13003: # is that filename actually a symb? Verify, clean, and return
13004:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
13005: 	if (&symbverify($thisfn,$1)) {
13006: 	    return $env{$cache_str}=&symbclean($thisfn);
13007: 	}
13008:     }
13009:     $thisfn=declutter($thisfn);
13010:     my %hash;
13011:     my %bighash;
13012:     my $syval='';
13013:     if (($env{'request.course.fn'}) && ($thisfn)) {
13014:         my $targetfn = $thisfn;
13015:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
13016:             $targetfn = 'adm/wrapper/'.$thisfn;
13017:         }
13018: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
13019: 	    $targetfn=$1;
13020: 	}
13021:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
13022:                       &GDBM_READER(),0640)) {
13023: 	    $syval=$hash{$targetfn};
13024:             untie(%hash);
13025:         }
13026: # ---------------------------------------------------------- There was an entry
13027:         if ($syval) {
13028: 	    #unless ($syval=~/\_\d+$/) {
13029: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
13030: 		    #&appenv({'request.ambiguous' => $thisfn});
13031: 		    #return $env{$cache_str}='';
13032: 		#}    
13033: 		#$syval.=$1;
13034: 	    #}
13035:         } else {
13036: # ------------------------------------------------------- Was not in symb table
13037:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
13038:                             &GDBM_READER(),0640)) {
13039: # ---------------------------------------------- Get ID(s) for current resource
13040:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
13041:               unless ($ids) { 
13042:                  $ids=$bighash{'ids_/'.$thisfn};
13043:               }
13044:               unless ($ids) {
13045: # alias?
13046: 		  $ids=$bighash{'mapalias_'.$thisfn};
13047:               }
13048:               if ($ids) {
13049: # ------------------------------------------------------------------- Has ID(s)
13050:                  my @possibilities=split(/\,/,$ids);
13051:                  if ($#possibilities==0) {
13052: # ----------------------------------------------- There is only one possibility
13053: 		     my ($mapid,$resid)=split(/\./,$ids);
13054: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
13055: 						    $resid,$thisfn);
13056:                      if (ref($possibles) eq 'HASH') {
13057:                          $possibles->{$syval} = 1;    
13058:                      }
13059:                      if ($checkforblock) {
13060:                          my @blockers = &has_comm_blocking('bre',$syval,$bighash{'src_'.$ids});
13061:                          if (@blockers) {
13062:                              $syval = '';
13063:                              return;
13064:                          }
13065:                      }
13066:                  } elsif ((!$donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) { 
13067: # ------------------------------------------ There is more than one possibility
13068:                      my $realpossible=0;
13069:                      foreach my $id (@possibilities) {
13070: 			 my $file=$bighash{'src_'.$id};
13071:                          my $canaccess;
13072:                          if (($donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
13073:                              $canaccess = 1;
13074:                          } else { 
13075:                              $canaccess = &allowed('bre',$file);
13076:                          }
13077:                          if ($canaccess) {
13078:          		     my ($mapid,$resid)=split(/\./,$id);
13079:                              if ($bighash{'map_type_'.$mapid} ne 'page') {
13080:                                  my $poss_syval=&encode_symb($bighash{'map_id_'.$mapid},
13081: 						             $resid,$thisfn);
13082:                                  if (ref($possibles) eq 'HASH') {
13083:                                      $possibles->{$syval} = 1;
13084:                                  }
13085:                                  if ($checkforblock) {
13086:                                      my @blockers = &has_comm_blocking('bre',$poss_syval,$file);
13087:                                      unless (@blockers > 0) {
13088:                                          $syval = $poss_syval;
13089:                                          $realpossible++;
13090:                                      }
13091:                                  } else {
13092:                                      $syval = $poss_syval;
13093:                                      $realpossible++;
13094:                                  }
13095:                              }
13096: 			 }
13097:                      }
13098: 		     if ($realpossible!=1) { $syval=''; }
13099:                  } else {
13100:                      $syval='';
13101:                  }
13102: 	      }
13103:               untie(%bighash);
13104:            }
13105:         }
13106:         if ($syval) {
13107: 	    return $env{$cache_str}=$syval;
13108:         }
13109:     }
13110:     &appenv({'request.ambiguous' => $thisfn});
13111:     return $env{$cache_str}='';
13112: }
13113: 
13114: # ---------------------------------------------------------- Return random seed
13115: 
13116: sub numval {
13117:     my $txt=shift;
13118:     $txt=~tr/A-J/0-9/;
13119:     $txt=~tr/a-j/0-9/;
13120:     $txt=~tr/K-T/0-9/;
13121:     $txt=~tr/k-t/0-9/;
13122:     $txt=~tr/U-Z/0-5/;
13123:     $txt=~tr/u-z/0-5/;
13124:     $txt=~s/\D//g;
13125:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
13126:     return int($txt);
13127: }
13128: 
13129: sub numval2 {
13130:     my $txt=shift;
13131:     $txt=~tr/A-J/0-9/;
13132:     $txt=~tr/a-j/0-9/;
13133:     $txt=~tr/K-T/0-9/;
13134:     $txt=~tr/k-t/0-9/;
13135:     $txt=~tr/U-Z/0-5/;
13136:     $txt=~tr/u-z/0-5/;
13137:     $txt=~s/\D//g;
13138:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
13139:     my $total;
13140:     foreach my $val (@txts) { $total+=$val; }
13141:     if ($_64bit) { if ($total > 2**32) { return -1; } }
13142:     return int($total);
13143: }
13144: 
13145: sub numval3 {
13146:     use integer;
13147:     my $txt=shift;
13148:     $txt=~tr/A-J/0-9/;
13149:     $txt=~tr/a-j/0-9/;
13150:     $txt=~tr/K-T/0-9/;
13151:     $txt=~tr/k-t/0-9/;
13152:     $txt=~tr/U-Z/0-5/;
13153:     $txt=~tr/u-z/0-5/;
13154:     $txt=~s/\D//g;
13155:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
13156:     my $total;
13157:     foreach my $val (@txts) { $total+=$val; }
13158:     if ($_64bit) { $total=(($total<<32)>>32); }
13159:     return $total;
13160: }
13161: 
13162: sub digest {
13163:     my ($data)=@_;
13164:     my $digest=&Digest::MD5::md5($data);
13165:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
13166:     my ($e,$f);
13167:     {
13168:         use integer;
13169:         $e=($a+$b);
13170:         $f=($c+$d);
13171:         if ($_64bit) {
13172:             $e=(($e<<32)>>32);
13173:             $f=(($f<<32)>>32);
13174:         }
13175:     }
13176:     if (wantarray) {
13177: 	return ($e,$f);
13178:     } else {
13179: 	my $g;
13180: 	{
13181: 	    use integer;
13182: 	    $g=($e+$f);
13183: 	    if ($_64bit) {
13184: 		$g=(($g<<32)>>32);
13185: 	    }
13186: 	}
13187: 	return $g;
13188:     }
13189: }
13190: 
13191: sub latest_rnd_algorithm_id {
13192:     return '64bit5';
13193: }
13194: 
13195: sub get_rand_alg {
13196:     my ($courseid)=@_;
13197:     if (!$courseid) { $courseid=(&whichuser())[1]; }
13198:     if ($courseid) {
13199: 	return $env{"course.$courseid.rndseed"};
13200:     }
13201:     return &latest_rnd_algorithm_id();
13202: }
13203: 
13204: sub validCODE {
13205:     my ($CODE)=@_;
13206:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
13207:     return 0;
13208: }
13209: 
13210: sub getCODE {
13211:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
13212:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
13213: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
13214: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
13215: 	return $Apache::lonhomework::history{'resource.CODE'};
13216:     }
13217:     return undef;
13218: }
13219: #
13220: #  Determines the random seed for a specific context:
13221: #
13222: # parameters:
13223: #   symb      - in course context the symb for the seed.
13224: #   course_id - The course id of the form domain_coursenum.
13225: #   domain    - Domain for the user.
13226: #   course    - Course for the user.
13227: #   cenv      - environment of the course.
13228: #
13229: # NOTE:
13230: #   All parameters are picked out of the environment if missing
13231: #   or not defined.
13232: #   If a symb cannot be determined the current time is used instead.
13233: #
13234: #  For a given well defined symb, courside, domain, username,
13235: #  and course environment, the seed is reproducible.
13236: #
13237: sub rndseed {
13238:     my ($symb,$courseid,$domain,$username, $cenv)=@_;
13239:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
13240:     if (!defined($symb)) {
13241: 	unless ($symb=$wsymb) { return time; }
13242:     }
13243:     if (!defined $courseid) { 
13244: 	$courseid=$wcourseid; 
13245:     }
13246:     if (!defined $domain) { $domain=$wdomain; }
13247:     if (!defined $username) { $username=$wusername }
13248: 
13249:     my $which;
13250:     if (defined($cenv->{'rndseed'})) {
13251: 	$which = $cenv->{'rndseed'};
13252:     } else {
13253: 	$which =&get_rand_alg($courseid);
13254:     }
13255:     if (defined(&getCODE())) {
13256: 
13257: 	if ($which eq '64bit5') {
13258: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
13259: 	} elsif ($which eq '64bit4') {
13260: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
13261: 	} else {
13262: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
13263: 	}
13264:     } elsif ($which eq '64bit5') {
13265: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
13266:     } elsif ($which eq '64bit4') {
13267: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
13268:     } elsif ($which eq '64bit3') {
13269: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
13270:     } elsif ($which eq '64bit2') {
13271: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
13272:     } elsif ($which eq '64bit') {
13273: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
13274:     }
13275:     return &rndseed_32bit($symb,$courseid,$domain,$username);
13276: }
13277: 
13278: sub rndseed_32bit {
13279:     my ($symb,$courseid,$domain,$username)=@_;
13280:     {
13281: 	use integer;
13282: 	my $symbchck=unpack("%32C*",$symb) << 27;
13283: 	my $symbseed=numval($symb) << 22;
13284: 	my $namechck=unpack("%32C*",$username) << 17;
13285: 	my $nameseed=numval($username) << 12;
13286: 	my $domainseed=unpack("%32C*",$domain) << 7;
13287: 	my $courseseed=unpack("%32C*",$courseid);
13288: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
13289: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
13290: 	#&logthis("rndseed :$num:$symb");
13291: 	if ($_64bit) { $num=(($num<<32)>>32); }
13292: 	return $num;
13293:     }
13294: }
13295: 
13296: sub rndseed_64bit {
13297:     my ($symb,$courseid,$domain,$username)=@_;
13298:     {
13299: 	use integer;
13300: 	my $symbchck=unpack("%32S*",$symb) << 21;
13301: 	my $symbseed=numval($symb) << 10;
13302: 	my $namechck=unpack("%32S*",$username);
13303: 	
13304: 	my $nameseed=numval($username) << 21;
13305: 	my $domainseed=unpack("%32S*",$domain) << 10;
13306: 	my $courseseed=unpack("%32S*",$courseid);
13307: 	
13308: 	my $num1=$symbchck+$symbseed+$namechck;
13309: 	my $num2=$nameseed+$domainseed+$courseseed;
13310: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
13311: 	#&logthis("rndseed :$num:$symb");
13312: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
13313: 	return "$num1,$num2";
13314:     }
13315: }
13316: 
13317: sub rndseed_64bit2 {
13318:     my ($symb,$courseid,$domain,$username)=@_;
13319:     {
13320: 	use integer;
13321: 	# strings need to be an even # of cahracters long, it it is odd the
13322:         # last characters gets thrown away
13323: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
13324: 	my $symbseed=numval($symb) << 10;
13325: 	my $namechck=unpack("%32S*",$username.' ');
13326: 	
13327: 	my $nameseed=numval($username) << 21;
13328: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
13329: 	my $courseseed=unpack("%32S*",$courseid.' ');
13330: 	
13331: 	my $num1=$symbchck+$symbseed+$namechck;
13332: 	my $num2=$nameseed+$domainseed+$courseseed;
13333: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
13334: 	#&logthis("rndseed :$num:$symb");
13335: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
13336: 	return "$num1,$num2";
13337:     }
13338: }
13339: 
13340: sub rndseed_64bit3 {
13341:     my ($symb,$courseid,$domain,$username)=@_;
13342:     {
13343: 	use integer;
13344: 	# strings need to be an even # of cahracters long, it it is odd the
13345:         # last characters gets thrown away
13346: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
13347: 	my $symbseed=numval2($symb) << 10;
13348: 	my $namechck=unpack("%32S*",$username.' ');
13349: 	
13350: 	my $nameseed=numval2($username) << 21;
13351: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
13352: 	my $courseseed=unpack("%32S*",$courseid.' ');
13353: 	
13354: 	my $num1=$symbchck+$symbseed+$namechck;
13355: 	my $num2=$nameseed+$domainseed+$courseseed;
13356: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
13357: 	#&logthis("rndseed :$num1:$num2:$_64bit");
13358: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
13359: 	
13360: 	return "$num1:$num2";
13361:     }
13362: }
13363: 
13364: sub rndseed_64bit4 {
13365:     my ($symb,$courseid,$domain,$username)=@_;
13366:     {
13367: 	use integer;
13368: 	# strings need to be an even # of cahracters long, it it is odd the
13369:         # last characters gets thrown away
13370: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
13371: 	my $symbseed=numval3($symb) << 10;
13372: 	my $namechck=unpack("%32S*",$username.' ');
13373: 	
13374: 	my $nameseed=numval3($username) << 21;
13375: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
13376: 	my $courseseed=unpack("%32S*",$courseid.' ');
13377: 	
13378: 	my $num1=$symbchck+$symbseed+$namechck;
13379: 	my $num2=$nameseed+$domainseed+$courseseed;
13380: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
13381: 	#&logthis("rndseed :$num1:$num2:$_64bit");
13382: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
13383: 	
13384: 	return "$num1:$num2";
13385:     }
13386: }
13387: 
13388: sub rndseed_64bit5 {
13389:     my ($symb,$courseid,$domain,$username)=@_;
13390:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
13391:     return "$num1:$num2";
13392: }
13393: 
13394: sub rndseed_CODE_64bit {
13395:     my ($symb,$courseid,$domain,$username)=@_;
13396:     {
13397: 	use integer;
13398: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
13399: 	my $symbseed=numval2($symb);
13400: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
13401: 	my $CODEseed=numval(&getCODE());
13402: 	my $courseseed=unpack("%32S*",$courseid.' ');
13403: 	my $num1=$symbseed+$CODEchck;
13404: 	my $num2=$CODEseed+$courseseed+$symbchck;
13405: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
13406: 	#&logthis("rndseed :$num1:$num2:$symb");
13407: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
13408: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
13409: 	return "$num1:$num2";
13410:     }
13411: }
13412: 
13413: sub rndseed_CODE_64bit4 {
13414:     my ($symb,$courseid,$domain,$username)=@_;
13415:     {
13416: 	use integer;
13417: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
13418: 	my $symbseed=numval3($symb);
13419: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
13420: 	my $CODEseed=numval3(&getCODE());
13421: 	my $courseseed=unpack("%32S*",$courseid.' ');
13422: 	my $num1=$symbseed+$CODEchck;
13423: 	my $num2=$CODEseed+$courseseed+$symbchck;
13424: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
13425: 	#&logthis("rndseed :$num1:$num2:$symb");
13426: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
13427: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
13428: 	return "$num1:$num2";
13429:     }
13430: }
13431: 
13432: sub rndseed_CODE_64bit5 {
13433:     my ($symb,$courseid,$domain,$username)=@_;
13434:     my $code = &getCODE();
13435:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
13436:     return "$num1:$num2";
13437: }
13438: 
13439: sub setup_random_from_rndseed {
13440:     my ($rndseed)=@_;
13441:     if ($rndseed =~/([,:])/) {
13442:         my ($num1,$num2) = map { abs($_); } (split(/[,:]/,$rndseed));
13443:         if ((!$num1) || (!$num2) || ($num1 > 2147483562) || ($num2 > 2147483398)) {
13444:             &Math::Random::random_set_seed_from_phrase($rndseed);
13445:         } else {
13446:             &Math::Random::random_set_seed($num1,$num2);
13447:         }
13448:     } else {
13449: 	&Math::Random::random_set_seed_from_phrase($rndseed);
13450:     }
13451: }
13452: 
13453: sub latest_receipt_algorithm_id {
13454:     return 'receipt3';
13455: }
13456: 
13457: sub recunique {
13458:     my $fucourseid=shift;
13459:     my $unique;
13460:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
13461: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
13462: 	$unique=$env{"course.$fucourseid.internal.encseed"};
13463:     } else {
13464: 	$unique=$perlvar{'lonReceipt'};
13465:     }
13466:     return unpack("%32C*",$unique);
13467: }
13468: 
13469: sub recprefix {
13470:     my $fucourseid=shift;
13471:     my $prefix;
13472:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
13473: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
13474: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
13475:     } else {
13476: 	$prefix=$perlvar{'lonHostID'};
13477:     }
13478:     return unpack("%32C*",$prefix);
13479: }
13480: 
13481: sub ireceipt {
13482:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
13483: 
13484:     my $return =&recprefix($fucourseid).'-';
13485: 
13486:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
13487: 	$env{'request.state'} eq 'construct') {
13488: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
13489: 	return $return;
13490:     }
13491: 
13492:     my $cuname=unpack("%32C*",$funame);
13493:     my $cudom=unpack("%32C*",$fudom);
13494:     my $cucourseid=unpack("%32C*",$fucourseid);
13495:     my $cusymb=unpack("%32C*",$fusymb);
13496:     my $cunique=&recunique($fucourseid);
13497:     my $cpart=unpack("%32S*",$part);
13498:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
13499: 
13500: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
13501: 			       
13502: 	$return.= ($cunique%$cuname+
13503: 		   $cunique%$cudom+
13504: 		   $cusymb%$cuname+
13505: 		   $cusymb%$cudom+
13506: 		   $cucourseid%$cuname+
13507: 		   $cucourseid%$cudom+
13508: 		   $cpart%$cuname+
13509: 		   $cpart%$cudom);
13510:     } else {
13511: 	$return.= ($cunique%$cuname+
13512: 		   $cunique%$cudom+
13513: 		   $cusymb%$cuname+
13514: 		   $cusymb%$cudom+
13515: 		   $cucourseid%$cuname+
13516: 		   $cucourseid%$cudom);
13517:     }
13518:     return $return;
13519: }
13520: 
13521: sub receipt {
13522:     my ($part)=@_;
13523:     my ($symb,$courseid,$domain,$name) = &whichuser();
13524:     return &ireceipt($name,$domain,$courseid,$symb,$part);
13525: }
13526: 
13527: sub whichuser {
13528:     my ($passedsymb)=@_;
13529:     my ($symb,$courseid,$domain,$name,$publicuser);
13530:     if (defined($env{'form.grade_symb'})) {
13531: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
13532: 	my $allowed=&allowed('vgr',$tmp_courseid);
13533: 	if (!$allowed &&
13534: 	    exists($env{'request.course.sec'}) &&
13535: 	    $env{'request.course.sec'} !~ /^\s*$/) {
13536: 	    $allowed=&allowed('vgr',$tmp_courseid.
13537: 			      '/'.$env{'request.course.sec'});
13538: 	}
13539: 	if ($allowed) {
13540: 	    ($symb)=&get_env_multiple('form.grade_symb');
13541: 	    $courseid=$tmp_courseid;
13542: 	    ($domain)=&get_env_multiple('form.grade_domain');
13543: 	    ($name)=&get_env_multiple('form.grade_username');
13544: 	    return ($symb,$courseid,$domain,$name,$publicuser);
13545: 	}
13546:     }
13547:     if (!$passedsymb) {
13548: 	$symb=&symbread();
13549:     } else {
13550: 	$symb=$passedsymb;
13551:     }
13552:     $courseid=$env{'request.course.id'};
13553:     $domain=$env{'user.domain'};
13554:     $name=$env{'user.name'};
13555:     if ($name eq 'public' && $domain eq 'public') {
13556: 	if (!defined($env{'form.username'})) {
13557: 	    $env{'form.username'}.=time.rand(10000000);
13558: 	}
13559: 	$name.=$env{'form.username'};
13560:     }
13561:     return ($symb,$courseid,$domain,$name,$publicuser);
13562: 
13563: }
13564: 
13565: # ------------------------------------------------------------ Serves up a file
13566: # returns either the contents of the file or 
13567: # -1 if the file doesn't exist
13568: #
13569: # if the target is a file that was uploaded via DOCS, 
13570: # a check will be made to see if a current copy exists on the local server,
13571: # if it does this will be served, otherwise a copy will be retrieved from
13572: # the home server for the course and stored in /home/httpd/html/userfiles on
13573: # the local server.   
13574: 
13575: sub getfile {
13576:     my ($file) = @_;
13577:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
13578:     &repcopy($file);
13579:     return &readfile($file);
13580: }
13581: 
13582: sub repcopy_userfile {
13583:     my ($file)=@_;
13584:     my $londocroot = $perlvar{'lonDocRoot'};
13585:     if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
13586:     if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
13587:     my ($cdom,$cnum,$filename) = 
13588: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
13589:     my $uri="/uploaded/$cdom/$cnum/$filename";
13590:     if (-e "$file") {
13591: # we already have a local copy, check it out
13592: 	my @fileinfo = stat($file);
13593: 	my $rtncode;
13594: 	my $info;
13595: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
13596: 	if ($lwpresp ne 'ok') {
13597: # there is no such file anymore, even though we had a local copy
13598: 	    if ($rtncode eq '404') {
13599: 		unlink($file);
13600: 	    }
13601: 	    return -1;
13602: 	}
13603: 	if ($info < $fileinfo[9]) {
13604: # nice, the file we have is up-to-date, just say okay
13605: 	    return 'ok';
13606: 	} else {
13607: # the file is outdated, get rid of it
13608: 	    unlink($file);
13609: 	}
13610:     }
13611: # one way or the other, at this point, we don't have the file
13612: # construct the correct path for the file
13613:     my @parts = ($cdom,$cnum); 
13614:     if ($filename =~ m|^(.+)/[^/]+$|) {
13615: 	push @parts, split(/\//,$1);
13616:     }
13617:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
13618:     foreach my $part (@parts) {
13619: 	$path .= '/'.$part;
13620: 	if (!-e $path) {
13621: 	    mkdir($path,0770);
13622: 	}
13623:     }
13624: # now the path exists for sure
13625: # get a user agent
13626:     my $transferfile=$file.'.in.transfer';
13627: # FIXME: this should flock
13628:     if (-e $transferfile) { return 'ok'; }
13629:     my $request;
13630:     $uri=~s/^\///;
13631:     my $homeserver = &homeserver($cnum,$cdom);
13632:     my $hostname = &hostname($homeserver);
13633:     my $protocol = $protocol{$homeserver};
13634:     $protocol = 'http' if ($protocol ne 'https');
13635:     $request=new HTTP::Request('GET',$protocol.'://'.$hostname.'/raw/'.$uri);
13636:     my $response = &LONCAPA::LWPReq::makerequest($homeserver,$request,$transferfile,\%perlvar,'',0,1);
13637: # did it work?
13638:     if ($response->is_error()) {
13639: 	unlink($transferfile);
13640: 	&logthis("Userfile repcopy failed for $uri");
13641: 	return -1;
13642:     }
13643: # worked, rename the transfer file
13644:     rename($transferfile,$file);
13645:     return 'ok';
13646: }
13647: 
13648: sub tokenwrapper {
13649:     my $uri=shift;
13650:     $uri=~s|^https?\://([^/]+)||;
13651:     $uri=~s|^/||;
13652:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
13653:     my $token=$1;
13654:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
13655:     if ($udom && $uname && $file) {
13656: 	$file=~s|(\?\.*)*$||;
13657:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
13658:         my $homeserver = &homeserver($uname,$udom);
13659:         my $hostname = &hostname($homeserver);
13660:         my $protocol = $protocol{$homeserver};
13661:         $protocol = 'http' if ($protocol ne 'https');
13662:         return $protocol.'://'.$hostname.'/'.$uri.
13663:                (($uri=~/\?/)?'&':'?').'token='.$token.
13664:                                '&tokenissued='.$perlvar{'lonHostID'};
13665:     } else {
13666:         return '/adm/notfound.html';
13667:     }
13668: }
13669: 
13670: # call with reqtype HEAD: get last modification time
13671: # call with reqtype GET: get the file contents
13672: # Do not call this with reqtype GET for large files! It loads everything into memory
13673: #
13674: sub getuploaded {
13675:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
13676:     $uri=~s/^\///;
13677:     my $homeserver = &homeserver($cnum,$cdom);
13678:     my $hostname = &hostname($homeserver);
13679:     my $protocol = $protocol{$homeserver};
13680:     $protocol = 'http' if ($protocol ne 'https');
13681:     $uri = $protocol.'://'.$hostname.'/raw/'.$uri;
13682:     my $request=new HTTP::Request($reqtype,$uri);
13683:     my $response=&LONCAPA::LWPReq::makerequest($homeserver,$request,'',\%perlvar,'',0,1);
13684:     $$rtncode = $response->code;
13685:     if (! $response->is_success()) {
13686: 	return 'failed';
13687:     }      
13688:     if ($reqtype eq 'HEAD') {
13689: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
13690:     } elsif ($reqtype eq 'GET') {
13691: 	$$info = $response->content;
13692:     }
13693:     return 'ok';
13694: }
13695: 
13696: sub readfile {
13697:     my $file = shift;
13698:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
13699:     my $fh;
13700:     open($fh,"<",$file);
13701:     my $a='';
13702:     while (my $line = <$fh>) { $a .= $line; }
13703:     return $a;
13704: }
13705: 
13706: sub filelocation {
13707:     my ($dir,$file) = @_;
13708:     my $location;
13709:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
13710: 
13711:     if ($file =~ m-^/adm/-) {
13712: 	$file=~s-^/adm/wrapper/-/-;
13713: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
13714:     }
13715: 
13716:     if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
13717:         $location = $file;
13718:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
13719:         my ($udom,$uname,$filename)=
13720:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
13721:         my $home=&homeserver($uname,$udom);
13722:         my $is_me=0;
13723:         my @ids=&current_machine_ids();
13724:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
13725:         if ($is_me) {
13726:   	    $location=propath($udom,$uname).'/userfiles/'.$filename;
13727:         } else {
13728:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
13729:   	      $udom.'/'.$uname.'/'.$filename;
13730:         }
13731:     } elsif ($file =~ m-^/adm/-) {
13732: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
13733:     } else {
13734:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
13735:         $file=~s:^/(res|priv)/:/:;
13736:         my $space=$1;
13737:         if ( !( $file =~ m:^/:) ) {
13738:             $location = $dir. '/'.$file;
13739:         } else {
13740:             $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
13741:         }
13742:     }
13743:     $location=~s://+:/:g; # remove duplicate /
13744:     while ($location=~m{/\.\./}) {
13745: 	if ($location =~ m{/[^/]+/\.\./}) {
13746: 	    $location=~ s{/[^/]+/\.\./}{/}g;
13747: 	} else {
13748: 	    $location=~ s{/\.\./}{/}g;
13749: 	}
13750:     } #remove dir/..
13751:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
13752:     return $location;
13753: }
13754: 
13755: sub hreflocation {
13756:     my ($dir,$file)=@_;
13757:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
13758: 	$file=filelocation($dir,$file);
13759:     } elsif ($file=~m-^/adm/-) {
13760: 	$file=~s-^/adm/wrapper/-/-;
13761: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
13762:     }
13763:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
13764: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
13765:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
13766: 	$file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
13767: 	        {/uploaded/$1/$2/}x;
13768:     }
13769:     if ($file=~ m{^/userfiles/}) {
13770: 	$file =~ s{^/userfiles/}{/uploaded/};
13771:     }
13772:     return $file;
13773: }
13774: 
13775: 
13776: 
13777: 
13778: 
13779: sub current_machine_domains {
13780:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
13781: }
13782: 
13783: sub machine_domains {
13784:     my ($hostname) = @_;
13785:     my @domains;
13786:     my %hostname = &all_hostnames();
13787:     while( my($id, $name) = each(%hostname)) {
13788: #	&logthis("-$id-$name-$hostname-");
13789: 	if ($hostname eq $name) {
13790: 	    push(@domains,&host_domain($id));
13791: 	}
13792:     }
13793:     return @domains;
13794: }
13795: 
13796: sub current_machine_ids {
13797:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
13798: }
13799: 
13800: sub machine_ids {
13801:     my ($hostname) = @_;
13802:     $hostname ||= &hostname($perlvar{'lonHostID'});
13803:     my @ids;
13804:     my %name_to_host = &all_names();
13805:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
13806: 	return @{ $name_to_host{$hostname} };
13807:     }
13808:     return;
13809: }
13810: 
13811: sub additional_machine_domains {
13812:     my @domains;
13813:     open(my $fh,"<","$perlvar{'lonTabDir'}/expected_domains.tab");
13814:     while( my $line = <$fh>) {
13815:         $line =~ s/\s//g;
13816:         push(@domains,$line);
13817:     }
13818:     return @domains;
13819: }
13820: 
13821: sub default_login_domain {
13822:     my $domain = $perlvar{'lonDefDomain'};
13823:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
13824:     foreach my $posdom (&current_machine_domains(),
13825:                         &additional_machine_domains()) {
13826:         if (lc($posdom) eq lc($testdomain)) {
13827:             $domain=$posdom;
13828:             last;
13829:         }
13830:     }
13831:     return $domain;
13832: }
13833: 
13834: sub uses_sts {
13835:     my ($ignore_cache) = @_;
13836:     my $lonhost = $perlvar{'lonHostID'};
13837:     my $hostname = &hostname($lonhost);
13838:     my $sts_on;
13839:     if ($protocol{$lonhost} eq 'https') {
13840:         my $cachetime = 12*3600;
13841:         if (!$ignore_cache) {
13842:             ($sts_on,my $cached)=&is_cached_new('stspolicy',$lonhost);
13843:             if (defined($cached)) {
13844:                 return $sts_on;
13845:             }
13846:         }
13847:         my $url = $protocol{$lonhost}.'://'.$hostname.'/index.html';
13848:         my $request=new HTTP::Request('HEAD',$url);
13849:         my $response=&LONCAPA::LWPReq::makerequest($lonhost,$request,'',\%perlvar,'','','',1);
13850:         if ($response->is_success) {
13851:             my $has_sts = $response->header('Strict-Transport-Security');
13852:             if ($has_sts eq '') {
13853:                 $sts_on = 0;
13854:             } else {
13855:                 if ($has_sts =~ /\Qmax-age=\E(\d+)/) {
13856:                     my $maxage = $1;
13857:                     if ($maxage) {
13858:                         $sts_on = 1;
13859:                     } else {
13860:                         $sts_on = 0;
13861:                     }
13862:                 } else {
13863:                     $sts_on = 0;
13864:                 }
13865:             }
13866:             return &do_cache_new('stspolicy',$lonhost,$sts_on,$cachetime);
13867:         }
13868:     }
13869:     return;
13870: }
13871: 
13872: # ------------------------------------------------------------- Declutters URLs
13873: 
13874: sub declutter {
13875:     my $thisfn=shift;
13876:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
13877:     unless ($thisfn=~m{^/home/httpd/html/priv/}) {
13878:         $thisfn=~s{^/home/httpd/html}{};
13879:     }
13880:     $thisfn=~s/^\///;
13881:     $thisfn=~s|^adm/wrapper/||;
13882:     $thisfn=~s|^adm/coursedocs/showdoc/||;
13883:     $thisfn=~s/^res\///;
13884:     $thisfn=~s/^priv\///;
13885:     unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
13886:         $thisfn=~s/\?.+$//;
13887:     }
13888:     return $thisfn;
13889: }
13890: 
13891: # ------------------------------------------------------------- Clutter up URLs
13892: 
13893: sub clutter {
13894:     my $thisfn='/'.&declutter(shift);
13895:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
13896: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
13897:        $thisfn='/res'.$thisfn; 
13898:     }
13899:     if ($thisfn !~m|^/adm|) {
13900: 	if ($thisfn =~ m|^/ext/|) {
13901: 	    $thisfn='/adm/wrapper'.$thisfn;
13902: 	} else {
13903: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
13904: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
13905: 	    if ($embstyle eq 'ssi'
13906: 		|| ($embstyle eq 'hdn')
13907: 		|| ($embstyle eq 'rat')
13908: 		|| ($embstyle eq 'prv')
13909: 		|| ($embstyle eq 'ign')) {
13910: 		#do nothing with these
13911: 	    } elsif (($embstyle eq 'img') 
13912: 		|| ($embstyle eq 'emb')
13913: 		|| ($embstyle eq 'wrp')) {
13914: 		$thisfn='/adm/wrapper'.$thisfn;
13915: 	    } elsif ($embstyle eq 'unk'
13916: 		     && $thisfn!~/\.(sequence|page)$/) {
13917: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
13918: 	    } else {
13919: #		&logthis("Got a blank emb style");
13920: 	    }
13921: 	}
13922:     } elsif ($thisfn =~ m{^/adm/$match_domain/$match_courseid/\d+/ext\.tool$}) {
13923:         $thisfn='/adm/wrapper'.$thisfn;
13924:     }
13925:     return $thisfn;
13926: }
13927: 
13928: sub clutter_with_no_wrapper {
13929:     my $uri = &clutter(shift);
13930:     if ($uri =~ m-^/adm/-) {
13931: 	$uri =~ s-^/adm/wrapper/-/-;
13932: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
13933:     }
13934:     return $uri;
13935: }
13936: 
13937: sub freeze_escape {
13938:     my ($value)=@_;
13939:     if (ref($value)) {
13940: 	$value=&nfreeze($value);
13941: 	return '__FROZEN__'.&escape($value);
13942:     }
13943:     return &escape($value);
13944: }
13945: 
13946: 
13947: sub thaw_unescape {
13948:     my ($value)=@_;
13949:     if ($value =~ /^__FROZEN__/) {
13950: 	substr($value,0,10,undef);
13951: 	$value=&unescape($value);
13952: 	return &thaw($value);
13953:     }
13954:     return &unescape($value);
13955: }
13956: 
13957: sub correct_line_ends {
13958:     my ($result)=@_;
13959:     $$result =~s/\r\n/\n/mg;
13960:     $$result =~s/\r/\n/mg;
13961: }
13962: # ================================================================ Main Program
13963: 
13964: sub goodbye {
13965:    &logthis("Starting Shut down");
13966: #not converted to using infrastruture and probably shouldn't be
13967:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
13968: #converted
13969: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
13970:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
13971: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
13972: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
13973: #1.1 only
13974: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
13975: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
13976: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
13977: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
13978:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
13979:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
13980:    &logthis(sprintf("%-20s is %s",'hits',$hits));
13981:    &flushcourselogs();
13982:    &logthis("Shutting down");
13983: }
13984: 
13985: sub get_dns {
13986:     my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
13987:     if (!$ignore_cache) {
13988: 	my ($content,$cached)=
13989: 	    &Apache::lonnet::is_cached_new('dns',$url);
13990: 	if ($cached) {
13991: 	    &$func($content,$hashref);
13992: 	    return;
13993: 	}
13994:     }
13995: 
13996:     my %alldns;
13997:     if (open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab")) {
13998:         foreach my $dns (<$config>) {
13999: 	    next if ($dns !~ /^\^(\S*)/x);
14000:             my $line = $1;
14001:             my ($host,$protocol) = split(/:/,$line);
14002:             if ($protocol ne 'https') {
14003:                 $protocol = 'http';
14004:             }
14005: 	    $alldns{$host} = $protocol;
14006:         }
14007:         close($config);
14008:     }
14009:     while (%alldns) {
14010: 	my ($dns) = sort { $b cmp $a } keys(%alldns);
14011: 	my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
14012:         my $response = &LONCAPA::LWPReq::makerequest('',$request,'',\%perlvar,30,0);
14013:         delete($alldns{$dns});
14014: 	next if ($response->is_error());
14015:         if ($url eq '/adm/dns/loncapaCRL') {
14016:             return &$func($response);
14017:         } else {
14018: 	    my @content = split("\n",$response->content);
14019: 	    unless ($nocache) {
14020: 	        &do_cache_new('dns',$url,\@content,30*24*60*60);
14021: 	    }
14022: 	    &$func(\@content,$hashref);
14023:             return;
14024:         }
14025:     }
14026:     my $which = (split('/',$url,4))[3];
14027:     if ($which eq 'loncapaCRL') {
14028:         my $diskfile = "$perlvar{'lonCertificateDirectory'}/$perlvar{'lonnetCertRevocationList'}";
14029:         if (-e $diskfile) {
14030:             &logthis("unable to contact DNS, on disk file $diskfile not updated");
14031:         } else {
14032:             &logthis("unable to contact DNS, no on disk file $diskfile available");
14033:         }
14034:     } else {
14035:         &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
14036:         if (open(my $config,"<","$perlvar{'lonTabDir'}/dns_$which.tab")) {
14037:             my @content = <$config>;
14038:             close($config);
14039:             &$func(\@content,$hashref);
14040:         }
14041:     }
14042:     return;
14043: }
14044: 
14045: # ------------------------------------------------------Get DNS checksums file
14046: sub parse_dns_checksums_tab {
14047:     my ($lines,$hashref) = @_;
14048:     my $lonhost = $perlvar{'lonHostID'};
14049:     my $machine_dom = &Apache::lonnet::host_domain($lonhost);
14050:     my $loncaparev = &get_server_loncaparev($machine_dom);
14051:     my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
14052:     my $webconfdir = '/etc/httpd/conf';
14053:     if ($distro =~ /^(ubuntu|debian)(\d+)$/) {
14054:         $webconfdir = '/etc/apache2';
14055:     } elsif ($distro =~ /^sles(\d+)$/) {
14056:         if ($1 >= 10) {
14057:             $webconfdir = '/etc/apache2';
14058:         }
14059:     } elsif ($distro =~ /^suse(\d+\.\d+)$/) {
14060:         if ($1 >= 10.0) {
14061:             $webconfdir = '/etc/apache2';
14062:         }
14063:     }
14064:     my ($release,$timestamp) = split(/\-/,$loncaparev);
14065:     my (%chksum,%revnum);
14066:     if (ref($lines) eq 'ARRAY') {
14067:         chomp(@{$lines});
14068:         my $version = shift(@{$lines});
14069:         if ($version eq $release) {  
14070:             foreach my $line (@{$lines}) {
14071:                 my ($file,$version,$shasum) = split(/,/,$line);
14072:                 if ($file =~ m{^/etc/httpd/conf}) {
14073:                     if ($webconfdir eq '/etc/apache2') {
14074:                         $file =~ s{^\Q/etc/httpd/conf/\E}{$webconfdir/};
14075:                     }
14076:                 }
14077:                 $chksum{$file} = $shasum;
14078:                 $revnum{$file} = $version;
14079:             }
14080:             if (ref($hashref) eq 'HASH') {
14081:                 %{$hashref} = (
14082:                                 sums     => \%chksum,
14083:                                 versions => \%revnum,
14084:                               );
14085:             }
14086:         }
14087:     }
14088:     return;
14089: }
14090: 
14091: sub fetch_dns_checksums {
14092:     my %checksums;
14093:     my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
14094:     my $loncaparev = &get_server_loncaparev($machine_dom,$perlvar{'lonHostID'});
14095:     my ($release,$timestamp) = split(/\-/,$loncaparev);
14096:     &get_dns("/adm/dns/checksums/$release",\&parse_dns_checksums_tab,1,1,
14097:              \%checksums);
14098:     return \%checksums;
14099: }
14100: 
14101: sub fetch_crl_pemfile {
14102:     return &get_dns("/adm/dns/loncapaCRL",\&save_crl_pem,1,1);
14103: }
14104: 
14105: sub save_crl_pem {
14106:     my ($response) = @_;
14107:     my ($msg,$hadchanges);
14108:     if (ref($response)) {
14109:         my $now = time;
14110:         my $lonca = $perlvar{'lonCertificateDirectory'}.'/'.$perlvar{'lonnetCertificateAuthority'};
14111:         my $tmpcrl = $tmpdir.'/'.$perlvar{'lonnetCertRevocationList'}.'_'.$now.'.'.$$.'.tmp';
14112:         if (open(my $fh,'>',"$tmpcrl")) {
14113:             print $fh $response->content;
14114:             close($fh);
14115:             if (-e $lonca) {
14116:                 if (open(PIPE,"openssl crl -in $tmpcrl -inform pem -CAfile $lonca -noout 2>&1 |")) {
14117:                     my $check = <PIPE>;
14118:                     close(PIPE);
14119:                     chomp($check);
14120:                     if ($check eq 'verify OK') {
14121:                         my $dest = "$perlvar{'lonCertificateDirectory'}/$perlvar{'lonnetCertRevocationList'}";
14122:                         my $backup;
14123:                         if (-e $dest) {
14124:                             if (&File::Copy::move($dest,"$dest.bak")) {
14125:                                 $backup = 'ok';
14126:                             }
14127:                         }
14128:                         if (&File::Copy::move($tmpcrl,$dest)) {
14129:                             $msg = 'ok';
14130:                             if ($backup) {
14131:                                 my (%oldnums,%newnums);
14132:                                 if (open(PIPE, "openssl crl -inform PEM -text -noout -in $dest.bak |grep 'Serial Number' |")) {
14133:                                     while (<PIPE>) {
14134:                                         $oldnums{(split(/:/))[1]} = 1;
14135:                                     }
14136:                                     close(PIPE);
14137:                                 }
14138:                                 if (open(PIPE, "openssl crl -inform PEM -text -noout -in $dest |grep 'Serial Number' |")) {
14139:                                     while(<PIPE>) {
14140:                                         $newnums{(split(/:/))[1]} = 1;
14141:                                     }
14142:                                     close(PIPE);
14143:                                 }
14144:                                 foreach my $key (sort {$b <=> $a } (keys(%newnums))) {
14145:                                     unless (exists($oldnums{$key})) {
14146:                                         $hadchanges = 1;
14147:                                         last;
14148:                                     }
14149:                                 }
14150:                                 unless ($hadchanges) {
14151:                                     foreach my $key (sort {$b <=> $a } (keys(%oldnums))) {
14152:                                         unless (exists($newnums{$key})) {
14153:                                             $hadchanges = 1;
14154:                                             last;
14155:                                         }
14156:                                     }
14157:                                 }
14158:                             }
14159:                         }
14160:                     } else {
14161:                         unlink($tmpcrl);
14162:                     }
14163:                 } else {
14164:                     unlink($tmpcrl);
14165:                 }
14166:             } else {
14167:                 unlink($tmpcrl);
14168:             }
14169:         }
14170:     }
14171:     return ($msg,$hadchanges);
14172: }
14173: 
14174: # ------------------------------------------------------------ Read domain file
14175: {
14176:     my $loaded;
14177:     my %domain;
14178: 
14179:     sub parse_domain_tab {
14180: 	my ($lines) = @_;
14181: 	foreach my $line (@$lines) {
14182: 	    next if ($line =~ /^(\#|\s*$ )/x);
14183: 
14184: 	    chomp($line);
14185: 	    my ($name,@elements) = split(/:/,$line,9);
14186: 	    my %this_domain;
14187: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
14188: 			       'lang_def', 'city', 'longi', 'lati',
14189: 			       'primary') {
14190: 		$this_domain{$field} = shift(@elements);
14191: 	    }
14192: 	    $domain{$name} = \%this_domain;
14193: 	}
14194:     }
14195: 
14196:     sub reset_domain_info {
14197: 	undef($loaded);
14198: 	undef(%domain);
14199:     }
14200: 
14201:     sub load_domain_tab {
14202: 	my ($ignore_cache,$nocache) = @_;
14203: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache,$nocache);
14204: 	my $fh;
14205: 	if (open($fh,"<",$perlvar{'lonTabDir'}.'/domain.tab')) {
14206: 	    my @lines = <$fh>;
14207: 	    &parse_domain_tab(\@lines);
14208: 	}
14209: 	close($fh);
14210: 	$loaded = 1;
14211:     }
14212: 
14213:     sub domain {
14214: 	&load_domain_tab() if (!$loaded);
14215: 
14216: 	my ($name,$what) = @_;
14217: 	return if ( !exists($domain{$name}) );
14218: 
14219: 	if (!$what) {
14220: 	    return $domain{$name}{'description'};
14221: 	}
14222: 	return $domain{$name}{$what};
14223:     }
14224: 
14225:     sub domain_info {
14226:         &load_domain_tab() if (!$loaded);
14227:         return %domain;
14228:     }
14229: 
14230: }
14231: 
14232: 
14233: # ------------------------------------------------------------- Read hosts file
14234: {
14235:     my %hostname;
14236:     my %hostdom;
14237:     my %libserv;
14238:     my $loaded;
14239:     my %name_to_host;
14240:     my %internetdom;
14241:     my %LC_dns_serv;
14242: 
14243:     sub parse_hosts_tab {
14244: 	my ($file) = @_;
14245: 	foreach my $configline (@$file) {
14246: 	    next if ($configline =~ /^(\#|\s*$ )/x);
14247:             chomp($configline);
14248: 	    if ($configline =~ /^\^/) {
14249:                 if ($configline =~ /^\^([\w.\-]+)/) {
14250:                     $LC_dns_serv{$1} = 1;
14251:                 }
14252:                 next;
14253:             }
14254: 	    my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
14255: 	    $name=~s/\s//g;
14256: 	    if ($id && $domain && $role && $name) {
14257:                 if ((exists($hostname{$id})) && ($hostname{$id} ne '')) {
14258:                     my $curr = $hostname{$id};
14259:                     my $skip;
14260:                     if (ref($name_to_host{$curr}) eq 'ARRAY') {
14261:                         if (($curr eq $name) && (@{$name_to_host{$curr}} == 1)) {
14262:                             $skip = 1;
14263:                         } else {
14264:                             @{$name_to_host{$curr}} = grep { $_ ne $id } @{$name_to_host{$curr}};
14265:                         }
14266:                     }
14267:                     unless ($skip) {
14268:                         push(@{$name_to_host{$name}},$id);
14269:                     }
14270:                 } else {
14271:                     push(@{$name_to_host{$name}},$id);
14272:                 }
14273: 		$hostname{$id}=$name;
14274: 		$hostdom{$id}=$domain;
14275: 		if ($role eq 'library') { $libserv{$id}=$name; }
14276:                 if (defined($protocol)) {
14277:                     if ($protocol eq 'https') {
14278:                         $protocol{$id} = $protocol;
14279:                     } else {
14280:                         $protocol{$id} = 'http'; 
14281:                     }
14282:                 } else {
14283:                     $protocol{$id} = 'http';
14284:                 }
14285:                 if (defined($intdom)) {
14286:                     $internetdom{$id} = $intdom;
14287:                 }
14288: 	    }
14289: 	}
14290:     }
14291:     
14292:     sub reset_hosts_info {
14293: 	&purge_remembered();
14294: 	&reset_domain_info();
14295: 	&reset_hosts_ip_info();
14296:         undef(%internetdom);
14297: 	undef(%name_to_host);
14298: 	undef(%hostname);
14299: 	undef(%hostdom);
14300: 	undef(%libserv);
14301: 	undef($loaded);
14302:     }
14303: 
14304:     sub load_hosts_tab {
14305: 	my ($ignore_cache,$nocache) = @_;
14306: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache,$nocache);
14307: 	open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab");
14308: 	my @config = <$config>;
14309: 	&parse_hosts_tab(\@config);
14310: 	close($config);
14311: 	$loaded=1;
14312:     }
14313: 
14314:     sub hostname {
14315: 	&load_hosts_tab() if (!$loaded);
14316: 
14317: 	my ($lonid) = @_;
14318: 	return $hostname{$lonid};
14319:     }
14320: 
14321:     sub all_hostnames {
14322: 	&load_hosts_tab() if (!$loaded);
14323: 
14324: 	return %hostname;
14325:     }
14326: 
14327:     sub all_names {
14328:         my ($ignore_cache,$nocache) = @_;
14329: 	&load_hosts_tab($ignore_cache,$nocache) if (!$loaded);
14330: 
14331: 	return %name_to_host;
14332:     }
14333: 
14334:     sub all_host_domain {
14335:         &load_hosts_tab() if (!$loaded);
14336:         return %hostdom;
14337:     }
14338: 
14339:     sub all_host_intdom {
14340:         &load_hosts_tab() if (!$loaded);
14341:         return %internetdom;
14342:     }
14343: 
14344:     sub is_library {
14345: 	&load_hosts_tab() if (!$loaded);
14346: 
14347: 	return exists($libserv{$_[0]});
14348:     }
14349: 
14350:     sub all_library {
14351: 	&load_hosts_tab() if (!$loaded);
14352: 
14353: 	return %libserv;
14354:     }
14355: 
14356:     sub unique_library {
14357: 	#2x reverse removes all hostnames that appear more than once
14358:         my %unique = reverse &all_library();
14359:         return reverse %unique;
14360:     }
14361: 
14362:     sub get_servers {
14363: 	&load_hosts_tab() if (!$loaded);
14364: 
14365: 	my ($domain,$type) = @_;
14366: 	my %possible_hosts = ($type eq 'library') ? %libserv
14367: 	                                          : %hostname;
14368: 	my %result;
14369: 	if (ref($domain) eq 'ARRAY') {
14370: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
14371: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
14372: 		    $result{$host} = $hostname;
14373: 		}
14374: 	    }
14375: 	} else {
14376: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
14377: 		if ($hostdom{$host} eq $domain) {
14378: 		    $result{$host} = $hostname;
14379: 		}
14380: 	    }
14381: 	}
14382: 	return %result;
14383:     }
14384: 
14385:     sub get_unique_servers {
14386:         my %unique = reverse &get_servers(@_);
14387: 	return reverse %unique;
14388:     }
14389: 
14390:     sub host_domain {
14391: 	&load_hosts_tab() if (!$loaded);
14392: 
14393: 	my ($lonid) = @_;
14394: 	return $hostdom{$lonid};
14395:     }
14396: 
14397:     sub all_domains {
14398: 	&load_hosts_tab() if (!$loaded);
14399: 
14400: 	my %seen;
14401: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
14402: 	return @uniq;
14403:     }
14404: 
14405:     sub internet_dom {
14406:         &load_hosts_tab() if (!$loaded);
14407: 
14408:         my ($lonid) = @_;
14409:         return $internetdom{$lonid};
14410:     }
14411: 
14412:     sub is_LC_dns {
14413:         &load_hosts_tab() if (!$loaded);
14414: 
14415:         my ($hostname) = @_;
14416:         return exists($LC_dns_serv{$hostname});
14417:     }
14418: 
14419: }
14420: 
14421: { 
14422:     my %iphost;
14423:     my %name_to_ip;
14424:     my %lonid_to_ip;
14425: 
14426:     sub get_hosts_from_ip {
14427: 	my ($ip) = @_;
14428: 	my %iphosts = &get_iphost();
14429: 	if (ref($iphosts{$ip})) {
14430: 	    return @{$iphosts{$ip}};
14431: 	}
14432: 	return;
14433:     }
14434:     
14435:     sub reset_hosts_ip_info {
14436: 	undef(%iphost);
14437: 	undef(%name_to_ip);
14438: 	undef(%lonid_to_ip);
14439:     }
14440: 
14441:     sub get_host_ip {
14442: 	my ($lonid) = @_;
14443: 	if (exists($lonid_to_ip{$lonid})) {
14444: 	    return $lonid_to_ip{$lonid};
14445: 	}
14446: 	my $name=&hostname($lonid);
14447:    	my $ip = gethostbyname($name);
14448: 	return if (!$ip || length($ip) ne 4);
14449: 	$ip=inet_ntoa($ip);
14450: 	$name_to_ip{$name}   = $ip;
14451: 	$lonid_to_ip{$lonid} = $ip;
14452: 	return $ip;
14453:     }
14454:     
14455:     sub get_iphost {
14456: 	my ($ignore_cache,$nocache) = @_;
14457: 
14458: 	if (!$ignore_cache) {
14459: 	    if (%iphost) {
14460: 		return %iphost;
14461: 	    }
14462: 	    my ($ip_info,$cached)=
14463: 		&Apache::lonnet::is_cached_new('iphost','iphost');
14464: 	    if ($cached) {
14465: 		%iphost      = %{$ip_info->[0]};
14466: 		%name_to_ip  = %{$ip_info->[1]};
14467: 		%lonid_to_ip = %{$ip_info->[2]};
14468: 		return %iphost;
14469: 	    }
14470: 	}
14471: 
14472: 	# get yesterday's info for fallback
14473: 	my %old_name_to_ip;
14474: 	my ($ip_info,$cached)=
14475: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
14476: 	if ($cached) {
14477: 	    %old_name_to_ip = %{$ip_info->[1]};
14478: 	}
14479: 
14480: 	my %name_to_host = &all_names($ignore_cache,$nocache);
14481: 	foreach my $name (keys(%name_to_host)) {
14482: 	    my $ip;
14483: 	    if (!exists($name_to_ip{$name})) {
14484: 		$ip = gethostbyname($name);
14485: 		if (!$ip || length($ip) ne 4) {
14486: 		    if (defined($old_name_to_ip{$name})) {
14487: 			$ip = $old_name_to_ip{$name};
14488: 			&logthis("Can't find $name defaulting to old $ip");
14489: 		    } else {
14490: 			&logthis("Name $name no IP found");
14491: 			next;
14492: 		    }
14493: 		} else {
14494: 		    $ip=inet_ntoa($ip);
14495: 		}
14496: 		$name_to_ip{$name} = $ip;
14497: 	    } else {
14498: 		$ip = $name_to_ip{$name};
14499: 	    }
14500: 	    foreach my $id (@{ $name_to_host{$name} }) {
14501: 		$lonid_to_ip{$id} = $ip;
14502: 	    }
14503: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
14504: 	}
14505:         unless ($nocache) {
14506: 	    &do_cache_new('iphost','iphost',
14507: 		          [\%iphost,\%name_to_ip,\%lonid_to_ip],
14508: 		          48*60*60);
14509:         }
14510: 
14511: 	return %iphost;
14512:     }
14513: 
14514:     #
14515:     #  Given a DNS returns the loncapa host name for that DNS 
14516:     # 
14517:     sub host_from_dns {
14518:         my ($dns) = @_;
14519:         my @hosts;
14520:         my $ip;
14521: 
14522:         if (exists($name_to_ip{$dns})) {
14523:             $ip = $name_to_ip{$dns};
14524:         }
14525:         if (!$ip) {
14526:             $ip = gethostbyname($dns); # Initial translation to IP is in net order.
14527:             if (length($ip) == 4) { 
14528: 	        $ip   = &IO::Socket::inet_ntoa($ip);
14529:             }
14530:         }
14531:         if ($ip) {
14532: 	    @hosts = get_hosts_from_ip($ip);
14533: 	    return $hosts[0];
14534:         }
14535:         return undef;
14536:     }
14537: 
14538:     sub get_internet_names {
14539:         my ($lonid) = @_;
14540:         return if ($lonid eq '');
14541:         my ($idnref,$cached)=
14542:             &Apache::lonnet::is_cached_new('internetnames',$lonid);
14543:         if ($cached) {
14544:             return $idnref;
14545:         }
14546:         my $ip = &get_host_ip($lonid);
14547:         my @hosts = &get_hosts_from_ip($ip);
14548:         my %iphost = &get_iphost();
14549:         my (@idns,%seen);
14550:         foreach my $id (@hosts) {
14551:             my $dom = &host_domain($id);
14552:             my $prim_id = &domain($dom,'primary');
14553:             my $prim_ip = &get_host_ip($prim_id);
14554:             next if ($seen{$prim_ip});
14555:             if (ref($iphost{$prim_ip}) eq 'ARRAY') {
14556:                 foreach my $id (@{$iphost{$prim_ip}}) {
14557:                     my $intdom = &internet_dom($id);
14558:                     unless (grep(/^\Q$intdom\E$/,@idns)) {
14559:                         push(@idns,$intdom);
14560:                     }
14561:                 }
14562:             }
14563:             $seen{$prim_ip} = 1;
14564:         }
14565:         return &do_cache_new('internetnames',$lonid,\@idns,12*60*60);
14566:     }
14567: 
14568: }
14569: 
14570: sub all_loncaparevs {
14571:     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);
14572: }
14573: 
14574: # ---------------------------------------------------------- Read loncaparev table
14575: {
14576:     sub load_loncaparevs { 
14577:         if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
14578:             if (open(my $config,"<","$perlvar{'lonTabDir'}/loncaparevs.tab")) {
14579:                 while (my $configline=<$config>) {
14580:                     chomp($configline);
14581:                     my ($hostid,$loncaparev)=split(/:/,$configline);
14582:                     $loncaparevs{$hostid}=$loncaparev;
14583:                 }
14584:                 close($config);
14585:             }
14586:         }
14587:     }
14588: }
14589: 
14590: # ---------------------------------------------------------- Read serverhostID table
14591: {
14592:     sub load_serverhomeIDs {
14593:         if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
14594:             if (open(my $config,"<","$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
14595:                 while (my $configline=<$config>) {
14596:                     chomp($configline);
14597:                     my ($name,$id)=split(/:/,$configline);
14598:                     $serverhomeIDs{$name}=$id;
14599:                 }
14600:                 close($config);
14601:             }
14602:         }
14603:     }
14604: }
14605: 
14606: 
14607: BEGIN {
14608: 
14609: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
14610:     unless ($readit) {
14611: {
14612:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
14613:     %perlvar = (%perlvar,%{$configvars});
14614: }
14615: 
14616: 
14617: # ------------------------------------------------------ Read spare server file
14618: {
14619:     open(my $config,"<","$perlvar{'lonTabDir'}/spare.tab");
14620: 
14621:     while (my $configline=<$config>) {
14622:        chomp($configline);
14623:        if ($configline) {
14624: 	   my ($host,$type) = split(':',$configline,2);
14625: 	   if (!defined($type) || $type eq '') { $type = 'default' };
14626: 	   push(@{ $spareid{$type} }, $host);
14627:        }
14628:     }
14629:     close($config);
14630: }
14631: # ------------------------------------------------------------ Read permissions
14632: {
14633:     open(my $config,"<","$perlvar{'lonTabDir'}/roles.tab");
14634: 
14635:     while (my $configline=<$config>) {
14636: 	chomp($configline);
14637: 	if ($configline) {
14638: 	    my ($role,$perm)=split(/ /,$configline);
14639: 	    if ($perm ne '') { $pr{$role}=$perm; }
14640: 	}
14641:     }
14642:     close($config);
14643: }
14644: 
14645: # -------------------------------------------- Read plain texts for permissions
14646: {
14647:     open(my $config,"<","$perlvar{'lonTabDir'}/rolesplain.tab");
14648: 
14649:     while (my $configline=<$config>) {
14650: 	chomp($configline);
14651: 	if ($configline) {
14652: 	    my ($short,@plain)=split(/:/,$configline);
14653:             %{$prp{$short}} = ();
14654: 	    if (@plain > 0) {
14655:                 $prp{$short}{'std'} = $plain[0];
14656:                 for (my $i=1; $i<@plain; $i++) {
14657:                     $prp{$short}{'alt'.$i} = $plain[$i];  
14658:                 }
14659:             }
14660: 	}
14661:     }
14662:     close($config);
14663: }
14664: 
14665: # ---------------------------------------------------------- Read package table
14666: {
14667:     open(my $config,"<","$perlvar{'lonTabDir'}/packages.tab");
14668: 
14669:     while (my $configline=<$config>) {
14670: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
14671: 	chomp($configline);
14672: 	my ($short,$plain)=split(/:/,$configline);
14673: 	my ($pack,$name)=split(/\&/,$short);
14674: 	if ($plain ne '') {
14675: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
14676: 	    $packagetab{$short}=$plain; 
14677: 	}
14678:     }
14679:     close($config);
14680: }
14681: 
14682: # ---------------------------------------------------------- Read loncaparev table
14683: 
14684: &load_loncaparevs();
14685: 
14686: # ---------------------------------------------------------- Read serverhostID table
14687: 
14688: &load_serverhomeIDs();
14689: 
14690: # ---------------------------------------------------------- Read releaseslist XML
14691: {
14692:     my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
14693:     if (-e $file) {
14694:         my $parser = HTML::LCParser->new($file);
14695:         while (my $token = $parser->get_token()) {
14696:             if ($token->[0] eq 'S') {
14697:                 my $item = $token->[1];
14698:                 my $name = $token->[2]{'name'};
14699:                 my $value = $token->[2]{'value'};
14700:                 my $valuematch = $token->[2]{'valuematch'};
14701:                 my $namematch = $token->[2]{'namematch'};
14702:                 if ($item eq 'parameter') {
14703:                     if (($namematch ne '') || (($name ne '') && ($value ne '' || $valuematch ne ''))) {
14704:                         my $release = $parser->get_text();
14705:                         $release =~ s/(^\s*|\s*$ )//gx;
14706:                         $needsrelease{$item.':'.$name.':'.$value.':'.$valuematch.':'.$namematch} = $release;
14707:                     }
14708:                 } elsif ($item ne '' && $name ne '') {
14709:                     my $release = $parser->get_text();
14710:                     $release =~ s/(^\s*|\s*$ )//gx;
14711:                     $needsrelease{$item.':'.$name.':'.$value} = $release;
14712:                 }
14713:             }
14714:         }
14715:     }
14716: }
14717: 
14718: # ---------------------------------------------------------- Read managers table
14719: {
14720:     if (-e "$perlvar{'lonTabDir'}/managers.tab") {
14721:         if (open(my $config,"<","$perlvar{'lonTabDir'}/managers.tab")) {
14722:             while (my $configline=<$config>) {
14723:                 chomp($configline);
14724:                 next if ($configline =~ /^\#/);
14725:                 if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
14726:                     $managerstab{$configline} = 1;
14727:                 }
14728:             }
14729:             close($config);
14730:         }
14731:     }
14732: }
14733: 
14734: # ------------- set up temporary directory
14735: {
14736:     $tmpdir = LONCAPA::tempdir();
14737: 
14738: }
14739: 
14740: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
14741: 				'compress_threshold'=> 20_000,
14742:  			        });
14743: 
14744: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
14745: $dumpcount=0;
14746: $locknum=0;
14747: 
14748: &logtouch();
14749: &logthis('<font color="yellow">INFO: Read configuration</font>');
14750: $readit=1;
14751:     {
14752: 	use integer;
14753: 	my $test=(2**32)+1;
14754: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
14755: 	&logthis(" Detected 64bit platform ($_64bit)");
14756:     }
14757: }
14758: }
14759: 
14760: 1;
14761: __END__
14762: 
14763: =pod
14764: 
14765: =head1 NAME
14766: 
14767: Apache::lonnet - Subroutines to ask questions about things in the network.
14768: 
14769: =head1 SYNOPSIS
14770: 
14771: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
14772: 
14773:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
14774: 
14775: Common parameters:
14776: 
14777: =over 4
14778: 
14779: =item *
14780: 
14781: $uname : an internal username (if $cname expecting a course Id specifically)
14782: 
14783: =item *
14784: 
14785: $udom : a domain (if $cdom expecting a course's domain specifically)
14786: 
14787: =item *
14788: 
14789: $symb : a resource instance identifier
14790: 
14791: =item *
14792: 
14793: $namespace : the name of a .db file that contains the data needed or
14794: being set.
14795: 
14796: =back
14797: 
14798: =head1 OVERVIEW
14799: 
14800: lonnet provides subroutines which interact with the
14801: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
14802: about classes, users, and resources.
14803: 
14804: For many of these objects you can also use this to store data about
14805: them or modify them in various ways.
14806: 
14807: =head2 Symbs
14808: 
14809: To identify a specific instance of a resource, LON-CAPA uses symbols
14810: or "symbs"X<symb>. These identifiers are built from the URL of the
14811: map, the resource number of the resource in the map, and the URL of
14812: the resource itself. The latter is somewhat redundant, but might help
14813: if maps change.
14814: 
14815: An example is
14816: 
14817:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
14818: 
14819: The respective map entry is
14820: 
14821:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
14822:   title="Problem 2">
14823:  </resource>
14824: 
14825: Symbs are used by the random number generator, as well as to store and
14826: restore data specific to a certain instance of for example a problem.
14827: 
14828: =head2 Storing And Retrieving Data
14829: 
14830: X<store()>X<cstore()>X<restore()>Three of the most important functions
14831: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
14832: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
14833: is is the non-critical message twin of cstore. These functions are for
14834: handlers to store a perl hash to a user's permanent data space in an
14835: easy manner, and to retrieve it again on another call. It is expected
14836: that a handler would use this once at the beginning to retrieve data,
14837: and then again once at the end to send only the new data back.
14838: 
14839: The data is stored in the user's data directory on the user's
14840: homeserver under the ID of the course.
14841: 
14842: The hash that is returned by restore will have all of the previous
14843: value for all of the elements of the hash.
14844: 
14845: Example:
14846: 
14847:  #creating a hash
14848:  my %hash;
14849:  $hash{'foo'}='bar';
14850: 
14851:  #storing it
14852:  &Apache::lonnet::cstore(\%hash);
14853: 
14854:  #changing a value
14855:  $hash{'foo'}='notbar';
14856: 
14857:  #adding a new value
14858:  $hash{'bar'}='foo';
14859:  &Apache::lonnet::cstore(\%hash);
14860: 
14861:  #retrieving the hash
14862:  my %history=&Apache::lonnet::restore();
14863: 
14864:  #print the hash
14865:  foreach my $key (sort(keys(%history))) {
14866:    print("\%history{$key} = $history{$key}");
14867:  }
14868: 
14869: Will print out:
14870: 
14871:  %history{1:foo} = bar
14872:  %history{1:keys} = foo:timestamp
14873:  %history{1:timestamp} = 990455579
14874:  %history{2:bar} = foo
14875:  %history{2:foo} = notbar
14876:  %history{2:keys} = foo:bar:timestamp
14877:  %history{2:timestamp} = 990455580
14878:  %history{bar} = foo
14879:  %history{foo} = notbar
14880:  %history{timestamp} = 990455580
14881:  %history{version} = 2
14882: 
14883: Note that the special hash entries C<keys>, C<version> and
14884: C<timestamp> were added to the hash. C<version> will be equal to the
14885: total number of versions of the data that have been stored. The
14886: C<timestamp> attribute will be the UNIX time the hash was
14887: stored. C<keys> is available in every historical section to list which
14888: keys were added or changed at a specific historical revision of a
14889: hash.
14890: 
14891: B<Warning>: do not store the hash that restore returns directly. This
14892: will cause a mess since it will restore the historical keys as if the
14893: were new keys. I.E. 1:foo will become 1:1:foo etc.
14894: 
14895: Calling convention:
14896: 
14897:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname);
14898:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$laststore);
14899: 
14900: For more detailed information, see lonnet specific documentation.
14901: 
14902: =head1 RETURN MESSAGES
14903: 
14904: =over 4
14905: 
14906: =item * B<con_lost>: unable to contact remote host
14907: 
14908: =item * B<con_delayed>: unable to contact remote host, message will be delivered
14909: when the connection is brought back up
14910: 
14911: =item * B<con_failed>: unable to contact remote host and unable to save message
14912: for later delivery
14913: 
14914: =item * B<error:>: an error a occurred, a description of the error follows the :
14915: 
14916: =item * B<no_such_host>: unable to fund a host associated with the user/domain
14917: that was requested
14918: 
14919: =back
14920: 
14921: =head1 PUBLIC SUBROUTINES
14922: 
14923: =head2 Session Environment Functions
14924: 
14925: =over 4
14926: 
14927: =item * 
14928: X<appenv()>
14929: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
14930: the user envirnoment file, and will be restored for each access this
14931: user makes during this session, also modifies the %env for the current
14932: process. Optional rolesarrayref - if defined contains a reference to an array
14933: of roles which are exempt from the restriction on modifying user.role entries 
14934: in the user's environment.db and in %env.    
14935: 
14936: =item *
14937: X<delenv()>
14938: B<delenv($delthis,$regexp)>: removes all items from the session
14939: environment file that begin with $delthis. If the 
14940: optional second arg - $regexp - is true, $delthis is treated as a 
14941: regular expression, otherwise \Q$delthis\E is used. 
14942: The values are also deleted from the current processes %env.
14943: 
14944: =item * get_env_multiple($name) 
14945: 
14946: gets $name from the %env hash, it seemlessly handles the cases where multiple
14947: values may be defined and end up as an array ref.
14948: 
14949: returns an array of values
14950: 
14951: =back
14952: 
14953: =head2 User Information
14954: 
14955: =over 4
14956: 
14957: =item *
14958: X<queryauthenticate()>
14959: B<queryauthenticate($uname,$udom)>: try to determine user's current 
14960: authentication scheme
14961: 
14962: =item *
14963: X<authenticate()>
14964: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
14965: authenticate user from domain's lib servers (first use the current
14966: one). C<$upass> should be the users password.
14967: $checkdefauth is optional (value is 1 if a check should be made to
14968:    authenticate user using default authentication method, and allow
14969:    account creation if username does not have account in the domain).
14970: $clientcancheckhost is optional (value is 1 if checking whether the
14971:    server can host will occur on the client side in lonauth.pm).   
14972: 
14973: =item *
14974: X<homeserver()>
14975: B<homeserver($uname,$udom)>: find the server which has
14976: the user's directory and files (there must be only one), this caches
14977: the answer, and also caches if there is a borken connection.
14978: 
14979: =item *
14980: X<idget()>
14981: B<idget($udom,$idsref,$namespace)>: find the usernames behind either 
14982: a list of student/employee IDs or clicker IDs
14983: (student/employee IDs are a unique resource in a domain, there must be 
14984: only 1 ID per username, and only 1 username per ID in a specific domain).
14985: clickerIDs are not necessarily unique, as students might share clickers.
14986: (returns hash: id=>name,id=>name)
14987: 
14988: =item *
14989: X<idrget()>
14990: B<idrget($udom,@unames)>: find the IDs behind a list of
14991: usernames (returns hash: name=>id,name=>id)
14992: 
14993: =item *
14994: X<idput()>
14995: B<idput($udom,$idsref,$uhome,$namespace)>: store away a list of 
14996: names and associated student/employee IDs or clicker IDs.
14997: 
14998: =item *
14999: X<iddel()>
15000: B<iddel($udom,$idshashref,$uhome,$namespace)>: delete unwanted 
15001: student/employee ID or clicker ID username look-ups from domain.
15002: The homeserver ($uhome) and namespace ($namespace) are optional.
15003: If no $uhome is provided, it will be determined usig &homeserver()
15004: for each user.  If no $namespace is provided, the default is ids.
15005: 
15006: =item *
15007: X<updateclickers()>
15008: B<updateclickers($udom,$action,$idshashref,$uhome,$critical)>: update 
15009: clicker ID-to-username look-ups in clickers.db on library server.
15010: Permitted actions are add or del (i.e., add or delete). The 
15011: clickers.db contains clickerID as keys (escaped), and each corresponding
15012: value is an escaped comma-separated list of usernames (for whom the
15013: library server is the homeserver), who registered that particular ID.
15014: If $critical is true, the update will be sent via &critical, otherwise
15015: &reply() will be used.
15016: 
15017: =item *
15018: X<rolesinit()>
15019: B<rolesinit($udom,$username)>: get user privileges.
15020: returns user role, first access and timer interval hashes
15021: 
15022: =item *
15023: X<privileged()>
15024: B<privileged($username,$domain)>: returns a true if user has a
15025: privileged and active role (i.e. su or dc), false otherwise.
15026: 
15027: =item *
15028: X<getsection()>
15029: B<getsection($udom,$uname,$cname)>: finds the section of student in the
15030: course $cname, return section name/number or '' for "not in course"
15031: and '-1' for "no section"
15032: 
15033: =item *
15034: X<userenvironment()>
15035: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
15036: passed in @what from the requested user's environment, returns a hash
15037: 
15038: =item * 
15039: X<userlog_query()>
15040: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
15041: activity.log file. %filters defines filters applied when parsing the
15042: log file. These can be start or end timestamps, or the type of action
15043: - log to look for Login or Logout events, check for Checkin or
15044: Checkout, role for role selection. The response is in the form
15045: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
15046: escaped strings of the action recorded in the activity.log file.
15047: 
15048: =back
15049: 
15050: =head2 User Roles
15051: 
15052: =over 4
15053: 
15054: =item *
15055: 
15056: allowed($priv,$uri,$symb,$role,$clientip,$noblockcheck) : check for a user privilege; 
15057: returns codes for allowed actions.
15058: 
15059: The first argument is required, all others are optional.
15060: 
15061: $priv is the privilege being checked.
15062: $uri contains additional information about what is being checked for access (e.g.,
15063: URL, course ID etc.). 
15064: $symb is the unique resource instance identifier in a course; if needed,
15065: but not provided, it will be retrieved via a call to &symbread(). 
15066: $role is the role for which a priv is being checked (only used if priv is evb). 
15067: $clientip is the user's IP address (only used when checking for access to portfolio 
15068: files).
15069: $noblockcheck, if true, skips calls to &has_comm_blocking() for the bre priv. This 
15070: prevents recursive calls to &allowed.
15071: 
15072:  F: full access
15073:  U,I,K: authentication modes (cxx only)
15074:  '': forbidden
15075:  1: user needs to choose course
15076:  2: browse allowed
15077:  A: passphrase authentication needed
15078:  B: access temporarily blocked because of a blocking event in a course.
15079:  D: access blocked because access is required via session initiated via deep-link 
15080: 
15081: =item *
15082: 
15083: constructaccess($url,$setpriv) : check for access to construction space URL
15084: 
15085: See if the owner domain and name in the URL match those in the
15086: expected environment.  If so, return three element list
15087: ($ownername,$ownerdomain,$ownerhome).
15088: 
15089: Otherwise return the null string.
15090: 
15091: If second argument 'setpriv' is true, it assigns the privileges,
15092: and returns the same three element list, unless the owner has
15093: blocked "ad hoc" Domain Coordinator access to the Author Space,
15094: in which case the null string is returned.
15095: 
15096: =item *
15097: 
15098: definerole($rolename,$sysrole,$domrole,$courole,$uname,$udom) : define role;
15099: define a custom role rolename set privileges in format of lonTabs/roles.tab
15100: for system, domain, and course level. $uname and $udom are optional (current
15101: user's username and domain will be used when either of $uname or $udom are absent.
15102: 
15103: =item *
15104: 
15105: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
15106: (rolesplain.tab); plain text explanation of a user role term.
15107: $type is Course (default) or Community.
15108: If $forcedefault evaluates to true, text returned will be default 
15109: text for $type. Otherwise, if this is a course, the text returned 
15110: will be a custom name for the role (if defined in the course's 
15111: environment).  If no custom name is defined the default is returned.
15112:    
15113: =item *
15114: 
15115: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv) :
15116: All arguments are optional. Returns a hash of a roles, either for
15117: co-author/assistant author roles for a user's Construction Space
15118: (default), or if $context is 'userroles', roles for the user himself,
15119: In the hash, keys are set to colon-separated $uname,$udom,$role, and
15120: (optionally) if $withsec is true, a fourth colon-separated item - $section.
15121: For each key, value is set to colon-separated start and end times for
15122: the role.  If no username and domain are specified, will default to
15123: current user/domain. Types, roles, and roledoms are references to arrays
15124: of role statuses (active, future or previous), roles 
15125: (e.g., cc,in, st etc.) and domains of the roles which can be used
15126: to restrict the list of roles reported. If no array ref is 
15127: provided for types, will default to return only active roles.
15128: 
15129: =item *
15130: 
15131: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
15132: user: $uname:$udom has a role in the course: $cdom_$cnum. 
15133: 
15134: Additional optional arguments are: $type (if role checking is to be restricted 
15135: to certain user status types -- previous (expired roles), active (currently
15136: available roles) or future (roles available in the future), and
15137: $hideprivileged -- if true will not report course roles for users who
15138: have active Domain Coordinator role in course's domain or in additional
15139: domains (specified in 'Domains to check for privileged users' in course
15140: environment -- set via:  Course Settings -> Classlists and staff listing).
15141: 
15142: =item *
15143: 
15144: privileged($username,$domain,$possdomains,$possroles) : returns 1 if user
15145: $username:$domain is a privileged user (e.g., Domain Coordinator or Super User)
15146: $possdomains and $possroles are optional array refs -- to domains to check and
15147: roles to check.  If $possdomains is not specified, a dump will be done of the
15148: users' roles.db to check for a dc or su role in any domain. This can be
15149: time consuming if &privileged is called repeatedly (e.g., when displaying a
15150: classlist), so in such cases, supplying a $possdomains array is preferred, as
15151: this then allows &privileged_by_domain() to be used, which caches the identity
15152: of privileged users, eliminating the need for repeated calls to &dump().
15153: 
15154: =item *
15155: 
15156: privileged_by_domain($possdomains,$roles) : returns a hash of a hash of a hash,
15157: where the outer hash keys are domains specified in the $possdomains array ref,
15158: next inner hash keys are privileged roles specified in the $roles array ref,
15159: and the innermost hash contains key = value pairs for username:domain = end:start
15160: for active or future "privileged" users with that role in that domain. To avoid
15161: repeated dumps of domain roles -- via &get_domain_roles() -- contents of the
15162: innerhash are cached using priv_$role and $dom as the identifiers.
15163: 
15164: =back
15165: 
15166: =head2 User Modification
15167: 
15168: =over 4
15169: 
15170: =item *
15171: 
15172: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
15173: user for the level given by URL.  Optional start and end dates (leave empty
15174: string or zero for "no date")
15175: 
15176: =item *
15177: 
15178: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
15179: change a users, password, possible return values are: ok,
15180: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
15181: refused
15182: 
15183: =item *
15184: 
15185: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
15186: 
15187: =item *
15188: 
15189: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
15190:            $forceid,$desiredhome,$email,$inststatus,$candelete) :
15191: 
15192: will update user information (firstname,middlename,lastname,generation,
15193: permanentemail), and if forceid is true, student/employee ID also.
15194: A user's institutional affiliation(s) can also be updated.
15195: User information fields will not be overwritten with empty entries 
15196: unless the field is included in the $candelete array reference.
15197: This array is included when a single user is modified via "Manage Users",
15198: or when Autoupdate.pl is run by cron in a domain.
15199: 
15200: =item *
15201: 
15202: modifystudent
15203: 
15204: modify a student's enrollment and identification information.
15205: The course id is resolved based on the current user's environment.  
15206: This means the invoking user must be a course coordinator or otherwise
15207: associated with a course.
15208: 
15209: This call is essentially a wrapper for lonnet::modifyuser and
15210: lonnet::modify_student_enrollment
15211: 
15212: Inputs: 
15213: 
15214: =over 4
15215: 
15216: =item B<$udom> Student's loncapa domain
15217: 
15218: =item B<$uname> Student's loncapa login name
15219: 
15220: =item B<$uid> Student/Employee ID
15221: 
15222: =item B<$umode> Student's authentication mode
15223: 
15224: =item B<$upass> Student's password
15225: 
15226: =item B<$first> Student's first name
15227: 
15228: =item B<$middle> Student's middle name
15229: 
15230: =item B<$last> Student's last name
15231: 
15232: =item B<$gene> Student's generation
15233: 
15234: =item B<$usec> Student's section in course
15235: 
15236: =item B<$end> Unix time of the roles expiration
15237: 
15238: =item B<$start> Unix time of the roles start date
15239: 
15240: =item B<$forceid> If defined, allow $uid to be changed
15241: 
15242: =item B<$desiredhome> server to use as home server for student
15243: 
15244: =item B<$email> Student's permanent e-mail address
15245: 
15246: =item B<$type> Type of enrollment (auto or manual)
15247: 
15248: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
15249: 
15250: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
15251: 
15252: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
15253: 
15254: =item B<$context> role change context (shown in User Management Logs display in a course)
15255: 
15256: =item B<$inststatus> institutional status of user - : separated string of escaped status types
15257: 
15258: =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.
15259: 
15260: =back
15261: 
15262: =item *
15263: 
15264: modify_student_enrollment
15265: 
15266: Change a student's enrollment status in a class.  The environment variable
15267: 'role.request.course' must be defined for this function to proceed.
15268: 
15269: Inputs:
15270: 
15271: =over 4
15272: 
15273: =item $udom, student's domain
15274: 
15275: =item $uname, student's name
15276: 
15277: =item $uid, student's user id
15278: 
15279: =item $first, student's first name
15280: 
15281: =item $middle
15282: 
15283: =item $last
15284: 
15285: =item $gene
15286: 
15287: =item $usec
15288: 
15289: =item $end
15290: 
15291: =item $start
15292: 
15293: =item $type
15294: 
15295: =item $locktype
15296: 
15297: =item $cid
15298: 
15299: =item $selfenroll
15300: 
15301: =item $context
15302: 
15303: =item $credits, number of credits student will earn from this class
15304: 
15305: =item $instsec, institutional course section code for student
15306: 
15307: =back
15308: 
15309: 
15310: =item *
15311: 
15312: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
15313: custom role; give a custom role to a user for the level given by URL.  Specify
15314: name and domain of role author, and role name
15315: 
15316: =item *
15317: 
15318: revokerole($udom,$uname,$url,$role) : revoke a role for url
15319: 
15320: =item *
15321: 
15322: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
15323: 
15324: =back
15325: 
15326: =head2 Course Infomation
15327: 
15328: =over 4
15329: 
15330: =item *
15331: 
15332: coursedescription($courseid,$options) : returns a hash of information about the
15333: specified course id, including all environment settings for the
15334: course, the description of the course will be in the hash under the
15335: key 'description'
15336: 
15337: $options is an optional parameter that if supplied is a hash reference that controls
15338: what how this function works.  It has the following key/values:
15339: 
15340: =over 4
15341: 
15342: =item freshen_cache
15343: 
15344: If defined, and the environment cache for the course is valid, it is 
15345: returned in the returned hash.
15346: 
15347: =item one_time
15348: 
15349: If defined, the last cache time is set to _now_
15350: 
15351: =item user
15352: 
15353: If defined, the supplied username is used instead of the current user.
15354: 
15355: 
15356: =back
15357: 
15358: =item *
15359: 
15360: resdata($name,$domain,$type,@which) : request for current parameter
15361: setting for a specific $type, where $type is either 'course' or 'user',
15362: @what should be a list of parameters to ask about. This routine caches
15363: answers for 10 minutes.
15364: 
15365: =item *
15366: 
15367: get_courseresdata($courseid, $domain) : dump the entire course resource
15368: data base, returning a hash that is keyed by the resource name and has
15369: values that are the resource value.  I believe that the timestamps and
15370: versions are also returned.
15371: 
15372: get_numsuppfiles($cnum,$cdom) : retrieve number of files in a course's
15373: supplemental content area. This routine caches the number of files for 
15374: 10 minutes.
15375: 
15376: =back
15377: 
15378: =head2 Course Modification
15379: 
15380: =over 4
15381: 
15382: =item *
15383: 
15384: writecoursepref($courseid,%prefs) : write preferences (environment
15385: database) for a course
15386: 
15387: =item *
15388: 
15389: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
15390: 
15391: =item *
15392: 
15393: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
15394: 
15395: =item *
15396: 
15397: is_course($courseid), is_course($cdom, $cnum)
15398: 
15399: Accepts either a combined $courseid (in the form of domain_courseid) or the
15400: two component version $cdom, $cnum. It checks if the specified course exists.
15401: 
15402: Returns:
15403:     undef if the course doesn't exist, otherwise
15404:     in scalar context the combined courseid.
15405:     in list context the two components of the course identifier, domain and 
15406:     courseid.    
15407: 
15408: =back
15409: 
15410: =head2 Bubblesheet Configuration
15411: 
15412: =over 4
15413: 
15414: =item *
15415: 
15416: get_scantron_config($which)
15417: 
15418: $which - the name of the configuration to parse from the file.
15419: 
15420: Parses and returns the bubblesheet configuration line selected as a
15421: hash of configuration file fields.
15422: 
15423: 
15424: Returns:
15425:     If the named configuration is not in the file, an empty
15426:     hash is returned.
15427: 
15428:     a hash with the fields
15429:       name         - internal name for the this configuration setup
15430:       description  - text to display to operator that describes this config
15431:       CODElocation - if 0 or the string 'none'
15432:                           - no CODE exists for this config
15433:                      if -1 || the string 'letter'
15434:                           - a CODE exists for this config and is
15435:                             a string of letters
15436:                      Unsupported value (but planned for future support)
15437:                           if a positive integer
15438:                                - The CODE exists as the first n items from
15439:                                  the question section of the form
15440:                           if the string 'number'
15441:                                - The CODE exists for this config and is
15442:                                  a string of numbers
15443:       CODEstart   - (only matter if a CODE exists) column in the line where
15444:                      the CODE starts
15445:       CODElength  - length of the CODE
15446:       IDstart     - column where the student/employee ID starts
15447:       IDlength    - length of the student/employee ID info
15448:       Qstart      - column where the information from the bubbled
15449:                     'questions' start
15450:       Qlength     - number of columns comprising a single bubble line from
15451:                     the sheet. (usually either 1 or 10)
15452:       Qon         - either a single character representing the character used
15453:                     to signal a bubble was chosen in the positional setup, or
15454:                     the string 'letter' if the letter of the chosen bubble is
15455:                     in the final, or 'number' if a number representing the
15456:                     chosen bubble is in the file (1->A 0->J)
15457:       Qoff        - the character used to represent that a bubble was
15458:                     left blank
15459:       PaperID     - if the scanning process generates a unique number for each
15460:                     sheet scanned the column that this ID number starts in
15461:       PaperIDlength - number of columns that comprise the unique ID number
15462:                       for the sheet of paper
15463:       FirstName   - column that the first name starts in
15464:       FirstNameLength - number of columns that the first name spans
15465: 
15466:       LastName    - column that the last name starts in
15467:       LastNameLength - number of columns that the last name spans
15468:       BubblesPerRow - number of bubbles available in each row used to
15469:                       bubble an answer. (If not specified, 10 assumed).
15470: 
15471: 
15472: =item *
15473: 
15474: get_scantronformat_file($cdom)
15475: 
15476: $cdom - the course's domain (optional); if not supplied, uses
15477: domain for current $env{'request.course.id'}.
15478: 
15479: Returns an array containing lines from the scantron format file for
15480: the domain of the course.
15481: 
15482: If a url for a custom.tab file is listed in domain's configuration.db,
15483: lines are from this file.
15484: 
15485: Otherwise, if a default.tab has been published in RES space by the
15486: domainconfig user, lines are from this file.
15487: 
15488: Otherwise, fall back to getting lines from the legacy file on the
15489: local server:  /home/httpd/lonTabs/default_scantronformat.tab
15490: 
15491: =back
15492: 
15493: =head2 Resource Subroutines
15494: 
15495: =over 4
15496: 
15497: =item *
15498: 
15499: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
15500: 
15501: =item *
15502: 
15503: repcopy($filename) : subscribes to the requested file, and attempts to
15504: replicate from the owning library server, Might return
15505: 'unavailable', 'not_found', 'forbidden', 'ok', or
15506: 'bad_request', also attempts to grab the metadata for the
15507: resource. Expects the local filesystem pathname
15508: (/home/httpd/html/res/....)
15509: 
15510: =back
15511: 
15512: =head2 Resource Information
15513: 
15514: =over 4
15515: 
15516: =item *
15517: 
15518: EXT($varname,$symb,$udom,$uname,$usection,$recurse,$cid) : evaluates 
15519: and returns the value of a variety of different possible values,
15520: $varname should be a request string, and the other parameters can be
15521: used to specify who and what one is asking about. Ordinarily, $cid 
15522: does not need to be specified, as it is retrived from 
15523: $env{'request.course.id'}, but &Apache::lonnet::EXT() is called
15524: within lonuserstate::loadmap() when initializing a course, before
15525: $env{'request.course.id'} has been set, so it needs to be provided
15526: in that one case.
15527: 
15528: Possible values for $varname are environment.lastname (or other item
15529: from the envirnment hash), user.name (or someother aspect about the
15530: user), resource.0.maxtries (or some other part and parameter of a
15531: resource)
15532: 
15533: =item *
15534: 
15535: directcondval($number) : get current value of a condition; reads from a state
15536: string
15537: 
15538: =item *
15539: 
15540: condval($condidx) : value of condition index based on state
15541: 
15542: =item *
15543: 
15544: metadata($uri,$what,$toolsymb,$liburi,$prefix,$depthcount) : request a
15545: resource's metadata, $what should be either a specific key, or either
15546: 'keys' (to get a list of possible keys) or 'packages' to get a list of
15547: packages that this resource currently uses, the last 3 arguments are 
15548: only used internally for recursive metadata.
15549: 
15550: the toolsymb is only used where the uri is for an external tool (for which
15551: the uri as well as the symb are guaranteed to be unique).
15552: 
15553: this function automatically caches all requests except any made recursively
15554: to retrieve a list of metadata keys for an imported library file ($liburi is 
15555: defined).
15556: 
15557: =item *
15558: 
15559: metadata_query($query,$custom,$customshow) : make a metadata query against the
15560: network of library servers; returns file handle of where SQL and regex results
15561: will be stored for query
15562: 
15563: =item *
15564: 
15565: symbread($filename,$donotrecurse,$ignorecachednull,$checkforblock,$possibles) : 
15566: return symbolic list entry (all arguments optional). 
15567: 
15568: Args: filename is the filename (including path) for the file for which a symb 
15569: is required; donotrecurse, if true will prevent calls to allowed() being made 
15570: to check access status if more than one resource was found in the bighash 
15571: (see rev. 1.249) to avoid an infinite loop if an ambiguous resource is part of 
15572: a randompick); ignorecachednull, if true will prevent a symb of '' being 
15573: returned if $env{$cache_str} is defined as ''; checkforblock if true will
15574: cause possible symbs to be checked to determine if they are subject to content
15575: blocking, if so they will not be included as possible symbs; possibles is a
15576: ref to a hash, which, as a side effect, will be populated with all possible 
15577: symbs (content blocking not tested).
15578:  
15579: returns the data handle
15580: 
15581: =item *
15582: 
15583: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
15584: and is a possible symb for the URL in $thisfn, and if is an encrypted
15585: resource that the user accessed using /enc/ returns a 1 on success, 0
15586: on failure, user must be in a course, as it assumes the existence of
15587: the course initial hash, and uses $env('request.course.id'}.  The third
15588: arg is an optional reference to a scalar.  If this arg is passed in the 
15589: call to symbverify, it will be set to 1 if the symb has been set to be 
15590: encrypted; otherwise it will be null.  
15591: 
15592: =item *
15593: 
15594: symbclean($symb) : removes versions numbers from a symb, returns the
15595: cleaned symb
15596: 
15597: =item *
15598: 
15599: is_on_map($uri) : checks if the $uri is somewhere on the current
15600: course map, user must be in a course for it to work.
15601: 
15602: =item *
15603: 
15604: numval($salt) : return random seed value (addend for rndseed)
15605: 
15606: =item *
15607: 
15608: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
15609: a random seed, all arguments are optional, if they aren't sent it uses the
15610: environment to derive them. Note: if symb isn't sent and it can't get one
15611: from &symbread it will use the current time as its return value
15612: 
15613: =item *
15614: 
15615: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
15616: unfakeable, receipt
15617: 
15618: =item *
15619: 
15620: receipt() : API to ireceipt working off of env values; given out to users
15621: 
15622: =item *
15623: 
15624: countacc($url) : count the number of accesses to a given URL
15625: 
15626: =item *
15627: 
15628: 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
15629: 
15630: =item *
15631: 
15632: 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)
15633: 
15634: =item *
15635: 
15636: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
15637: 
15638: =item *
15639: 
15640: devalidate($symb) : devalidate temporary spreadsheet calculations,
15641: forcing spreadsheet to reevaluate the resource scores next time.
15642: 
15643: =item * 
15644: 
15645: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
15646: when viewing in course context.
15647: 
15648:  input: six args -- filename (decluttered), course number, course domain,
15649:                     url, symb (if registered) and group (if this is a 
15650:                     group item -- e.g., bulletin board, group page etc.).
15651: 
15652:  output: array of five scalars --
15653:          $cfile -- url for file editing if editable on current server
15654:          $home -- homeserver of resource (i.e., for author if published,
15655:                                           or course if uploaded.).
15656:          $switchserver --  1 if server switch will be needed.
15657:          $forceedit -- 1 if icon/link should be to go to edit mode 
15658:          $forceview -- 1 if icon/link should be to go to view mode
15659: 
15660: =item *
15661: 
15662: is_course_upload($file,$cnum,$cdom)
15663: 
15664: Used in course context to determine if current file was uploaded to 
15665: the course (i.e., would be found in /userfiles/docs on the course's 
15666: homeserver.
15667: 
15668:   input: 3 args -- filename (decluttered), course number and course domain.
15669:   output: boolean -- 1 if file was uploaded.
15670: 
15671: =back
15672: 
15673: =head2 Storing/Retreiving Data
15674: 
15675: =over 4
15676: 
15677: =item *
15678: 
15679: store($storehash,$symb,$namespace,$udom,$uname,$laststore) : stores hash
15680: permanently for this url; hashref needs to be given and should be a \%hashname;
15681: the remaining args aren't required and if they aren't passed or are '' they will
15682: be derived from the env (with the exception of $laststore, which is an 
15683: optional arg used when a user's submission is stored in grading).
15684: $laststore is $version=$timestamp, where $version is the most recent version
15685: number retrieved for the corresponding $symb in the $namespace db file, and
15686: $timestamp is the timestamp for that transaction (UNIX time).
15687: $laststore is currently only passed when cstore() is called by 
15688: structuretags::finalize_storage().
15689: 
15690: =item *
15691: 
15692: cstore($storehash,$symb,$namespace,$udom,$uname,$laststore) : same as store
15693: but uses critical subroutine
15694: 
15695: =item *
15696: 
15697: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
15698: all args are optional
15699: 
15700: =item *
15701: 
15702: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
15703: dumps the complete (or key matching regexp) namespace into a hash
15704: ($udom, $uname, $regexp, $range are optional) for a namespace that is
15705: normally &store()ed into
15706: 
15707: $range should be either an integer '100' (give me the first 100
15708:                                            matching records)
15709:               or be  two integers sperated by a - with no spaces
15710:                  '30-50' (give me the 30th through the 50th matching
15711:                           records)
15712: 
15713: 
15714: =item *
15715: 
15716: putstore($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog) :
15717: replaces a &store() version of data with a replacement set of data
15718: for a particular resource in a namespace passed in the $storehash hash 
15719: reference. If $tolog is true, the transaction is logged in the courselog
15720: with an action=PUTSTORE.
15721: 
15722: =item *
15723: 
15724: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
15725: works very similar to store/cstore, but all data is stored in a
15726: temporary location and can be reset using tmpreset, $storehash should
15727: be a hash reference, returns nothing on success
15728: 
15729: =item *
15730: 
15731: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
15732: similar to restore, but all data is stored in a temporary location and
15733: can be reset using tmpreset. Returns a hash of values on success,
15734: error string otherwise.
15735: 
15736: =item *
15737: 
15738: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
15739: deltes all keys for $symb form the temporary storage hash.
15740: 
15741: =item *
15742: 
15743: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
15744: reference filled in from namesp ($udom and $uname are optional)
15745: 
15746: =item *
15747: 
15748: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
15749: namesp ($udom and $uname are optional)
15750: 
15751: =item *
15752: 
15753: dump($namespace,$udom,$uname,$regexp,$range) : 
15754: dumps the complete (or key matching regexp) namespace into a hash
15755: ($udom, $uname, $regexp, $range are optional)
15756: 
15757: $range should be either an integer '100' (give me the first 100
15758:                                            matching records)
15759:               or be  two integers sperated by a - with no spaces
15760:                  '30-50' (give me the 30th through the 50th matching
15761:                           records)
15762: =item *
15763: 
15764: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
15765: $store can be a scalar, an array reference, or if the amount to be 
15766: incremented is > 1, a hash reference.
15767: 
15768: ($udom and $uname are optional)
15769: 
15770: =item *
15771: 
15772: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
15773: ($udom and $uname are optional)
15774: 
15775: =item *
15776: 
15777: cput($namespace,$storehash,$udom,$uname) : critical put
15778: ($udom and $uname are optional)
15779: 
15780: =item *
15781: 
15782: newput($namespace,$storehash,$udom,$uname) :
15783: 
15784: Attempts to store the items in the $storehash, but only if they don't
15785: currently exist, if this succeeds you can be certain that you have 
15786: successfully created a new key value pair in the $namespace db.
15787: 
15788: 
15789: Args:
15790:  $namespace: name of database to store values to
15791:  $storehash: hashref to store to the db
15792:  $udom: (optional) domain of user containing the db
15793:  $uname: (optional) name of user caontaining the db
15794: 
15795: Returns:
15796:  'ok' -> succeeded in storing all keys of $storehash
15797:  'key_exists: <key>' -> failed to anything out of $storehash, as at
15798:                         least <key> already existed in the db (other
15799:                         requested keys may also already exist)
15800:  'error: <msg>' -> unable to tie the DB or other error occurred
15801:  'con_lost' -> unable to contact request server
15802:  'refused' -> action was not allowed by remote machine
15803: 
15804: 
15805: =item *
15806: 
15807: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
15808: reference filled in from namesp (encrypts the return communication)
15809: ($udom and $uname are optional)
15810: 
15811: =item *
15812: 
15813: log($udom,$name,$home,$message) : write to permanent log for user; use
15814: critical subroutine
15815: 
15816: =item *
15817: 
15818: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
15819: array reference filled in from namespace found in domain level on either
15820: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
15821: 
15822: =item *
15823: 
15824: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
15825: domain level either on specified domain server ($uhome) or primary domain 
15826: server ($udom and $uhome are optional)
15827: 
15828: =item * 
15829: 
15830: get_domain_defaults($target_domain,$ignore_cache) : returns hash with defaults 
15831: for: authentication, language, quotas, timezone, date locale, and portal URL in
15832: the target domain.
15833: 
15834: May also include additional key => value pairs for the following groups:
15835: 
15836: =over
15837: 
15838: =item
15839: disk quotas (MB allocated by default to portfolios and authoring spaces).
15840: 
15841: =over
15842: 
15843: =item defaultquota, authorquota
15844: 
15845: =back
15846: 
15847: =item
15848: tools (availability of aboutme page, blog, webDAV access for authoring spaces,
15849: portfolio for users).
15850: 
15851: =over
15852: 
15853: =item
15854: aboutme, blog, webdav, portfolio
15855: 
15856: =back
15857: 
15858: =item
15859: requestcourses: ability to request courses, and how requests are processed.
15860: 
15861: =over
15862: 
15863: =item
15864: official, unofficial, community, textbook, placement
15865: 
15866: =back
15867: 
15868: =item
15869: inststatus: types of institutional affiliation, and order in which they are displayed.
15870: 
15871: =over
15872: 
15873: =item
15874: inststatustypes, inststatusorder, inststatusguest
15875: 
15876: =back
15877: 
15878: =item
15879: coursedefaults: can PDF forms can be created, default credits for courses, default quotas (MB)
15880: for course's uploaded content.
15881: 
15882: =over
15883: 
15884: =item
15885: canuse_pdfforms, officialcredits, unofficialcredits, textbookcredits, officialquota, unofficialquota, 
15886: communityquota, textbookquota, placementquota
15887: 
15888: =back
15889: 
15890: =item
15891: usersessions: set options for hosting of your users in other domains, and hosting of users from other domains
15892: on your servers.
15893: 
15894: =over
15895: 
15896: =item 
15897: remotesessions, hostedsessions
15898: 
15899: =back
15900: 
15901: =back
15902: 
15903: In cases where a domain coordinator has never used the "Set Domain Configuration"
15904: utility to create a configuration.db file on a domain's primary library server 
15905: only the following domain defaults: auth_def, auth_arg_def, lang_def
15906: -- corresponding values are authentication type (internal, krb4, krb5,
15907: or localauth), initial password or a kerberos realm, language (e.g., en-us) -- 
15908: will be available. Values are retrieved from cache (if current), unless the
15909: optional $ignore_cache arg is true, or from domain's configuration.db (if available),
15910: or lastly from values in lonTabs/dns_domain,tab, or lonTabs/domain.tab.
15911: 
15912: Typical usage:
15913: 
15914: %domdefaults = &get_domain_defaults($target_domain);
15915: 
15916: =back
15917: 
15918: =head2 Network Status Functions
15919: 
15920: =over 4
15921: 
15922: =item *
15923: 
15924: dirlist() : return directory list based on URI (first arg).
15925: 
15926: Inputs: 1 required, 5 optional.
15927: 
15928: =over
15929: 
15930: =item 
15931: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
15932: 
15933: =item
15934: $userdomain - domain of user/course to be listed. Extracted from $uri if absent. 
15935: 
15936: =item
15937: $username -  username of user/course to be listed. Extracted from $uri if absent. 
15938: 
15939: =item
15940: $getpropath - boolean: 1 if prepend path using &propath(). 
15941: 
15942: =item
15943: $getuserdir - boolean: 1 if prepend path for "userfiles".
15944: 
15945: =item 
15946: $alternateRoot - path to prepend in place of path from $uri.
15947: 
15948: =back
15949: 
15950: Returns: Array of up to two items.
15951: 
15952: =over
15953: 
15954: a reference to an array of files/subdirectories
15955: 
15956: =over
15957: 
15958: Each element in the array of files/subdirectories is a & separated list of
15959: item name and the result of running stat on the item.  If dirlist was requested
15960: for a file instead of a directory, the item name will be ''. For a directory 
15961: listing, if the item is a metadata file, the element will end &N&M 
15962: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
15963: default copyright set (1).  
15964: 
15965: =back
15966: 
15967: a scalar containing error condition (if encountered).
15968: 
15969: =over
15970: 
15971: =item 
15972: no_host (no homeserver identified for $username:$domain).
15973: 
15974: =item 
15975: no_such_host (server contacted for listing not identified as valid host).
15976: 
15977: =item 
15978: con_lost (connection to remote server failed).
15979: 
15980: =item 
15981: refused (invalid $username:$domain received on lond side).
15982: 
15983: =item 
15984: no_such_dir (directory at specified path on lond side does not exist). 
15985: 
15986: =item 
15987: empty (directory at specified path on lond side is empty).
15988: 
15989: =over
15990: 
15991: This is currently not encountered because the &ls3, &ls2, 
15992: &ls (_handler) routines on the lond side do not filter out
15993: . and .. from a directory listing. 
15994: 
15995: =back
15996: 
15997: =back
15998: 
15999: =back
16000: 
16001: =item *
16002: 
16003: spareserver() : find server with least workload from spare.tab
16004: 
16005: 
16006: =item *
16007: 
16008: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
16009: if there is no corresponding loncapa host.
16010: 
16011: =back
16012: 
16013: 
16014: =head2 Apache Request
16015: 
16016: =over 4
16017: 
16018: =item *
16019: 
16020: ssi($url,%hash) : server side include, does a complete request cycle on url to
16021: localhost, posts hash
16022: 
16023: =back
16024: 
16025: =head2 Data to String to Data
16026: 
16027: =over 4
16028: 
16029: =item *
16030: 
16031: hash2str(%hash) : convert a hash into a string complete with escaping and '='
16032: and '&' separators, supports elements that are arrayrefs and hashrefs
16033: 
16034: =item *
16035: 
16036: hashref2str($hashref) : convert a hashref into a string complete with
16037: escaping and '=' and '&' separators, supports elements that are
16038: arrayrefs and hashrefs
16039: 
16040: =item *
16041: 
16042: arrayref2str($arrayref) : convert an arrayref into a string complete
16043: with escaping and '&' separators, supports elements that are arrayrefs
16044: and hashrefs
16045: 
16046: =item *
16047: 
16048: str2hash($string) : convert string to hash using unescaping and
16049: splitting on '=' and '&', supports elements that are arrayrefs and
16050: hashrefs
16051: 
16052: =item *
16053: 
16054: str2array($string) : convert string to hash using unescaping and
16055: splitting on '&', supports elements that are arrayrefs and hashrefs
16056: 
16057: =back
16058: 
16059: =head2 Logging Routines
16060: 
16061: 
16062: These routines allow one to make log messages in the lonnet.log and
16063: lonnet.perm logfiles.
16064: 
16065: =over 4
16066: 
16067: =item *
16068: 
16069: logtouch() : make sure the logfile, lonnet.log, exists
16070: 
16071: =item *
16072: 
16073: logthis() : append message to the normal lonnet.log file, it gets
16074: preiodically rolled over and deleted.
16075: 
16076: =item *
16077: 
16078: logperm() : append a permanent message to lonnet.perm.log, this log
16079: file never gets deleted by any automated portion of the system, only
16080: messages of critical importance should go in here.
16081: 
16082: 
16083: =back
16084: 
16085: =head2 General File Helper Routines
16086: 
16087: =over 4
16088: 
16089: =item *
16090: 
16091: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
16092: (a) files in /uploaded
16093:   (i) If a local copy of the file exists - 
16094:       compares modification date of local copy with last-modified date for 
16095:       definitive version stored on home server for course. If local copy is 
16096:       stale, requests a new version from the home server and stores it. 
16097:       If the original has been removed from the home server, then local copy 
16098:       is unlinked.
16099:   (ii) If local copy does not exist -
16100:       requests the file from the home server and stores it. 
16101:   
16102:   If $caller is 'uploadrep':  
16103:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
16104:     for request for files originally uploaded via DOCS. 
16105:      - returns 'ok' if fresh local copy now available, -1 otherwise.
16106:   
16107:   Otherwise:
16108:      This indicates a call from the content generation phase of the request.
16109:      -  returns the entire contents of the file or -1.
16110:      
16111: (b) files in /res
16112:    - returns the entire contents of a file or -1; 
16113:    it properly subscribes to and replicates the file if neccessary.
16114: 
16115: 
16116: =item *
16117: 
16118: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
16119:                   reference
16120: 
16121: returns either a stat() list of data about the file or an empty list
16122: if the file doesn't exist or couldn't find out about it (connection
16123: problems or user unknown)
16124: 
16125: =item *
16126: 
16127: filelocation($dir,$file) : returns file system location of a file
16128: based on URI; meant to be "fairly clean" absolute reference, $dir is a
16129: directory that relative $file lookups are to looked in ($dir of /a/dir
16130: and a file of ../bob will become /a/bob)
16131: 
16132: =item *
16133: 
16134: hreflocation($dir,$file) : returns file system location or a URL; same as
16135: filelocation except for hrefs
16136: 
16137: =item *
16138: 
16139: declutter() : declutters URLs -- remove beginning slashes, 'res' etc.
16140: also removes beginning /home/httpd/html unless /priv/ follows it.
16141: 
16142: =back
16143: 
16144: =head2 Usererfile file routines (/uploaded*)
16145: 
16146: =over 4
16147: 
16148: =item *
16149: 
16150: userfileupload(): main rotine for putting a file in a user or course's
16151:                   filespace, arguments are,
16152: 
16153:  formname - required - this is the name of the element in $env where the
16154:            filename, and the contents of the file to create/modifed exist
16155:            the filename is in $env{'form.'.$formname.'.filename'} and the
16156:            contents of the file is located in $env{'form.'.$formname}
16157:  context - if coursedoc, store the file in the course of the active role
16158:              of the current user; 
16159:            if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
16160:            if 'canceloverwrite': delete file in tmp/overwrites directory
16161:  subdir - required - subdirectory to put the file in under ../userfiles/
16162:          if undefined, it will be placed in "unknown"
16163: 
16164:  (This routine calls clean_filename() to remove any dangerous
16165:  characters from the filename, and then calls finuserfileupload() to
16166:  complete the transaction)
16167: 
16168:  returns either the url of the uploaded file (/uploaded/....) if successful
16169:  and /adm/notfound.html if unsuccessful
16170: 
16171: =item *
16172: 
16173: clean_filename(): routine for cleaing a filename up for storage in
16174:                  userfile space, argument is:
16175: 
16176:  filename - proposed filename
16177: 
16178: returns: the new clean filename
16179: 
16180: =item *
16181: 
16182: finishuserfileupload(): routine that creates and sends the file to
16183: userspace, probably shouldn't be called directly
16184: 
16185:   docuname: username or courseid of destination for the file
16186:   docudom: domain of user/course of destination for the file
16187:   formname: same as for userfileupload()
16188:   fname: filename (including subdirectories) for the file
16189:   parser: if 'parse', will parse (html) file to extract references to objects, links etc.
16190:           if hashref, and context is scantron, will convert csv format to standard format
16191:   allfiles: reference to hash used to store objects found by parser
16192:   codebase: reference to hash used for codebases of java objects found by parser
16193:   thumbwidth: width (pixels) of thumbnail to be created for uploaded image
16194:   thumbheight: height (pixels) of thumbnail to be created for uploaded image
16195:   resizewidth: width to be used to resize image using resizeImage from ImageMagick
16196:   resizeheight: height to be used to resize image using resizeImage from ImageMagick
16197:   context: if 'overwrite', will move the uploaded file from its temporary location to
16198:             userfiles to facilitate overwriting a previously uploaded file with same name.
16199:   mimetype: reference to scalar to accommodate mime type determined
16200:             from File::MMagic if $parser = parse.
16201: 
16202:  returns either the url of the uploaded file (/uploaded/....) if successful
16203:  and /adm/notfound.html if unsuccessful (or an error message if context 
16204:  was 'overwrite').
16205:  
16206: 
16207: =item *
16208: 
16209: renameuserfile(): renames an existing userfile to a new name
16210: 
16211:   Args:
16212:    docuname: username or courseid of destination for the file
16213:    docudom: domain of user/course of destination for the file
16214:    old: current file name (including any subdirs under userfiles)
16215:    new: desired file name (including any subdirs under userfiles)
16216: 
16217: =item *
16218: 
16219: mkdiruserfile(): creates a directory is a userfiles dir
16220: 
16221:   Args:
16222:    docuname: username or courseid of destination for the file
16223:    docudom: domain of user/course of destination for the file
16224:    dir: dir to create (including any subdirs under userfiles)
16225: 
16226: =item *
16227: 
16228: removeuserfile(): removes a file that exists in userfiles
16229: 
16230:   Args:
16231:    docuname: username or courseid of destination for the file
16232:    docudom: domain of user/course of destination for the file
16233:    fname: filname to delete (including any subdirs under userfiles)
16234: 
16235: =item *
16236: 
16237: removeuploadedurl(): convience function for removeuserfile()
16238: 
16239:   Args:
16240:    url:  a full /uploaded/... url to delete
16241: 
16242: =item * 
16243: 
16244: get_portfile_permissions():
16245:   Args:
16246:     domain: domain of user or course contain the portfolio files
16247:     user: name of user or num of course contain the portfolio files
16248:   Returns:
16249:     hashref of a dump of the proper file_permissions.db
16250:    
16251: 
16252: =item * 
16253: 
16254: get_access_controls():
16255: 
16256: Args:
16257:   current_permissions: the hash ref returned from get_portfile_permissions()
16258:   group: (optional) the group you want the files associated with
16259:   file: (optional) the file you want access info on
16260: 
16261: Returns:
16262:     a hash (keys are file names) of hashes containing
16263:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
16264:         values are XML containing access control settings (see below) 
16265: 
16266: Internal notes:
16267: 
16268:  access controls are stored in file_permissions.db as key=value pairs.
16269:     key -> path to file/file_name\0uniqueID:scope_end_start
16270:         where scope -> public,guest,course,group,domains or users.
16271:               end -> UNIX time for end of access (0 -> no end date)
16272:               start -> UNIX time for start of access
16273: 
16274:     value -> XML description of access control
16275:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
16276:             <start></start>
16277:             <end></end>
16278: 
16279:             <password></password>  for scope type = guest
16280: 
16281:             <domain></domain>     for scope type = course or group
16282:             <number></number>
16283:             <roles id="">
16284:              <role></role>
16285:              <access></access>
16286:              <section></section>
16287:              <group></group>
16288:             </roles>
16289: 
16290:             <dom></dom>         for scope type = domains
16291: 
16292:             <users>             for scope type = users
16293:              <user>
16294:               <uname></uname>
16295:               <udom></udom>
16296:              </user>
16297:             </users>
16298:            </scope> 
16299:               
16300:  Access data is also aggregated for each file in an additional key=value pair:
16301:  key -> path to file/file_name\0accesscontrol 
16302:  value -> reference to hash
16303:           hash contains key = value pairs
16304:           where key = uniqueID:scope_end_start
16305:                 value = UNIX time record was last updated
16306: 
16307:           Used to improve speed of look-ups of access controls for each file.  
16308:  
16309:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
16310: 
16311: =item *
16312: 
16313: modify_access_controls():
16314: 
16315: Modifies access controls for a portfolio file
16316: Args
16317: 1. file name
16318: 2. reference to hash of required changes,
16319: 3. domain
16320: 4. username
16321:   where domain,username are the domain of the portfolio owner 
16322:   (either a user or a course) 
16323: 
16324: Returns:
16325: 1. result of additions or updates ('ok' or 'error', with error message). 
16326: 2. result of deletions ('ok' or 'error', with error message).
16327: 3. reference to hash of any new or updated access controls.
16328: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
16329:    key = integer (inbound ID)
16330:    value = uniqueID
16331: 
16332: =item *
16333: 
16334: get_timebased_id():
16335: 
16336: Attempts to get a unique timestamp-based suffix for use with items added to a 
16337: course via the Course Editor (e.g., folders, composite pages, 
16338: group bulletin boards).
16339: 
16340: Args: (first three required; six others optional)
16341: 
16342: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
16343:    docssequence, or name of group
16344: 
16345: 2. keyid (alphanumeric): name of temporary locking key in hash,
16346:    e.g., num, boardids
16347: 
16348: 3. namespace: name of gdbm file used to store suffixes already assigned;  
16349:    file will be named nohist_namespace.db
16350: 
16351: 4. cdom: domain of course; default is current course domain from %env
16352: 
16353: 5. cnum: course number; default is current course number from %env
16354: 
16355: 6. idtype: set to concat if an additional digit is to be appended to the 
16356:    unix timestamp to form the suffix, if the plain timestamp is already
16357:    in use.  Default is to not do this, but simply increment the unix 
16358:    timestamp by 1 until a unique key is obtained.
16359: 
16360: 7. who: holder of locking key; defaults to user:domain for user.
16361: 
16362: 8. locktries: number of attempts to obtain a lock (sleep of 1s before 
16363:    retrying); default is 3.
16364: 
16365: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.  
16366: 
16367: Returns:
16368: 
16369: 1. suffix obtained (numeric)
16370: 
16371: 2. result of deleting locking key (ok if deleted, or lock never obtained)
16372: 
16373: 3. error: contains (localized) error message if an error occurred.
16374: 
16375: 
16376: =back
16377: 
16378: =head2 HTTP Helper Routines
16379: 
16380: =over 4
16381: 
16382: =item *
16383: 
16384: escape() : unpack non-word characters into CGI-compatible hex codes
16385: 
16386: =item *
16387: 
16388: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
16389: 
16390: =back
16391: 
16392: =head1 PRIVATE SUBROUTINES
16393: 
16394: =head2 Underlying communication routines (Shouldn't call)
16395: 
16396: =over 4
16397: 
16398: =item *
16399: 
16400: subreply() : tries to pass a message to lonc, returns con_lost if incapable
16401: 
16402: =item *
16403: 
16404: reply() : uses subreply to send a message to remote machine, logs all failures
16405: 
16406: =item *
16407: 
16408: critical() : passes a critical message to another server; if cannot
16409: get through then place message in connection buffer directory and
16410: returns con_delayed, if incapable of saving message, returns
16411: con_failed
16412: 
16413: =item *
16414: 
16415: reconlonc() : tries to reconnect lonc client processes.
16416: 
16417: =back
16418: 
16419: =head2 Resource Access Logging
16420: 
16421: =over 4
16422: 
16423: =item *
16424: 
16425: flushcourselogs() : flush (save) buffer logs and access logs
16426: 
16427: =item *
16428: 
16429: courselog($what) : save message for course in hash
16430: 
16431: =item *
16432: 
16433: courseacclog($what) : save message for course using &courselog().  Perform
16434: special processing for specific resource types (problems, exams, quizzes, etc).
16435: 
16436: =item *
16437: 
16438: goodbye() : flush course logs and log shutting down; it is called in srm.conf
16439: as a PerlChildExitHandler
16440: 
16441: =back
16442: 
16443: =head2 Other
16444: 
16445: =over 4
16446: 
16447: =item *
16448: 
16449: symblist($mapname,%newhash) : update symbolic storage links
16450: 
16451: =back
16452: 
16453: =cut
16454: 

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